Manuale PHP

Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Philip Olson
Georg Richter
Damien Seguy
Jakub Vrana
E diversi altri

A cura di

Gabor Hojtsy

A cura di

Luca Perugini
Simone Cortesi
Marco Cucinato
Darvin Andrioli
Tradotto con la collaborazione di:
Massimo Colombo
Marco De Nittis
Fabio Gandola
Sergio Marchesini
Alan D'Angelo
Giacomo Tesio
Marco Spisto
Gabriele Scaroni
Mariano Calandra
Rocco Curcio
Luca Costantino
Fernando Fusano
Andrea Paramithiotti

2005-10-26

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


Sommario
Prefazione
Authors and Contributors
I. Guida Rapida
1. Introduzione
2. Una semplice introduzione
II. Installazione e configurazione
3. General Installation Considerations
4. Installation on Unix systems
5. Installation on Mac OS X
6. Installation on Windows systems
7. Installation of PECL extensions
8. Problems?
9. Runtime Configuration
III. Struttura del Linguaggio
10. Sintassi Fondamentale
11. Types
12. Variables
13. Costanti
14. Expressions
15. Operatori
16. Strutture di controllo
17. Funzioni
18. Classi e Oggetti (PHP 4)
19. Classes and Objects (PHP 5)
20. Exceptions
21. Spiegazioni sui riferimenti
IV. Security
22. Introduction
23. General considerations
24. Installed as CGI binary
25. Installed as an Apache module
26. Filesystem Security
27. Database Security
28. Error Reporting
29. Using Register Globals
30. User Submitted Data
31. Magic Quotes
32. Hiding PHP
33. Keeping Current
V. Caratteristiche
34. Autenticazione HTTP usando PHP
35. Cookies
36. Sessions
37. Dealing with XForms
38. Caricare file
39. Utilizzo di file remoti
40. Gestione della connessione
41. Connessioni Persistenti ai Database
42. Modalità sicura (Safe mode)
43. Utilizzo di PHP da linea di comando
VI. Guida Funzioni
I. Funzioni .NET
II. Funzioni Apache
III. Alternative PHP Cache
IV. Advanced PHP debugger
V. Funzioni di Array
VI. Funzioni Aspell [deprecated]
VII. Funzioni Matematiche BCMath a precisione arbitraria
VIII. PHP bytecode Compiler
IX. Funzioni di compressione Bzip2
X. Funzioni Calendar
XI. Funzioni API CCVS [deprecate]
XII. Funzioni per Classi/Oggetti
XIII. Classkit Functions
XIV. Funzioni ClibPDF
XV. Funzioni di supporto COM per Windows
XVI. Funzioni di Crack
XVII. Funzioni di tipo dei caratteri
XVIII. Funzioni CURL, Client URL Library
XIX. Funzioni di pagamento Cybercash
XX. Crédit Mutuel CyberMUT functions
XXI. Funzioni di amministrazione Cyrus IMAP
XXII. Funzioni di Data e Ora
XXIII. DB++ Functions
XXIV. Database (dbm-style) Abstraction Layer Functions
XXV. Funzioni dBase
XXVI. Funzioni DBM
XXVII. dbx Functions
XXVIII. Funzioni per l'IO diretto
XXIX. Funzioni per le directory
XXX. DOM Functions
XXXI. Funzioni DOM XML
XXXII. Funzioni di gestione degli errori e di logging
XXXIII. Exif Functions
XXXIV. Expect Functions
XXXV. File Alteration Monitor Functions
XXXVI. Funzioni Forms Data Format
XXXVII. Funzioni filePro
XXXVIII. Filesystem Functions
XXXIX. Funzioni Firebird/InterBase
XL. Firebird/Interbase Functions (PDO_FIREBIRD)
XLI. Funzioni FriBiDi
XLII. FrontBase Functions
XLIII. Funzioni FTP
XLIV. Function Handling Functions
XLV. Gettext
XLVI. Funzioni GMP
XLVII. Net_Gopher
XLVIII. Funzioni HTTP
XLIX. Hyperwave Functions
L. Hyperwave API Functions
LI. IBM DB2, Cloudscape and Apache Derby Functions
LII. ICAP Functions [deprecated]
LIII. Iconv
LIV. ID3 Functions
LV. Funzioni di Amministrazione IIS
LVI. Funzioni per le immagini
LVII. IMAP, POP3 and NNTP Functions
LVIII. Informix Functions
LIX. Ingres II Functions
LX. IRC Gateway Functions
LXI. PHP / Java Integration
LXII. KADM5
LXIII. LDAP Functions
LXIV. libxml Functions
LXV. Lotus Notes Functions
LXVI. Funzioni LZF
LXVII. Funzioni di Mail
LXVIII. mailparse Functions
LXIX. Funzioni Matematiche
LXX. MaxDB PHP Extension
LXXI. MCAL Functions
LXXII. Mcrypt Encryption Functions
LXXIII. MCVE Payment Functions
LXXIV. Memcache Functions
LXXV. Mhash Functions
LXXVI. Mimetype Functions
LXXVII. Ming functions for Flash
LXXVIII. Miscellaneous Functions
LXXIX. mnoGoSearch Functions
LXXX. Funzioni per Microsoft SQL Server
LXXXI. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
LXXXII. Mohawk Software Session Handler Functions
LXXXIII. mSQL Functions
LXXXIV. Multibyte String Functions
LXXXV. muscat Functions
LXXXVI. MySQL Functions
LXXXVII. MySQL Functions (PDO_MYSQL)
LXXXVIII. MySQL Improved Extension
LXXXIX. Ncurses Terminal Screen Control Functions
XC. Funzioni di rete
XCI. Newt Functions
XCII. NSAPI-specific Functions
XCIII. Object Aggregation/Composition Functions
XCIV. Proprietà object e method call overloading
XCV. Funzioni Oracle 8
XCVI. Funzioni ODBC (Unificate)
XCVII. ODBC and DB2 functions (PDO_ODBC)
XCVIII. oggvorbis
XCIX. OpenAL Audio Bindings
C. OpenSSL Functions
CI. Funzioni Oracle
CII. Oracle Functions (PDO_OCI)
CIII. Output Control Functions
CIV. Ovrimos SQL Functions
CV. Paradox File Access
CVI. Parsekit Functions
CVII. Process Control Functions
CVIII. Funzioni per le espressioni regolari (Perl compatibili)
CIX. PDF functions
CX. PDO Functions
CXI. PHP Opzioni&Informazioni
CXII. Funzioni POSIX
CXIII. Funzioni per le espressioni regolari (POSIX estesa)
CXIV. Funzioni PostgreSQL
CXV. PostgreSQL Functions (PDO_PGSQL)
CXVI. Funzioni per le Stampanti
CXVII. Funzioni per l'esecuzione di programmi
CXVIII. PostScript document creation
CXIX. Pspell Functions
CXX. Funzioni qtdom
CXXI. Radius
CXXII. Rar Functions
CXXIII. GNU Readline
CXXIV. GNU Recode Functions
CXXV. RPM Header Reading Funzioni
CXXVI. runkit Functions
CXXVII. Satellite CORBA client extension [deprecated]
CXXVIII. SDO Functions
CXXIX. SDO XML Data Access Service Functions
CXXX. SDO Relational Data Access Service Functions
CXXXI. Funzioni per i semafori, la memoria condivisa ed IPC
CXXXII. SESAM Database Functions
CXXXIII. PostgreSQL Session Save Handler
CXXXIV. Funzioni di gestione della sessione
CXXXV. Funzioni relative alla memoria condivisa
CXXXVI. SimpleXML functions
CXXXVII. Funzioni per SNMP
CXXXVIII. SOAP Functions
CXXXIX. Funzioni relative ai Socket
CXL. Standard PHP Library (SPL) Functions
CXLI. SQLite
CXLII. SQLite Functions (PDO_SQLITE)
CXLIII. Secure Shell2 Functions
CXLIV. Stream Functions
CXLV. Stringhe
CXLVI. Shockwave Flash Functions
CXLVII. Sybase Functions
CXLVIII. TCP Wrappers Functions
CXLIX. Tidy Functions
CL. Tokenizer Functions
CLI. Unicode Functions
CLII. URL Functions
CLIII. Funzioni per la gestione delle variabili
CLIV. Verisign Payflow Pro Functions
CLV. Funzioni vpopmail
CLVI. Funzioni W32api
CLVII. WDDX Functions
CLVIII. win32service Functions
CLIX. xattr Functions
CLX. xdiff Functions
CLXI. Funzioni relative al parser XML
CLXII. Funzioni XML-RPC
CLXIII. XMLReader functions
CLXIV. XSL functions
CLXV. Funzioni XSLT
CLXVI. YAZ Functions
CLXVII. YP/NIS Functions
CLXVIII. Funzioni per File Zip (Accesso di Sola Lettura)
CLXIX. Funzioni di compressione Zlib
VII. PHP and Zend Engine Internals
44. Streams API for PHP Extension Authors
45. PDO Driver How-To
46. Zend API: Hacking the Core of PHP
47. Extending PHP 3
VIII. FAQ: Frequently Asked Questions (domande e risposte ricorrenti)
48. Informazioni Generali
49. Mailing list
50. Ottenere PHP
51. Database issues
52. Installazione
53. Problemi di installazione
54. Using PHP
55. PHP and HTML
56. PHP e COM
57. PHP e gli altri linguaggi di programmazione
58. Migrazione da PHP 2 a PHP 3
59. Migrazione da PHP3 a PHP4
60. Migrating from PHP 4 to PHP 5
61. Domande varie
IX. Appendici
A. History of PHP and related projects
B. Migrating from PHP 4 to PHP 5
C. Migrating from PHP 3 to PHP 4
D. Migrazione da PHP/FI 2 a PHP 3
E. Debugging PHP
F. Configure options
G. Impostazioni del php.ini
H. List of Supported Timezones
I. Extension Categorization
J. Lista dei sinonimi delle funzioni PHP
K. Parole riservate nel PHP
L. List of Resource Types
M. List of Supported Protocols/Wrappers
N. List of Available Filters
O. List of Supported Socket Transports
P. PHP type comparison tables
Q. List of Parser Tokens
R. Informazioni sul manuale
S. Open Publication License
T. Indice delle Funzioni
U. Informazioni mancanti

Prefazione

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.


Authors and Contributors

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.


Authors and Editors

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.


User Note Maintainers

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.

I. Guida Rapida


Capitolo 1. Introduzione

Che cos'è il PHP?

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:

Esempio 1-1. Un esempio introduttivo

<html>
    <head>
        <title>Esempio</title>
    </head>
    <body>

        <?php 
        echo "Ciao, sono uno script PHP!"; 
        ?>

    </body>
</html>

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.


Che cosa può fare PHP?

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:

Adabas DInterBasePostgreSQL
dBaseFrontBaseSQLite
EmpressmSQLSolid
FilePro (read-only)Direct MS-SQLSybase
HyperwaveMySQLVelocis
IBM DB2ODBCUnix dbm
InformixOracle (OCI7 and OCI8) 
IngresOvrimos 

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.

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


Capitolo 2. Una semplice introduzione

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.


Di cosa ho bisogno?

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.


La prima pagina PHP

Creare un file con nome ciao.php nella directory del web server che abbia il seguente contenuto:

Esempio 2-1. Il nostro primo script PHP: ciao.php

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

L'output di questo script sarà:
<html>
 <head>
  <title>Test PHP</title>
 </head>
 <body>
Hello World!<p>
 </body>
</html>

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.


Qualcosa di utile

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:

Esempio 2-2. Stampare video una variable (elemento d'Array)

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

L'output (risultato) di questo script potrebbe essere:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

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:

Esempio 2-3. Mostrare tutte le variabili predefinite di PHP con phpinfo()

<?php phpinfo(); ?>

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

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

L'output di esempio di questo script potrebbe essere:
Stai usando Internet Explorer<br />

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:

Esempio 2-5. Intercalare i modi PHP e HTML

<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
?>
<h3>strstr dovrebbe ritornare true</h3>
<center><b>Stai usando Internet Explorer</b></center>
<?php
} else {
?>
<h3>strstr dovrebbe ritornare false</h3>
<center><b>Non stai usando Internet Explorer</b></center>
<?php
}
?>

L'output di esempio di questo script potrebbe essere:
<h3>strstr dovrebbe ritornare true</h3>
<center><b>Stai usando Internet Explorer</b></center>

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.


Trattare con i Form

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:

Esempio 2-6. Un semplice form HTML

<form action="action.php" method="POST">
 Il tuo Nome: <input type="text" name="name" value="" />
 La tua et&agrave;: <input type="text" name="age" value ="" />
 <input type="submit">
</form>

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:

Esempio 2-7. La stampa video di dati dal nostro form

Ciao <?php echo $_POST["name"]; ?>.
La tua età è di <?php echo $_POST["age"]; ?> anni.

Ecco un possibile output di questo script:
Ciao Joe.
La tua et&agrave; &egrave; di 22 anni.

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


L' uso di vecchi codici con le nuove versioni di PHP

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.

Per ulteriori dettagli su queste innovazioni, vedere la sezione sulle variabili predefinite ed i links ad essa connessi.


E poi?

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.


Capitolo 3. General Installation Considerations

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.


Capitolo 4. Installation on Unix systems

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

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.


Apache 1.3.x on Unix systems

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

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

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 1 and MySQL support.  Your
    path to apxs may differ from our example.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to 
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
  
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

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

    You may edit your .ini file to set PHP options.  If you prefer your
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10. 
    
    If you instead choose php.ini-recommended, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.
        
    For PHP 4:
            
      LoadModule php4_module libexec/libphp4.so

    For PHP 5:
                      
      LoadModule php5_module libexec/libphp5.so
      
15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:
    
    For PHP 4:
    
      AddModule mod_php4.c
      
    For PHP 5:
    
      AddModule mod_php5.c

16. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.

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

    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
    
      AddType application/x-httpd-php-source .phps

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

Alternatively, to install PHP as a static object:

Esempio 4-2. Installation Instructions (Static Module Installation for Apache) for PHP

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-4.x.y.tar.gz | tar xf -
6.  cd php-4.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php4/libphp4.a
    (The above line is correct! Yes, we know libphp4.a does not exist at this
    stage. It isn't supposed to. It will be created.)

12. make
    (you should now have an httpd binary which you can copy to your Apache bin dir if
    it is your first install then you need to "make install" as well)

13. cd ../php-4.x.y
14. cp php.ini-dist /usr/local/lib/php.ini

15. You can edit /usr/local/lib/php.ini file to set PHP options.
    Edit your httpd.conf or srm.conf file and add:
    AddType application/x-httpd-php .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

1. Several Linux and SysV variants:
/etc/rc.d/init.d/httpd restart

2. Using apachectl scripts:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Using mod_ssl, or another SSL server, you may want to manually
stop and start:
/path/to/apachectl stop
/path/to/apachectl startssl

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:

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

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.

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

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.

./configure --with-apache=/path/to/apache_source --with-pgsql

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.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

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:

User nobody
Group "#-1"

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.


Apache 2.0 on Unix systems

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.

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)

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

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

9.  cd ../php-NN

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 2 and MySQL support.  Your
    path to apxs may differ, in fact, the binary may even be named apxs2 on
    your system. 
    
      ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
                
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.
    
13. Setup your php.ini 
    
    cp php.ini-dist /usr/local/lib/php.ini
          
    You may edit your .ini file to set PHP options.  If you prefer having
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10.
    
    If you instead choose php.ini-recommended, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.

    For PHP 4:
  
      LoadModule php4_module modules/libphp4.so
      
    For PHP 5:
    
      LoadModule php5_module modules/libphp5.so
 
15. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.
            
      AddType application/x-httpd-php .php .phtml
                  
    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
    
      AddType application/x-httpd-php-source .phps
 
16. Use your normal procedure for starting the Apache server, e.g.:
   
      /usr/local/apache2/bin/apachectl start

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

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


Caudium

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

Esempio 4-5. Caudium Installation Instructions

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

You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the 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.


fhttpd related notes

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.


Sun, iPlanet and Netscape servers on Sun Solaris

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.

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

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

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

  4. tar xvf php-x.x.x.tar

  5. Change to your extracted PHP directory: cd ../php-x.x.x

  6. For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
    ./configure --with-mysql=/usr/local/mysql \
    --with-nsapi=/opt/netscape/suitespot/ \
    --enable-libgcc

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

  1. Add the following line to mime.types (you can do that by the administration server):
    type=magnus-internal/x-httpd-php exts=php

  2. 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"]
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your webserver config directory.

  3. 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>
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  4. 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>
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

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

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


CGI environment and recommended modifications in php.ini

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


Special use for error pages or self-made directory listings (PHP >= 4.3.3)

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...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

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...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].


Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

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


CGI and commandline setups

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.


Testing

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


Benchmarking

If you have built PHP 3 as a CGI program, you may benchmark your build by typing make bench. Note that if 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.


Using Variables

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


HP-UX specific installation notes

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.

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

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

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

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

  5. You now need flex, you need to download the source from one of the http://www.gnu.org mirrors. It is in the 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.

  6. Download the PHP and apache sources.

  7. gunzip and tar -xvf them. We need to hack a couple of files so that they can compile OK.

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

  9. Next, the Apache GuessOS file needs to be hacked. Under apache_1.3.9/src/helpers change line 89 from echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 to: echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0

  10. You cannot install PHP as a shared object under HP-UX so you must compile it as a static, just follow the instructions at the Apache page.

  11. PHP and Apache should have compiled OK, but Apache won't start. you need to create a new user for Apache, 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.


OpenBSD installation notes

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


Using Binary Packages

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

The main package you need to install is php4-core-4.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

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

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


Using Ports

You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The 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.


Common Problems

  • 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

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


Solaris specific installation tips

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


Required software

Solaris installs often lack C compilers and their related tools. 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

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


Using Packages

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


Gentoo installation notes

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


Using Portage (emerge)

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

# emerge \<apache-2
# USE="-*" emerge php mod_php
# ebuild /var/db/pkg/dev-php/mod_php-<your PHP version>/mod_php-<your PHP version>.ebuild config
# nano /etc/conf.d/apache
  Add "-D PHP4" to APACHE_OPTS
  
# rc-update add apache default
# /etc/init.d/apache start

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.


Better control on configuration

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

# USE="-*" emerge -pv php

[ebuild  N    ] dev-php/php-4.3.6-r1  -X -berkdb -crypt -curl -debug -doc 
-fdftk -firebird -flash -freetds -gd -gd-external -gdbm -gmp -hardenedphp 
-imap -informix -ipv6 -java -jpeg -kerberos -ldap -mcal -memlimit -mssql 
-mysql -ncurses -nls -oci8 -odbc -pam -pdflib -png -postgres -qt -readline 
-snmp -spell -ssl -tiff -truetype -xml2 -yaz  3,876 kB

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:

Esempio 4-9. Install PHP with USE flags

# USE="-* curl mysql gd" emerge php mod_php

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.


Common Problems

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


Debian GNU/Linux installation notes

This section contains notes and hints specific to installing PHP on Debian GNU/Linux.


Using APT

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 :

Esempio 4-10. The two Dotdeb related lines

deb http://packages.dotdeb.org stable all
deb-src http://packages.dotdeb.org stable all

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:

Esempio 4-11. Debian Install Example with Apache 1.3

# apt-get install libapache-mod-php4

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 :

Esempio 4-12. Stopping and starting Apache once PHP 4 is installed

# /etc/init.d/apache stop
# /etc/init.d/apache start

Better control on configuration

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

Esempio 4-13. Getting the list of PHP additional packages

# dpkg -l 'php4-*'

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:

Esempio 4-14. Install PHP with MySQL, cURL and GD

# apt-get install php4-mysql php4-curl php4-gd

APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).

Esempio 4-15. These lines activate MySQL, cURL and GD into PHP

extension=mysql.so
extension=curl.so
extension=gd.so

You'll only have to stop/start Apache as previously to activate the modules.


Common Problems

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

    Esempio 4-16. This line activates PHP 4 into Apache

    # Include /etc/apache/conf.d/
  • 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.


Capitolo 5. Installation on Mac OS X

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.


Using Packages

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


Compiling for OS X Server

Mac OS X Server install.

  1. Get the latest distributions of Apache and PHP.

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

  3. If you want the compiler to do some optimization, you may also want to add this line:
    setenv OPTIM=-O2

  4. Next, go to the PHP 4 source directory and configure it.
    ./configure --prefix=/usr \
        --sysconfdir=/etc \
        --localstatedir=/var \
        --mandir=/usr/share/man \
        --with-xml \
        --with-apache=/src/apache_1.3.12
    If you have any other additions (MySQL, GD, etc.), be sure to add them here. For the --with-apache string, put in the path to your apache source directory, for example /src/apache_1.3.12.

  5. Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.

  6. Now, reconfigure Apache to build in PHP 4.
    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache \
    --activate-module=src/modules/php4/libphp4.a
    You may get a message telling you that libmodphp4.a is out of date. If so, go to the src/modules/php4 directory inside your Apache source directory and run this command: ranlib libmodphp4.a. Then go back to the root of the Apache source directory and run the above configure command again. That'll bring the link table up to date. Run make and make install again.

  7. Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini.


Compiling for MacOS X Client

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:

  1. Open a terminal window.

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

  3. Type gunzip libphp4.so.gz.

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

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

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


Capitolo 6. Installation on Windows systems

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.


Windows Installer

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.


Manual Installation Steps

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

c:\php
   |
   +--cli
   |  |
   |  |-php.exe           -- CLI executable - ONLY for commandline scripting
   |
   +--dlls                -- support DLLs required by some extensions
   |  |
   |  |-expat.dll
   |  |
   |  |-fdftk.dll
   |  |
   |  |-...
   |
   +--extensions          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-..
   |
   +--mibs                -- support files for SNMP
   |
   +--openssl             -- support files for Openssl
   |
   +--pdf-related         -- support files for PDF
   |
   +--sapi                -- SAPI (server module support) DLLs
   |  |
   |  |-php4apache.dll
   |  |
   |  |-php4apache2.dll
   |  |
   |  |-..
   |
   +--PEAR                -- initial copy of PEAR
   |
   |
   |-go-pear.bat          -- PEAR setup script
   |
   |-..
   |
   |-php.exe              -- CGI executable
   |
   |-..
   |
   |-php.ini-dist         -- default php.ini settings
   |
   |-php.ini-recommended  -- recommended php.ini settings
   | 
   |-php4ts.dll           -- core PHP DLL
   | 
   |-...

Or:

Esempio 6-2. PHP 5 package structure

c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib
   |
   +--ext                 -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-..
   |
   +--extras
   |  |
   |  +--mibs             -- support files for SNMP
   |  |
   |  +--openssl          -- support files for Openssl
   |  |
   |  +--pdf-related      -- support files for PDF
   |  |
   |  |-mime.magic
   |
   +--pear                -- initial copy of PEAR
   |
   |
   |-go-pear.bat          -- PEAR setup script
   |
   |-fdftk.dll
   |
   |-..
   |
   |-php-cgi.exe          -- CGI executable
   |
   |-php-win.exe          -- executes scripts without an opened command prompt
   |
   |-php.exe              -- CLI executable - ONLY for command line scripting
   |
   |-..
   |
   |-php.ini-dist         -- default php.ini settings
   |
   |-php.ini-recommended  -- recommended php.ini settings
   | 
   |-php5activescript.dll
   |
   |-php5apache.dll
   |
   |-php5apache2.dll
   |
   |-..
   |
   |-php5ts.dll           -- core PHP DLL
   | 
   |-...

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:

    doc_root = c:\inetpub\wwwroot // for IIS/PWS
    
    doc_root = c:\apache\htdocs // for Apache

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


ActiveScript

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>
Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.

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.


Microsoft IIS / PWS

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.


General considerations for all installations of PHP with IIS

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


Windows NT/200x/XP and IIS 4 or newer

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.


Windows and PWS 4

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.


Windows and PWS/IIS 3

The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg 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.


Apache 1.3.x on Microsoft Windows

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.


Installing as an Apache module

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:

# Add to the end of the LoadModule section
# Don't forget to copy this file from the sapi directory!
LoadModule php4_module "C:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:

# Add to the end of the LoadModule section
LoadModule php5_module "C:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps


Installing as a CGI binary

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:

Esempio 6-4. PHP and Apache 1.3.x as CGI

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

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

# specify the directory where php.ini is
SetEnv PHPRC C:/php
Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.

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


Apache 2.0.x on Microsoft Windows

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.

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.


Installing as a CGI binary

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

Esempio 6-5. PHP and Apache 2.0 as CGI

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

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

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.


Installing as an Apache module

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

# For PHP 4 do something like this:
LoadModule php4_module "c:/php/php4apache2.dll"
# Don't forget to copy the php4apache2.dll file from the sapi directory!
AddType application/x-httpd-php .php

# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "C:/php"

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.


Sun, iPlanet and Netscape servers on Microsoft Windows

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.


CGI setup on Sun, iPlanet and Netscape servers

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


NSAPI setup on Sun, iPlanet and Netscape servers

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"]
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your webserver config directory.

  • 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 ...]
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  • 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>
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

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


CGI environment and recommended modifications in php.ini

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


Special use for error pages or self-made directory listings (PHP >= 4.3.3)

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...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

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...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].


Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

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"
where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

You can check the status by using the phpinfo() function.

Nota: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!


OmniHTTPd Server

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.

  1. Install OmniHTTPd server.

  2. Right click on the blue OmniHTTPd icon in the system tray and select Properties

  3. Click on Web Server Global Settings

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

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

  6. Click OK

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

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


Sambar Server on Microsoft Windows

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

    Esempio 6-7. ISAPI configuration of Sambar

    #for PHP 4
    *.php = c:\php\php4isapi.dll
    
    #for PHP 5
    *.php = c:\php\php5isapi.dll
    (This line assumes that PHP was installed in c:\php.)

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


Xitami on Microsoft Windows

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.


Building from source

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.


Requisiti

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:

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.


Putting it all together

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

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

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

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

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

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

Following this steps your directory structure looks like this:
+--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.


Build resolv.lib

You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release), 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"

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


Building PHP using the new build system [PHP >=5 only]

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.


Building PHP using DSW files [PHP 4]

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.


Configure MVC ++

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


Compiling

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

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

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

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

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

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

It is possible to do minor customization to the build process by editing the main/config.win32.h 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.


Installation of extensions on Windows

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:

    extension_dir = C:\php\extensions

  • 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

    // change the following line from ...
    ;extension=php_bz2.dll
    
    // ... to
    extension=php_bz2.dll

  • 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

ExtensionDescriptionNotes
php_bz2.dllbzip2 compression functionsNone
php_calendar.dllCalendar conversion functionsBuilt in since PHP 4.0.3
php_cpdf.dllClibPDF functionsNone
php_crack.dllCrack functionsNone
php_ctype.dllctype family functionsBuilt in since PHP 4.3.0
php_curl.dllCURL, Client URL library functionsRequires: libeay32.dll, ssleay32.dll (bundled)
php_cybercash.dllCybercash payment functionsPHP <= 4.2.0
php_db.dllDBM functionsDeprecated. Use DBA instead (php_dba.dll)
php_dba.dllDBA: DataBase (dbm-style) Abstraction layer functionsNone
php_dbase.dlldBase functionsNone
php_dbx.dlldbx functions 
php_domxml.dllDOM XML functions PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled)
php_dotnet.dll.NET functionsPHP <= 4.1.1
php_exif.dllEXIF functions php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dllFrontBase functionsPHP <= 4.2.0
php_fdf.dllFDF: Forms Data Format functions.Requires: fdftk.dll (bundled)
php_filepro.dllfilePro functionsRead-only access
php_ftp.dllFTP functionsBuilt-in since PHP 4.0.3
php_gd.dllGD 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.dllGD library image functionsGD2
php_gettext.dllGettext functions PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dllHyperWave functionsNone
php_iconv.dllICONV characterset conversionRequires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll
php_ifx.dllInformix functionsRequires: Informix libraries
php_iisfunc.dllIIS management functionsNone
php_imap.dllIMAP POP3 and NNTP functionsNone
php_ingres.dllIngres II functionsRequires: Ingres II libraries
php_interbase.dllInterBase functionsRequires: gds32.dll (bundled)
php_java.dllJava functionsPHP <= 4.0.6 requires: jvm.dll (bundled)
php_ldap.dllLDAP functions PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled)
php_mbstring.dllMulti-Byte String functionsNone
php_mcrypt.dllMcrypt Encryption functionsRequires: libmcrypt.dll
php_mhash.dllMhash functionsPHP >= 4.3.0 requires: libmhash.dll (bundled)
php_mime_magic.dllMimetype functionsRequires: magic.mime (bundled)
php_ming.dllMing functions for FlashNone
php_msql.dllmSQL functionsRequires: msql.dll (bundled)
php_mssql.dllMSSQL functionsRequires: ntwdblib.dll (bundled)
php_mysql.dllMySQL functionsPHP >= 5.0.0, requires libmysql.dll (bundled)
php_mysqli.dllMySQLi functionsPHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dllOracle 8 functionsRequires: Oracle 8.1+ client libraries
php_openssl.dllOpenSSL functionsRequires: libeay32.dll (bundled)
php_oracle.dllOracle functionsRequires: Oracle 7 client libraries
php_overload.dllObject overloading functionsBuilt in since PHP 4.3.0
php_pdf.dllPDF functionsNone
php_pgsql.dllPostgreSQL functionsNone
php_printer.dllPrinter functionsNone
php_shmop.dllShared Memory functionsNone
php_snmp.dllSNMP get and walk functionsNT only!
php_soap.dllSOAP functionsPHP >= 5.0.0
php_sockets.dllSocket functionsNone
php_sybase_ct.dllSybase functionsRequires: Sybase client libraries
php_tidy.dllTidy functionsPHP >= 5.0.0
php_tokenizer.dllTokenizer functionsBuilt in since PHP 4.3.0
php_w32api.dllW32api functionsNone
php_xmlrpc.dllXML-RPC functionsPHP >= 4.2.1 requires: iconv.dll (bundled)
php_xslt.dllXSLT 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.dllYAZ functionsRequires: yaz.dll (bundled)
php_zip.dllZip File functionsRead only access
php_zlib.dllZLib compression functionsBuilt in since PHP 4.3.0


Capitolo 7. Installation of PECL extensions

Introduction to PECL Installations

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.


Downloading PECL extensions

There are several options for downloading PECL extensions, such as:

  • http://pecl.php.net

    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.


PECL for Windows users

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.


Compiling shared PECL extensions with PEAR

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


Compiling shared PECL extensions with phpize

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.


Compiling PECL extensions statically into PHP

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


Capitolo 8. Problems?

Read the FAQ

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


Other problems

If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on http://www.php.net/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.


Bug reports

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

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


Capitolo 9. Runtime Configuration

The configuration file

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

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:\php\lib"

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


How to change configuration settings

Running PHP as an Apache module

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

php_value name value

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.

php_flag name on|off

Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.

php_admin_value name value

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.

php_admin_flag name on|off

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

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

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


Changing PHP configuration via the Windows registry

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.


Other interfaces to PHP

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


Capitolo 10. Sintassi Fondamentale

Modi per uscire dalla modalità HTML

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:

Esempio 10-1. Escape avanzato

<?php
if ($expression) {
    ?>
    <strong>This is true.</strong>
    <?php
} else {
    ?>
    <strong>This is false.</strong>
    <?php
}
?>
Questo codice funziona come atteso, perchè quando il PHP trova il tag di chiusura ?>, inizia a visualizzare tutto ciò che incontra sino a quando non si raggiunge un'altro tag di apertura. L'esempio è semplificato, ovviamente, ma nella visualizzazzione di grossi blocchi di testo uscire dalla modalità di parsing del codice PHP è generalmente più efficiente che inviare il tutto tramite echo() o print().

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

1.  <?php echo 'se si vogliono produrre documenti XHTML o XML, si utilizzi questo modo'; ?>
2.  <script language="php">
        echo 'alcuni editor (tipo FrontPage) non 
               amano le istruzioni di elaborazione';
    </script>

3.  <? echo 'questo è il più semplice, ovvero come istruzione SGML'; ?>
    <?= espressione ?>  Questa è un'abbreviazione per "<? echo espressione ?>"
 

4.  <% echo 'Opzionalmente puoi utilizzare tag nello stile ASP'; %>
    <%= $variable; # Questo &egrave; una abbreviazione per "<% echo ..." %>

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.    


Separazione delle istruzioni

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.

<?php
    echo 'Questo &grave; un test';
?>
<?php echo 'Questo &grave; un test' ?>

Nota: Il tag di chiusura di un blocco PHP alla fine di un file è opzionale, ed in alcuni casi è utile non utilizzarlo soprattutto quando si utilizza l'output buffering e le funzioni include() o require().


Commenti

Il PHP supporta i commenti dei linguaggi 'C', 'C++' e stile shell (stile Perl) di Unix. Per esempio:

<?php
    echo 'Questo &grave; un test'; // Questo &egrave; un commento su una linea nella stile c++ 
    /* Questo &egrave; un commento su pi&ugrave; linee
       ancora un'altra linea di commento */
    echo 'Questo &egrave; un altro test';
    echo 'Un ultimo test'; # Questo &egrave; 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 &egrave; un <?# echo 'semplice';?> esempio.</h1>
<p>L'intestazione qui sopra dir&agrave; 'Questo &egrave; 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
 /* 
    echo 'Questo &egrave; un test'; /* Questo commento causer&agrave; dei problemi */
 */
?>


Capitolo 11. Types

Introduction

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.


Booleans

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.


Syntax

To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.

<?php
$foo = True; // assign the value TRUE to $foo
?>

Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.

<?php
// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
    echo "The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
    echo "<hr>\n";
}

// ...because you can simply type
if ($show_separators) {
    echo "<hr>\n";
}
?>


Converting to boolean

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:

Every other value is considered TRUE (including any resource).

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


Integers

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


Syntax

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.

Esempio 11-1. Integer literals

<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
?>
Formally the possible structure for integer literals is:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers.

Avvertimento

If an invalid digit is passed to octal integer (i.e. 8 or 9), the rest of the number is ignored.

Esempio 11-2. Octal weirdness

<?php
var_dump(01090); // 010 octal = 8 decimal
?>


Integer overflow

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.

<?php
var_dump(25/7);         // float(3.5714285714286) 
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4) 
?>


Converting to integer

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.


From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).


From floating point numbers

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.

<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See for more information the warning about float-precision.


From other types

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

Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:

<?php
$a = 1.234; 
$b = 1.2e3; 
$c = 7E-10;
?>

Formally:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).

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.


Converting to float

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.


Strings

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.


Syntax

A string literal can be specified in three different ways.


Single quoted

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


Double quoted

If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

Tabella 11-1. Escaped characters

sequencemeaning
\nlinefeed (LF or 0x0A (10) in ASCII)
\rcarriage return (CR or 0x0D (13) in ASCII)
\thorizontal 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.


Heredoc

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.

Esempio 11-3. Invalid example

<?php
class foo {
    public $bar = <<<EOT
bar
EOT;
}
?>

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

<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var $foo;
    var $bar;

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

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

Nota: Heredoc support was added in PHP 4.


Variable parsing

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.


Simple syntax

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.


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


String access and modification by character

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

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str{0};

// Get the third character of a string
$third = $str{2};

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str{strlen($str)-1}; 

// Modify the last character of a string
$str = 'Look at the sea';
$str{strlen($str)-1} = 'e';
          
?>


Useful functions and operators

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.


Converting to string

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.


String conversion to numbers

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:

<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>

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.


Arrays

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.


Syntax

Specifying with array()

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

<?php
$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12];    // 1
?>

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.


Creating/modifying with square-bracket syntax

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
If $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it.

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


Useful functions

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

<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.


Array do's and don'ts

Why is $foo[bar] wrong?

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:

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>

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:

<?php
echo $arr[somefunc($bar)];
?>

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

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

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

because E_ERROR equals 1, etc.

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.


So why is it bad then?

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.


Converting to array

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.


Comparing

It is possible to compare arrays by array_diff() and by Array operators.


Examples

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

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              'OS'         => 'Linux',
              'lang'       => 'english',
              'short_tags' => true
            );
            
// strictly numerical keys
$array = array( 7,
                8,
                0,
                156,
                -10
              );
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    5    =>  6,
                    3    =>  7, 
                    'a'  =>  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =>  2, // key = 8 (integer!)
                    '02' => 77, // key = '02'
                    0    => 12  // the value 10 will be overwritten by 12
                  );
                  
// empty array
$empty = array();         
?>

Esempio 11-7. Collection

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

?>

Il precedente esempio visualizzerà:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing values of the array directly is possible since PHP 5 by passing them as reference. Prior versions need workaround:

Esempio 11-8. Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    $color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    $colors[$key] = strtoupper($color);
}

print_r($colors);
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Esempio 11-9. One-based index

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

Il precedente esempio visualizzerà:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Esempio 11-10. Filling an array

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;
}
closedir($handle); 
?>

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.

Esempio 11-11. Sorting an array

<?php
sort($files);
print_r($files);
?>

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

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above 
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"; 
?>

You should be aware that array assignment always involves value copying. You need to use the reference operator to copy an array by reference.

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)
             
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


Objects

Object Initialization

To initialize an object, you use the new statement to instantiate the object to a variable.

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, please read the section Classes and Objects.


Converting to object

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.

<?php
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
?>


Resource

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


Converting to resource

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.


Freeing resources

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.


NULL

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


Syntax

There is only one value of type NULL, and that is the case-insensitive keyword NULL.

<?php
$var = NULL;       
?>

See also is_null() and unset().


Pseudo-types used in this documentation

mixed

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.


number

number indicates that a parameter can be either integer or float.


callback

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 
// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod')); 

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>


Type Juggling

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.

<?php
$a = "1";     // $a is a string
$a[0] = "f";  // What about string offsets? What happens?
?>

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:

<?php
$a    = "abc"; // $a is a string
$a{1} = "f";   // $a is now "afc"
?>

See the section titled String access by character for more information.


Type Casting

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.

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

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:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

Nota: Instead of casting a variable to string, you can also enclose the variable in double quotes.

<?php
$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo "they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:


Capitolo 12. Variables

Basics

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
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>


Predefined variables

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

$GLOBALS

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.

$_SERVER

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

$_GET

Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST

Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE

Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES

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.

$_ENV

Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST

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.

$_SESSION

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.


Variable scope

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:

<?php
$a = 1;
include 'b.inc';
?>

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.


The global keyword

First, an example use of global:

Esempio 12-1. Using global

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b;
?>

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:

Esempio 12-2. Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
} 

Sum();
echo $b;
?>

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

<?php
function test_global()
{
    // Most predefined variables aren't "super" and require 
    // 'global' to be available to the functions local scope.
    global $HTTP_POST_VARS;
    
    echo $HTTP_POST_VARS['name'];
    
    // Superglobals are available in any scope and do 
    // not require 'global'. Superglobals are available 
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    echo $_POST['name'];
}
?>


Using static variables

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:

Esempio 12-4. Example demonstrating need for static variables

<?php
function Test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

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:

Esempio 12-5. Example use of static variables

<?php
function Test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

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:

Esempio 12-6. Static variables with recursive functions

<?php
function Test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        Test();
    }
    $count--;
}
?>

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.

Esempio 12-7. Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct 
    static $int = 1+2;        // wrong  (as it is an expression)
    static $int = sqrt(121);  // wrong  (as it is an expression too)

    $int++;
    echo $int;
}
?>


References with global and static variables

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.


Variable variables

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:

<?php
$a = 'hello';
?>

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.

<?php
$$a = 'world';
?>

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:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

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.


Variables from outside PHP

HTML Forms (GET and POST)

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:

Esempio 12-8. A simple HTML form

<form action="foo.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

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

<?php 
// Available since PHP 4.1.0

   echo $_POST['username'];
   echo $_REQUEST['username'];

   import_request_variables('p', 'p_');
   echo $p_username;

// Available since PHP 3. As of PHP 5.0.0, these long predefined
// variables can be disabled with the register_long_arrays directive.

   echo $HTTP_POST_VARS['username'];

// Available if the PHP directive register_globals = on. As of 
// PHP 4.2.0 the default value of register_globals = off.
// Using/relying on this method is not preferred.

   echo $username;
?>

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

<?php
if (isset($_POST['action']) && $_POST['action'] == 'submitted') {
    echo '<pre>';
    print_r($_POST);
    echo '<a href="'. $_SERVER['PHP_SELF'] .'">Please try again</a>';

    echo '</pre>';
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Beer: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="hidden" name="action" value="submitted" />
    <input type="submit" name="submit" value="submit me!" />
</form>
<?php
}
?>

In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such restriction applies.


IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" src="image.gif" name="sub" />

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.


HTTP Cookies

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

<?php
if (isset($_COOKIE['count'])) {
    $count = $_COOKIE['count'] + 1;
} else {
    $count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

Dots in incoming variable names

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 */
?>
Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.


Determining variable types

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.


Capitolo 13. Costanti

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

<?php
// Nomi validi
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more")
 
// Nomi di costante errati
define("2FOO",    "something");
	 
// Nomi validi, ma da evitare:
// un domani potrebbero essere utilizzati dal PHP per fornire costanti magiche
// e quindi si avrebbero problemi nello script
define("__FOO__", "something"); 
?>

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.


Sintassi

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

Esempio 13-2. Definizione di costanti

<?php
define("COSTANTE", "Ciao mondo.");
echo COSTANTE; // stampa "Ciao mondo."
echo Costante; // stampa "Costante" e genera una notice.
?>


Costanti magiche

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

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


Capitolo 14. Expressions

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:

<?php
function foo ()
{
    return 5;
}
?>

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:

<?php
$first ? $second : $third
?>

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.


Capitolo 15. Operatori

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.


Precedenza degli operatori

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àOperatoriInformazioni aggiuntive
non associativinewnew
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
sinistraand operatori logici
sinistraxor operatori logici
sinistraor 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.

Esempio 15-1. Associatività

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
 
$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
Utilizzare le parentesi per aumentare la leggibilità del codice.

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.


Operatori aritmetici

Ricordate l'aritmetica di base dalla scuola? Questi funzionano proprio come quelli.

Tabella 15-2. Operatori aritmetici

EsempioNomeRisultato
-$aNegazioneOpposto di $a.
$a + $bAddizioneLa somma di $a e $b.
$a - $bSottrazioneLa differenza di $a e $b.
$a * $bMoltiplicazioneil prodotto di $a e $b.
$a / $bDivisioneQuoziente di $a e $b.
$a % $bModuloIl 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.


Operatori di assegnazione

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:

<?php
$a = ($b = 4) + 5; // $a è uguale a 9 ora, e $b è stato impostato a 4.
?>

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.


Operatori bitwise

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

EsempioNomeRisultato
$a & $bAndSono impostati ad ON i bit che sono ON sia in $a che in $b.
$a | $bOrSono impostati ad ON i bit che sono ON in $a oppure in $b.
$a ^ $bXor Sono impostati ad ON i bit che sono ON in $a oppure in $b na non quelli che sono entrambi ON.
~ $aNot Sono impostati ad ON i bit che sono OFF in $a, e viceversa.
$a << $bShift left Sposta i bit di $a a sinistra di $b passi (ogni passo significa "moltiplica per due")
$a >> $bShift 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.


Operatori di confronto

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

EsempioNomeRisultato
$a == $bUgualeTRUE se $a è uguale a $b.
$a === $bIdentico TRUE se $a è uguale a $b, ed essi sono dello stesso tipo. (Dal PHP 4)
$a != $bDiversiTRUE se $a è diverso da $b.
$a <> $bDiversiTRUE se $a è diverso da $b.
$a !== $bNon identici TRUE se $a è diverso da $b, o se essi non sono dello stesso tipo. (Dal PHP 4)
$a < $bMinoreTRUE se $a è strettamente minore di $b.
$a > $bMaggioreTRUE se $a è strettamente maggiore di $b.
$a <= $bMinore o ugualeTRUE se $a è minore o uguale a $b.
$a >= $bMaggiore o ugualeTRUE 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 1Tipo dell'operando 2Risultato
null oppure stringstringSi converte NULL in "", confronto numerico o lessicale
bool oppure nullqualsiasiConvertito in bool, FALSE < TRUE
objectobjectLe 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 numberstring, resource oppure numberStringhe e risorse sono converti in numeri, confronto matematico
arrayarrayLa 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)
arrayqualsiasiarray è sempre più grande
objectqualsiasiobject è sempre più grande

Esempio 15-2. Trascrizione del confronto standard tra matrici

<?php
// Le matrici vengono confrontate come illustrato in questa funzione
function standard_array_compare($op1, $op2)
{
    if (count($op1) < count($op2)) {
        return -1; // $op1 < $op2
    } elseif (count($op1) > count($op2)) {
        return 1; // $op1 > $op2
    }
    foreach ($op1 as $key => $val) {
        if (!array_key_exists($key, $op2)) {
            return null; // uncomparable
        } elseif ($val < $op2[$key]) {
            return -1;
        } elseif ($val > $op2[$key]) {
            return 1;
        }
    }
    return 0; // $op1 == $op2
}
?>

Vedere anche strcasecmp(), strcmp(), Array operators, e la sezione del manuale su Types.


Operatore ternario

Un'altro operatore condizionale è l'operatore ternario "?:".

Esempio 15-3. Assegnazione di un valore di default

<?php
// Esempio di utilizzo dell'operatore ternario
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// La riga precedente è simile a
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>
L'espressione (espressione1) ? (espressione2) : (espressione3) vale espressione2 se espressione1 è TRUE, e espressione3 se espressione1 è FALSE.

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.


Operatori di controllo errori

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


Operatori di esecuzione

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

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

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.


Operatori di incremento/decremento

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

EsempioNomeEffetto
++$aPre-incrementoIncrementa $a di una unità, inoltre restituisce $a.
$a++Post-incrementoRestituisce $a, inoltre incrementa $a di una unità.
--$aPre-decrementoDecrementa $a di una unità, inoltre restituisce $a.
$a--Post-decrementoRestituisce $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.

Esempio 15-4. Operazioni aritmetiche su variabili stringa

<?php
$i = 'W';
for ($n=0; $n<6; $n++)
    echo ++$i . "\n";

Il precedente esempio visualizzerà:

X
Y
Z
AA
AB
AC

Incrementare o decrementare valori booleani non ha effetto.


Operatori logici

Tabella 15-7. Operatori logici

EsempioNomeRisultato
$a and $bAndTRUE se entrambi $a e $b sono TRUE.
$a or $bOrTRUE se uno tra $a o $b è TRUE.
$a xor $bXorTRUE se uno tra $a o $b è TRUE, ma non entrambi.
! $aNotTRUE se $a non è TRUE.
$a && $bAndTRUE se entrambi $a e $b sono TRUE.
$a || $bOrTRUE 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.)


Operatori di stringa

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.


Operatori per matrici

Tabella 15-8. Operatori per matrici

EsempioNomeRisultato
$a + $bUnioneUnione di $a e $b.
$a == $bUguaglianzaTRUE se $a e $b hanno le stesse coppie di chiavi/valori.
$a === $bIdentitàTRUE se $a e $b hanno le stesse coppie di chiavi/valori nel medesimo ordine e dl medesimo tipo.
$a != $bDisuguaglianzaTRUE se $a non è uguale a $b.
$a <> $bDisuguaglianzaTRUE se $a non è uguale a $b.
$a !== $bNon-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);
?>

Una volta eseguito, lo script visualizzerà:
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.

Esempio 15-5. Confrontare le matrici

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
 
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

Vedere anche la sezione del manuale sulle Matrici e Funzioni per le matrici.


Operatori di tipi

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


Capitolo 16. Strutture di controllo

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.


if

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:

<?php
if (expression)
    istruzione
?>

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:

<?php
if ($a > $b)
    echo "a è 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:

<?php
if ($a > $b) {
    echo "a è maggiore di b";
    $b = $a;
}
?>

Si possono annidare indefinitamente istruzioni if, la qual cosa fornisce piena flessibilità per l'esecuzione di istruzioni condizionali in diversi punti del programma.


else

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:

<?php
if ($a > $b) {
    echo "a è maggiore di b";
} else {
    echo "a NON è maggiore di b";
}
?>

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

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.


Sintassi alternativa per le strutture di controllo

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.

<?php if ($a == 5): ?>
a è uguale a 5
<?php endif; ?>

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:

<?php
if ($a == 5):
    echo  "a è uguale a 5";
    echo  "...";
elseif ($a == 6):
    echo  "a è uguale a 6";
    echo  "!!!";
else:
    echo  "a non è nè 5 nè 6";
endif;
?>

Vedere anche while, for, e if per ulteriori esempi.


while

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:

while (espressione) 
   istruzione

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:

while (espressione): 
    istruzione 
    ... 
endwhile;

Gli esempi seguenti sono identici e entrambi visualizzano i numeri da 1 a 10:

<?php
/* esempio 1 */

$i = 1;
while ($i <= 10) {
    echo $i++;  /* Il valore visualizzato è il valore della
                    variabile $i prima dell'incremento
                    (post-incremento) */
}

/* esempio 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>


do-while

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:

<?php
$i = 0;
do {
   echo $i;
} while ($i > 0);
?>

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


for

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

for (espressione1; espressione2; espressione3) 
    istruzione

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.

for (espressione1; espressione2; espressione3): 
   istruzione
   ...
endfor;


foreach

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.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr vale ora array(2, 4, 6, 8)
?>

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

Allo stesso modo i due cicli seguenti sono identici:

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

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

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 "&nbsp;&nbsp;Centrale<br />\n";
        while (1) {
            echo "&nbsp;&nbsp;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

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:

Esempio 16-1. Struttura switch

<?php
if ($i == 0) {
    echo  "i è uguale a 0";
} elseif ($i == 1) {
    echo  "i è uguale a 1";
} elseif ($i == 2) {
    echo  "i è uguale a 2";
}

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

Esempio 16-2. L'istruzione switch permette l'uso di stringhe

<?php
switch ($i) {
case "apple":
    echo "i is apple";
    break;
case "bar":
    echo "i is bar";
    break;
case "cake":
    echo "i is cake";
    break;
}
?>

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

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


declare

Il costrutto declare si usa per definire direttive di esecuzione per blocchi di istruzioni. La sintassi è simile alla sintassi di altre strutture di controllo:

declare (direttiva)
    istruzione

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


Ticks

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

<?php
// Una funzione che registra il tempo quando viene chiamata
function profile($dump = FALSE)
{
    static $profile;

    // Restituisce il tempo immagazinato in $profile, successivamente lo cancella
    if ($dump) {
        $temp = $profile;
        unset($profile);
        return $temp;
    }

    $profile[] = microtime();
}

// Imposta un tick handler
register_tick_function("profile");

// Inizializza la funzione prima del blocco declare
profile();

// Esegue un blocco di codice, attraverso un tick ogni seconda istruzione
declare(ticks = 2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text(md5($x), md5($x*$x)), "<br />;";
    }
}

// Mostra i dati immagazionati nel profilo
print_r(profile(TRUE));
?>
L'esempio descrive il codice PHP all'interno del blocco 'declare', registrando il tempo in cui è stata eseguita ogni seconda istruzione di basso livello. Questa informazione può poi essere usata per trovare le aree lente all'interno di particolari segmenti di codice. Questo processo può essere ottimizzato usando altri metodi: usando i tick è più conveniente e facile da implementare.

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


return

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


require()

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

<?php

require 'prepend.php';

require $qualche_file;

require ('qualche_file.txt');

?>

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.


include()

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

vars.php
<?php

$colore = 'verde';
$frutto = 'mela';

?>

test.php
<?php

echo "Una $frutto $colore"; // Una

include 'vars.php';

echo "Una $frutto $colore"; // Una mela verde

?>

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

<?php

function foo()
{
    global $frutto;

    include 'vars.php';

    echo "Una $frutto $colore";
}

/* vars.php è nello scope di foo() così    *
 * $colore NON è disponibile fuori di      *
 * questo scope. $frutto si perchè è stato *
 * dichiarato globale.                     */

foo();                        // Una mela verde
echo "Una $frutto $colore";   // Una mela

?>

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

<?php

/* Questo esempio assume che www.example.com è configurato per eseguire file 
 * .php e non file .txt. Anche, 'Funziona' qui significa che le variabili    
 * $foo e $bar sono disponibili all'interno del file incluso.                */

// Non funzionerà; file.txt non è stato trattato da www.example.com come PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Non funzionerà; cercare un file chiamato'file.php?foo=1&bar=2' nel
// filesystem locale.
include 'file.php?foo=1&bar=2';

// Funziona.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt';  // Funziona.
include 'file.php';  // Funziona.

?>
Vedere anche Remote files, fopen() e file() per informazioni correlate.

Poichè include() e require() sono speciali costrutti di linguaggio, dovete includerli all'interno di blocchi di istruzioni se si trovano in un blocco condizionale.

Esempio 16-8. include() e i blocchi condizionali

<?php

// Questo NON VA BENE e non funzionerà come desiderato.
if ($condizione)
    include $file;
else
    include $un_altro;


// Questo è CORRETTO.
if ($condizione) {
    include $file;
} else {
    include $un_altro;
}

?>

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.

Esempio 16-9. Confronto dei valori restituiti da include

<?php
// non funziona, viene trattato come include(('vars.php') == 'OK'), ad esempio. include('')
if (include('vars.php') == 'OK') {
    echo 'OK';
}
 
// funziona
if ((include 'vars.php') == 'OK') {
    echo 'OK';
}
?>

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.

Esempio 16-10. include() and the return() statement

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // stampa 'PHP'

$bar = include 'noreturn.php';

echo $bar; // stampa 1

?>

$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

<?php
$string = get_include_contents('somefile.php');
 
function get_include_contents($filename) {
    if (is_file($filename)) {
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }
    return false;
}
 
?>

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.


require_once()

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

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

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


include_once()

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

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

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


Capitolo 17. Funzioni

Funzioni definite dall'utente

Una funzione può essere definita usando la seguente sintassi:

Esempio 17-1. Psuedo codice per dimostrare l'uso delle funzioni

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Funzione di esempio.\n";
    return $retval;
}
?>

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

<?php
 
$makefoo = true;
 
/* Qui non possiamo chiamare foo()
   poichè non esiste ancora,
   ma possiamo chiamare bar() */
 
bar();
 
if ($makefoo) {
  function foo()
  {
    echo "Io non esisto sino a quando il programma non ri raggiunge.\n";
  }
}
 
/* Ora possiamo chiarame foo()
   poichè $makefoo vale true */
 
if ($makefoo) foo();
 
function bar()
{
  echo "Io esco immediatamente dop l'avvio del programma.\n";
}
 
?>

Esempio 17-3. Funzioni dentro a funzioni

<?php
function foo()
{
  function bar()
  {
    echo "Io non esiste fino a quando non si esegue foo().\n";
  }
}
 
/* Non possiamo chiamare bar()
   poicheè non esiste ancora. */
 
foo();
 
/* Ora si può eseguire bar(),
   l'elaborazione di foo()
   l'ha resa accessibile. */
 
bar();
 
?>

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.

Esempio 17-4. Funzioni ricorsive

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?>


Argomenti delle funzioni

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.

Esempio 17-5. Passaggio di array a funzioni

<?php
function prende_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>


Costruire argomenti passati per riferimento

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:

Esempio 17-6. Passaggio di parametri per riferimento

<?php
function aggiungi_qualcosa(&$string)
{
    $string .= 'e qualche altra cosa.';
}
$str = 'Questa è una stringa, ';
aggiungi_qualcosa($str);
echo $str;    // l'output sarà 'Questa è una stringa, e qualche altra cosa.'
?>


Valori predefiniti degli argomenti

Una funzione può definire valori predefiniti in stile C++ per argomenti scalari come segue:

Esempio 17-7. Utilizzo dei parametri default in una funzione

<?php
function fare_il_caffe($tipo = "cappuccino")
{
    return "Sto facendo una tazza di $tipo.\n";
}
echo fare_il_caffe();
echo fare_il_caffe("espresso");

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

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

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:

Esempio 17-9. Utilizzo incorretto degli argomenti di default

<?php
function fare_lo_yogurt($tipo = "yogurt", $gusto)
{
    return "Fare una vaschetta di $tipo a $gusto.\n";
}

echo fare_lo_yogurt("fragola");   // non funziona come si aspetta
?>

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:

Esempio 17-10. Utilizzo corretto degli argomenti di default

<?php
function fare_lo_yogurt($gusto, $tipo = "yogurt")
{
    return "Fare una vaschetta di $tipo a $gusto.\n";
}

echo fare_lo_yogurt("fragola");   // funziona come si aspetta

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.


Liste di argomenti a lunghezza variabile

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.


Valori restituiti

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

<?php
function quadrato ($num)
{
    return $num * $num;
}
echo quadrato(4);   // L'output è '16'.
?>

Non possono essere restituiti valori multipli da una funzione, ma risultati simili possono essere ottenuti restituendo una lista.

Esempio 17-12. Restituzione di una matrice per ottenere più valori

<?php
function numeri_piccoli()
{
    return array (0, 1, 2);
}
list ($zero, $uno, $due) = numeri_piccoli();
?>

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:

Esempio 17-13. Restituzione di un riferimento ad una funzione

<?php
function &restituisce_riferimento()
{
    return $un_riferimento;
}

$nuovo_riferimento =& restituisce_riferimento();
?>

Per maggiori informazioni sui riferimenti, consultare References Explained.


Funzioni variabili

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

<?php
function foo() {
    echo "In foo()<br />\n";
}

function bar($arg = '')
{
    echo "In bar(); l'argomento era '$arg'.<br />\n";
}

// Questa è la funzione per usare echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // questa chiama foo()
$func = 'bar';
$func('test');  // questa chiama bar()

$func = 'echoit';
$func('test');  // questa chiama echoit()
?>

Tramite le funzioni variabili si può eseguire anche metodi di oggetti.

Esempio 17-15. Esempio di un metodo variabile

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // Questo esegue il metodo Bar()
    }
 
    function Bar()
    {
        echo "This is Bar";
    }
}
 
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // Questo esegue $foo->Variable()
 
?>

Vedere anche call_user_func(), variabili variabili e function_exists().


Funzioni interne (built-in)

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


Capitolo 18. Classi e Oggetti (PHP 4)

Classi

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:

<?php
class test {
?>
<?php
    function test() {
        print 'OK';
    }
}
?>

Tuttavia è permessa la seguente struttura:

<?php
class test {
    function test() {
        ?>
        <?php
        print 'OK';
    }
}
?>

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.


extends

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.


Costruttori

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.

<?php
class Auto_Cart extends Cart {
    function Auto_Cart() {
        $this->add_item ("10", 1);
    }
}
?>

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.


Operatore Scope Resolution (::)

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.


parent

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


Serializzare oggetti - oggetti nelle sessioni

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.


Le funzioni magiche __sleep e __wakeup

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.


Riferimenti all'interno del costruttore

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

Per dimostrare quello che è scritto sopra guardate il codice qui sotto.

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


Confronto di oggetti

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

<?php
function bool2str($bool) {
    if ($bool === false) {
            return 'FALSE';
    } else {
            return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2) {
    echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
    echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
    echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
    echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}

class Flag {
    var $flag;

    function Flag($flag=true) {
            $this->flag = $flag;
    }
}

class SwitchableFlag extends Flag {

    function turnOn() {
        $this->flag = true;
    }

    function turnOff() {
        $this->flag = false;
    }
}

$o = new Flag();
$p = new Flag(false);
$q = new Flag();

$r = new SwitchableFlag();

echo "Confronto di istanze create con gli stessi parametri\n";
compareObjects($o, $q);

echo "\nConfronto di istanze create con parametri diversi\n";
compareObjects($o, $p);

echo "\nConfronto di un'istanza della classe genitore con una sottoclasse\n";
compareObjects($o, $r);
?>

Il precedente esempio visualizzerà:

Confronto di istanze create con gli stessi parametri
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Confronto di istanze create con parametri diversi
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Confronto di un'istanza della classe genitore con una sottoclasse
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Questo è l'output che si ottiene secondo le regole di confronto descritte sopra. Solo le istanze con gli stessi valori per gli attributi e derivanti dalla stessa classe sono considerate uguali ed identiche.

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

<?php
class FlagSet {
    var $set;

    function FlagSet($flagArr = array()) {
        $this->set = $flagArr;
    }

    function addFlag($name, $flag) {
        $this->set[$name] = $flag;
    }

    function removeFlag($name) {
        if (array_key_exists($name, $this->set)) {
            unset($this->set[$name]);
        }
    }
}


$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));

echo "\nOggetti composti u(o,p) e v(q,p)\n";
compareObjects($u, $v);

echo "\nu(o,p) and w(q)\n";
compareObjects($u, $w);
?>

Il precedente esempio visualizzerà:

Oggetti composti u(o,p) e v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


Capitolo 19. Classes and Objects (PHP 5)

Introduction

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.


The Basics

class

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.

Esempio 19-1. Simple Class definition

<?php
class SimpleClass
{
    // member declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

new

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.

Esempio 19-2. Creating an instance

<?php
$instance = new SimpleClass()
?>

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

<?php
$assigned   =  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

Il precedente esempio visualizzerà:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

extends

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

<?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

Il precedente esempio visualizzerà:

Extending class
a default value

Autoloading Objects

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.

Esempio 19-5. Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.

<?php
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>


Constructors and Destructors

Constructor

void __construct ( [mixed args [, ...]] )

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

<?php
class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
       print "In SubClass constructor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

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.


Destructor

void __destruct ( void )

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.

Esempio 19-7. Destructor Example

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

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.


Visibility

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.


Members Visibility

Class members must be defined with public, private, or protected.

Esempio 19-8. Member declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected method, but not private
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, not Private

?>

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.


Method Visibility

Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.

Esempio 19-9. Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Contructors must be public
    public function __construct() { }

    // Declare a public method
    public function MyPublic() { }

    // Declare a protected method
    protected function MyProtected() { }

    // Declare a private method
    private function MyPrivate() { }

    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // This is public
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); // Fatal Error
    }
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
?>


Scope Resolution Operator (::)

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!

Esempio 19-10. :: from outside the class definition

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

echo MyClass::CONST_VALUE;
?>

Two special keywords self and parent are used to access members or methods from inside the class definition.

Esempio 19-11. :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static $my_static = 'static var';

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

OtherClass::doubleColon();
?>

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

<?php
class MyClass
{
    protected function myFunc() {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>

Static Keyword

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

<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}

class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n";      // Undefined "Property" my_static 

// $foo::my_static is not possible

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>

Esempio 19-14. Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
?>

Class Constants

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.

Esempio 19-15. Defining and using a constant

<?php
class MyClass
{
    const constant = 'constant value';

    function showConstant() {
        echo  self::constant . "\n";
    }
}

echo MyClass::constant . "\n";

$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>

Class Abstraction

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

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>

Il precedente esempio visualizzerà:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.


Object Interfaces

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.


implements

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.


Esempi

Esempio 19-17. Interface example

<?php
// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
  
    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
 
        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();
  
    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}

?>

See also the instanceof operator.


Overloading

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.


Member overloading

void __set ( string name, mixed value )

mixed __get ( string name )

bool __isset ( string name )

void __unset ( string name )

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

<?php
class Setter
{
    public $n;
    private $x = array("a" => 1, "b" => 2, "c" => 3);

    private function __get($nm)
    {
        echo "Getting [$nm]\n";

        if (isset($this->x[$nm])) {
            $r = $this->x[$nm];
            print "Returning: $r\n";
            return $r;
        } else {
            echo "Nothing!\n";
        }
    }

    private function __set($nm, $val)
    {
        echo "Setting [$nm] to $val\n";

        if (isset($this->x[$nm])) {
            $this->x[$nm] = $val;
            echo "OK!\n";
        } else {
            echo "Not OK!\n";
        }
    }

    private function __isset($nm)
    {
        echo "Checking if $nm is set\n";

        return isset($this->x[$nm]);
    }

    private function __unset($nm)
    {
        echo "Unsetting $nm\n";

        unset($this->x[$nm]);
    }
}

$foo = new Setter();
$foo->n = 1;
$foo->a = 100;
$foo->a++;
$foo->z++;

var_dump(isset($foo->a)); //true
unset($foo->a);
var_dump(isset($foo->a)); //false

// this doesn't pass through the __isset() method
// because 'n' is a public property
var_dump(isset($foo->n));

var_dump($foo);
?>

Il precedente esempio visualizzerà:

Setting [a] to 100
OK!
Getting [a]
Returning: 100
Setting [a] to 101
OK!
Getting [z]
Nothing!
Setting [z] to 1
Not OK!

Checking if a is set
bool(true)
Unsetting a
Checking if a is set
bool(false)
bool(true)

object(Setter)#1 (2) {
  ["n"]=>
  int(1)
  ["x:private"]=>
  array(2) {
    ["b"]=>
    int(2)
    ["c"]=>
    int(3)
  }
}

Method overloading

mixed __call ( string name, array arguments )

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

<?php
class Caller
{
    private $x = array(1, 2, 3);

    public function __call($m, $a)
    {
        print "Method $m called:\n";
        var_dump($a);
        return $this->x;
    }
}

$foo = new Caller();
$a = $foo->test(1, "2", 3.4, true);
var_dump($a);
?>

Il precedente esempio visualizzerà:

Method test called:
array(4) {
    [0]=>
    int(1)
    [1]=>
    string(1) "2"
    [2]=>
    float(3.4)
    [3]=>
    bool(true)
}
array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
}

Object Iteration

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

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key => $value) {
    print "$key => $value\n";
}
echo "\n";


$class->iterateVisible();

?>

Il precedente esempio visualizzerà:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

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

<?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }

    public function rewind() {
        echo "rewinding\n";
        reset($this->var);
    }

    public function current() {
        $var = current($this->var);
        echo "current: $var\n";
        return $var;
    }

    public function key() {
        $var = key($this->var);
        echo "key: $var\n";
        return $var;
    }

    public function next() {
        $var = next($this->var);
        echo "next: $var\n";
        return $var;
    }

    public function valid() {
        $var = $this->current() !== false;
        echo "valid: {$var}\n";
        return $var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a => $b) {
    print "$a: $b\n";
}
?>

Il precedente esempio visualizzerà:

rewinding
current: 1
valid: 1
current: 1
key: 0
0: 1
next: 2
current: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
current: 3
valid: 1
current: 3
key: 2
2: 3
next:
current:
valid:

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

<?php
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;

    // Required definition of interface IteratorAggregate
    public function getIterator() {
        return new MyIterator($this->items);
    }

    public function add($value) {
        $this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach ($coll as $key => $val) {
    echo "key/value: [$key -> $val]\n\n";
}
?>

Il precedente esempio visualizzerà:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

Nota: For more examples of iterators, see the SPL Extension.


Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.


Factory

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

<?php
class Example
{
    // The factory method
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception ('Driver not found');
        }
    }
}
?>

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:

<?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');

// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?>

Singleton

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

<?php
class Example
{
    // Hold an instance of the class
    private static $instance;
    
    // A private constructor; prevents direct creation of object
    private function __construct() 
    {
        echo 'I am constructed';
    }

    // The singleton method
    public static function singleton() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }
    
    // Example method
    public function bark()
    {
        echo 'Woof!';
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

This allows a single instance of the Example class to be retrieved.

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test = Example::singleton();
$test->bark();

// This will issue an E_USER_ERROR.
$test_clone = clone($test);

?>

Magic Methods

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.


__sleep and __wakeup

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

<?php
class Connection {
    protected $link;
    private $server, $username, $password, $db;
    
    public function __construct($server, $username, $password, $db)
    {
        $this->server = $server;
        $this->username = $username;
        $this->password = $password;
        $this->db = $db;
        $this->connect();
    }
    
    private function connect()
    {
        $this->link = mysql_connect($this->server, $this->username, $this->password);
        mysql_select_db($this->db, $this->link);
    }
    
    public function __sleep()
    {
        mysql_close($this->link);
    }
    
    public function __wakeup()
    {
        $this->connect();
    }
}
?>

__toString

The __toString method allows a class to decide how it will react when it is converted to a string.

Esempio 19-26. Simple example

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

Il precedente esempio visualizzerà:

Hello

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
// __toString called
echo $class;

// __toString called (still a normal parameter for echo)
echo 'text', $class;

// __toString not called (concatenation operator used first)
echo 'text' . $class;

// __toString not called (cast to string first)
echo (string) $class;

// __toString not called (cast to string first)
echo "text $class";
?>

Final Keyword

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

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }
   
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Esempio 19-29. Final class example

<?php
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Object cloning

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.

$copy_of_object = clone $object;

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

<?php
class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }

    public function __clone() {
        $this->instance = ++self::$instances;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // Force a copy of this->object, otherwise
        // it will point to same object.
        $this->object1 = clone($this->object1);
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

?>

Il precedente esempio visualizzerà:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)

Comparing objects

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

<?php
function bool2str($bool)
{
    if ($bool === false) {
        return 'FALSE';
    } else {
        return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2)
{
    echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
    echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
    echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
    echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
    public $flag;

    function Flag($flag = true) {
        $this->flag = $flag;
    }
}

class OtherFlag
{
    public $flag;

    function OtherFlag($flag = true) {
        $this->flag = $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();

echo "Two instances of the same class\n";
compareObjects($o, $p);

echo "\nTwo references to the same instance\n";
compareObjects($o, $q);

echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>

Il precedente esempio visualizzerà:

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


Reflection

Introduction

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

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

Il precedente esempio visualizzerà:

Class [ <internal> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [6] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
  }

  - Methods [9] {
    Method [ <internal> final private method __clone ] {
    }

    Method [ <internal> <ctor> public method __construct ] {

      - Parameters [2] {
        Parameter #0 [ <required> $message ]
        Parameter #1 [ <required> $code ]
      }
    }

    Method [ <internal> final public method getMessage ] {
    }

    Method [ <internal> final public method getCode ] {
    }

    Method [ <internal> final public method getFile ] {
    }

    Method [ <internal> final public method getLine ] {
    }

    Method [ <internal> final public method getTrace ] {
    }

    Method [ <internal> final public method getTraceAsString ] {
    }

    Method [ <internal> public method __toString ] {
    }
  }
}


ReflectionException

ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.


ReflectionFunction

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

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter() 
{
    static $c = 0;
    return $c++;
}

// Create an instance of the Reflection_Function class
$func = new ReflectionFunction('counter');

// Print out basic information
printf(
    "===> The %s function '%s'\n".
    "     declared in %s\n".
    "     lines %d to %d\n",
    $func->isInternal() ? 'internal' : 'user-defined',
    $func->getName(),
    $func->getFileName(),
    $func->getStartLine(),
    $func->getEndline()
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

// Print static variables if existant
if ($statics = $func->getStaticVariables())
{
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the function
printf("---> Invokation results in: ");
var_dump($func->invoke());


// you may prefer to use the export() method
echo "\nReflectionFunction::export() results:\n";
echo ReflectionFunction::export('counter');
?>

Nota: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().


ReflectionParameter

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

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

// Create an instance of Reflection_Function with the
// parameter given from the command line.    
$reflect = new ReflectionFunction($argv[1]);

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, 
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

ReflectionClass

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

<?php
interface Serializable
{
    // ...
}

class Object
{
    // ...
}

/**
 * A counter class
 */
class Counter extends Object implements Serializable 
{
    const START = 0;
    private static $c = Counter::START;

    /**
     * Invoke counter
     *
     * @access  public
     * @return  int
     */
    public function count() {
        return self::$c++;
    }
}

// Create an instance of the ReflectionClass class
$class = new ReflectionClass('Counter');

// Print out basic information
printf(
    "===> The %s%s%s %s '%s' [extends %s]\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d [%s]\n",
        $class->isInternal() ? 'internal' : 'user-defined',
        $class->isAbstract() ? ' abstract' : '',
        $class->isFinal() ? ' final' : '',
        $class->isInterface() ? 'interface' : 'class',
        $class->getName(),
        var_export($class->getParentClass(), 1),
        $class->getFileName(),
        $class->getStartLine(),
        $class->getEndline(),
        $class->getModifiers(),
        implode(' ', Reflection::getModifierNames($class->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($class->getDocComment(), 1));

// Print which interfaces are implemented by this class
printf("---> Implements:\n %s\n", var_export($class->getInterfaces(), 1));

// Print class constants
printf("---> Constants: %s\n", var_export($class->getConstants(), 1));

// Print class properties
printf("---> Properties: %s\n", var_export($class->getProperties(), 1));

// Print class methods
printf("---> Methods: %s\n", var_export($class->getMethods(), 1));

// If this class is instantiable, create an instance
if ($class->isInstantiable()) {
    $counter = $class->newInstance();

    echo '---> $counter is instance? '; 
    echo $class->isInstance($counter) ? 'yes' : 'no';

    echo "\n---> new Object() is instance? ";
    echo $class->isInstance(new Object()) ? 'yes' : 'no';
}
?>

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


ReflectionMethod

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

<?php
class Counter
{
    private static $c = 0;

    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Create an instance of the Reflection_Method class
$method = new ReflectionMethod('Counter', 'increment');

// Print out basic information
printf(
    "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d[%s]\n",
        $method->isInternal() ? 'internal' : 'user-defined',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'the constructor' : 'a regular method',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));

// Print static variables if existant
if ($statics= $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the method
printf("---> Invokation results in: ");
var_dump($method->invoke(NULL));
?>

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.


ReflectionProperty

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

<?php
class String
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('String', 'length');

// Print out basic information
printf(
    "===> The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop->isPublic() ? ' public' : '',
        $prop->isPrivate() ? ' private' : '',
        $prop->isProtected() ? ' protected' : '',
        $prop->isStatic() ? ' static' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of String
$obj= new String();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

Nota: Trying to get or set private or protected class property's values will result in an exception being thrown.


ReflectionExtension

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

<?php
// Create an instance of the ReflectionProperty class
$ext = new ReflectionExtension('standard');

// Print out basic information
printf(
    "Name        : %s\n" .
    "Version     : %s\n" .
    "Functions   : [%d] %s\n" .
    "Constants   : [%d] %s\n" .
    "INI entries : [%d] %s\n" .
    "Classes     : [%d] %s\n",
        $ext->getName(),
        $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
        sizeof($ext->getFunctions()),
        var_export($ext->getFunctions(), 1),

        sizeof($ext->getConstants()),
        var_export($ext->getConstants(), 1),

        sizeof($ext->getINIEntries()),
        var_export($ext->getINIEntries(), 1),

        sizeof($ext->getClassNames()),
        var_export($ext->getClassNames(), 1)
);
?>

Extending the reflection classes

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

<?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = '';

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility= Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Demo class #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Demo class #2
 *
 */
class U extends T {
    function x() {}
}

// Print out information
var_dump(new My_Reflection_Method('U', 'x'));
?>

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


Type Hinting

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

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }


    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

Failing to satisfy the type hint results in a fatal error.

<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

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.


Capitolo 20. Exceptions

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

<?php
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

Extending Exceptions

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

<?php
class Exception
{
    protected $message = 'Unknown exception';   // exception message
    protected $code = 0;                        // user defined exception code
    protected $file;                            // source filename of exception
    protected $line;                            // source line of exception

    function __construct($message = null, $code = 0);

    final function getMessage();                // message of exception 
    final function getCode();                   // code of exception
    final function getFile();                   // source filename
    final function getLine();                   // source line
    final function getTrace();                  // an array of the backtrace()
    final function getTraceAsString();          // formated string of trace

    /* Overrideable */
    function __toString();                       // formated string for display
}
?>

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

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
        // some code
    
        // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

    // custom string representation of object */
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A Custom function for this type of exception\n";
    }
}


/**
 * Create a class to test the exception
 */
class TestException
{
    public $var;

    const THROW_NONE    = 0;
    const THROW_CUSTOM  = 1;
    const THROW_DEFAULT = 2;

    function __construct($avalue = self::THROW_NONE) {

        switch ($avalue) {
            case self::THROW_CUSTOM:
                // throw custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // throw default one.
                throw new Exception('2 isnt allowed as a parameter', 6);
                break;

            default: 
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }
}


// Example 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";


// Example 2
try {
    $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // Doesn't match this type
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Will be caught
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";


// Example 3
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) {        // Will be caught
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";


// Example 4
try {
    $o = new TestException();
} catch (Exception $e) {        // Skipped, no exception
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o);
echo "\n\n";
?>

Capitolo 21. Spiegazioni sui riferimenti

Cosa sono i riferimenti

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.


Che cosa fanno i riferimenti

I riferimenti permettono di creare due o più variabili che si riferiscono allo stesso contenuto. Questo significa, che scrivendo:

<?php
$a =& $b;
?>

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

<?php
$bar =& new fooclass();
$foo =& find_var($bar);
?>

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.

Esempio 21-1. Riferimenti di varibiali globali all'interno di una funzione

<?php
$var1 = "Example variable";
$var2 = "";
 
function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 =& $var1; // visible only inside the function
    } else {
        $GLOBALS["var2"] =& $var1; // visible also in global context
    }
}
 
global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
Si pensi a global $var; come ad una scorciatoia per $var =& $GLOBALS['var'];. Quindi assegnando altri riferimenti a $var si cambia soltanto il riferimento della variabile locale.

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.

Esempio 21-2. Riferimenti e istruzione foreach

<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
    // esegue qualcosa
}
echo $ref; // 3 - ultimo elemento dell'array
?>

Avvertimento

Spesso le matrici complesse sono copiate che referenziate. Il seguente esempio non gira come atteso.

Esempio 21-3. Riferimenti con matrici complesse

<?php
$top = array(
    'A' => array(),
    'B' => array(
        'B_b' => array(),
    ),
);
 
$top['A']['parent'] = &$top;
$top['B']['parent'] = &$top;
$top['B']['B_b']['data'] = 'test';
print_r($top['A']['parent']['B']['B_b']); // array()
?>

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:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
?>

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


Cosa i riferimenti non sono

Come detto prima, i riferimenti non sono puntatori. Questo significa, che il seguente costrutto non fà quello che ci si aspetterebbe:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar); 
?>

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.


Passaggio per riferimento

Si può passare una variabile ad una funzione per riferimento, modificandone gli argomenti. La sintassi è la seguente:

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a adesso è 6
?>

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.

    <?php
    function &bar()
    {
        $a = 5;
        return $a;
    }
    foo(bar());
    ?>

    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:

<?php
function bar() // Nota l'assenza di &
{
    $a = 5;
    return $a;
}

foo(bar()); // produce un errore fatale da PHP 5.1.0
foo($a = 5); // Expressione: non una variabile
foo(5); // Genera un errore fatale
?>

Questi requisiti sono validi per PHP 4.0.4 e seguenti.


Restituzione per riferimento

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

In questo esempio, la proprietà dell'oggetto restituito dalla funzione find_var viene impostata, non la copia, come sarebbe stato senza l'uso della sintassi del riferimento.

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.


Cancellare riferimenti

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:

<?php
$a = 1;
$b =& $a;
unset($a); 
?>

non cancella $b, ma solo $a.

Di nuovo, può essere utile pensare a questo con un'analogia col comendo Unix unlink.


Spotting References

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:


Il riferimento global

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:

<?php
$var =& $GLOBALS["var"];
?>

Questo significa, per esempio, che cancellando $var non si cancella la variabile globale.


$this

In un metodo di un oggetto, $this è sempre un riferimento all'oggetto chiamante.


Capitolo 22. Introduction

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.


Capitolo 23. General considerations

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

The best security is often 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.


Capitolo 24. Installed as CGI binary

Possible attacks

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

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

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

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

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

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

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


Case 1: only public files served

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

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


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

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

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

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

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


Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes 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.


Case 4: PHP parser outside of web tree

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

#!/usr/local/bin/php

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

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


Capitolo 25. Installed as an Apache module

When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database 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.


Capitolo 26. Filesystem Security

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

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

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

Esempio 26-1. Poor variable checking leads to....

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

Esempio 26-2. ... A filesystem attack

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

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

  • Check all variables which are submitted.

Here is an improved script:

Esempio 26-3. More secure file name checking

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

$homedir = "/home/$username";

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

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

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

Esempio 26-4. More secure file name checking

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

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

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

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


Capitolo 27. Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret 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.


Designing Databases

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.


Connecting to Database

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.


Encrypted Storage Model

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

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

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this 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

<?php

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

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

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

?>

SQL Injection

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

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

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

Esempio 27-2. Splitting the result set into pages ... and making superusers (PostgreSQL)

<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL

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

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

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

A feasible way to gain passwords is to circumvent your search result pages. 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.

Esempio 27-3. Listing out articles ... and some passwords (any database server)

<?php

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);

?>
The static part of the query can be combined with another SELECT statement which reveals all passwords:

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

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

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

Esempio 27-4. From resetting a password ... to gaining more privileges (any database server)

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

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

Esempio 27-5. Attacking the database hosts operating system (MSSQL Server)

<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

<?php

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

?>

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

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


Avoiding techniques

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

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust 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

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

  • Quote each non numeric user 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.


Capitolo 28. Error Reporting

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

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

Esempio 28-1. Attacking Variables with a custom HTML page

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

The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure 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:

Esempio 28-2. Exploiting common debugging variables

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

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

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

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

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

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

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

Esempio 28-3. Finding dangerous variables with E_ALL

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


Capitolo 29. Using Register Globals

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

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

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

<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

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

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

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


Capitolo 30. User Submitted Data

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

Esempio 30-1. Dangerous Variable Usage

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

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

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

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

  • Will this script only affect the intended files?

  • Can unusual or undesirable data be acted upon?

  • Can this script be used in unintended ways?

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

  • Will any transactions be adequately logged?

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

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


Capitolo 31. Magic Quotes

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.


What are Magic Quotes

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:

  • magic_quotes_gpc

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

  • magic_quotes_runtime

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

  • magic_quotes_sybase

    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.


Why use Magic Quotes

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


Why not to use Magic Quotes

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


Disabling Magic Quotes

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.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

If access to the server configuration is unavailable, use of .htaccess is also an option. For example:

php_flag magic_quotes_gpc Off

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

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
?>


Capitolo 32. Hiding PHP

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

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

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

Esempio 32-1. Hiding PHP as another language

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

Esempio 32-2. Using unknown types for PHP extensions

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

Esempio 32-3. Using HTML types for PHP extensions

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


Capitolo 33. Keeping Current

PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance 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.


Capitolo 34. Autenticazione HTTP usando PHP

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"

<?php
  if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Il mio realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Messaggio da inviare se si preme il tasto Cancel';
    exit;
  } else {
    echo "<p>Ciao {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>Hai inserito {$_SERVER['PHP_AUTH_PW']} come tua password.</p>";
  }
?>

Esempio 34-2. Esempio di autenticazione HTTP "Digest"

Questo esempio illustra come implementare una autenticazione Digest. Per maggiori dettagli vedere RFC 2617.

<?php
$realm = 'Restricted area';
 
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
 
 
if (!isset($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '" qop="auth" nonce="'.uniqid().'" opaque="'.md5($realm).'"');
 
    die('Text to send if user hits Cancel button');
}
 
// analisi della variabile PHP_AUTH_DIGEST
preg_match('/username="(?P<username>.*)",\s*realm="(?P<realm>.*)",\s*nonce="(?P<nonce>.*)",\s*uri="(?P<uri>.*)",\s*response="(?P<response>.*)",\s*opaque="(?P<opaque>.*)",\s*qop=(?P<qop>.*),\s*nc=(?P<nc>.*),\s*cnonce="(?P<cnonce>.*)"/', $_SERVER['PHP_AUTH_DIGEST'], $digest);
 
if (!isset($users[$digest['username']]))
    die('Username not valid!');
 
 
// generazione di una risposta valida
$A1 = md5($digest['username'] . ':' . $realm . ':' . $users[$digest['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$digest['uri']);
$valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2);
 
if ($digest['response'] != $valid_response)
    die('Wrong Credentials!');
 
// Ok, utente/passworrd validi
echo 'Your are logged in as: ' . $digest['username'];
  	 
?>

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

<?php
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Prova del Sistema di Autenticazione"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Per poter accedere a questa risorsa occorre inserire una coppia login e password valide\n";
    exit;
  }

  if (!isset($_SERVER['PHP_AUTH_USER']) ||
      ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   authenticate();
  } 
  else {
   echo "<p>Benvenuto: {$_SERVER['PHP_AUTH_USER']}<br>";
   echo "Vecchio: {$_REQUEST['OldAuth']}";
   echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='POST'>\n";
   echo "<input type='hidden' name='SeenBefore' value='1'>\n";
   echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}'>\n";
   echo "<input type='submit' value='Ri autentifica'>\n";
   echo "</form></p>\n";
  }
?>

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.


Capitolo 35. Cookies

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


Capitolo 36. Sessions

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.


Capitolo 37. Dealing with XForms

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

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

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

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

Nota: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.


Capitolo 38. Caricare file

Metodo POST per caricamento di file

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:

<!-- Tipo di codifcia dei dati, DEVE essere specificato come segue -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE deve precedere campo di input del nome file -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Il nome dell'elemento di input determina il nome nell'array $_FILES -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

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.

$_FILES['userfile']['name']

Il nome originale del file sulla macchina dell'utente.

$_FILES['userfile']['type']

Il mime-type del file, se il browser fornisce questa informazione. Un esempio potrebbe essere "image/gif".

$_FILES['userfile']['size']

La dimensione, in bytes, del file caricato.

$_FILES['userfile']['tmp_name']

Il nome del file temporaneo in cui il file caricato è salvato sul server.

$_FILES['userfile']['error']

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.

<?php
// Nelle versioni di PHP precedenti alla 4.1.0 si deve utilizzare  $HTTP_POST_FILES anzichè 
// $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<pre>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possibile attacco tramite file upload!\n"; 
}
echo 'Alcune infromazioni di debug:';
print_r($_FILES); 

print "</pre>";

?>

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.

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}
?>

Spiegazione dei messaggi di errore

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

UPLOAD_ERR_OK

Valore: 0; Non vi sono errori, l'upload è stato eseguito con successo.

UPLOAD_ERR_INI_SIZE

Valore: 1; Il file inviato eccede le dimensioni specificate nel parametro upload_max_filesize di php.ini.

UPLOAD_ERR_FORM_SIZE

Valore: 2; Il file inviato eccede le dimensioni specificate nel parametro MAX_FILE_SIZE del form.

UPLOAD_ERR_PARTIAL

Valore: 3; Upload eseguito parzialmente.

UPLOAD_ERR_NO_FILE

Valore: 4; Nessun file è stato inviato.

UPLOAD_ERR_NO_TMP_DIR

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.


Common Pitfalls

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


Caricamento di più file

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.

Esempio 38-4. Caricamento di più file

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

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


Supporto per metodo PUT

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

<?php
/* I dati PUT arrivano in stdin */
$putdata = fopen("php://stdin", "r");
/* Apertura del file in scrittura */
$fp = fopen("myputfile.ext", "w");
/* Lettura dei dati d 1kb alla volta e scrittura nel file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);
 
/* Chiusura */
fclose($fp);
fclose($putdata);
?>

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

PUT /percorso/nomefile.html HTTP/1.1

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:

Script PUT /put.php

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:

<?php copy($PHP_UPLOADED_FILE_NAME, $DOCUMENT_ROOT . $REQUEST_URI); ?>

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.


Capitolo 39. Utilizzo di file remoti

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

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Impossibile aprire il file remoto.\n";
    exit;
}
while (!feof ($file)) {
    $linea = fgets ($file, 1024);
    /* Funziona solo se title e i relativi tag sono sulla medesima riga */
    if (eregi ("<title>(.*)</title>", $linea, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

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

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Impossibile aprire il file remoto in scrittura.\n";
    exit;
}
/* Scrive i dati qui. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Nota: Dall'esempio precedente ci si può fare un'idea di come usare questa tecnica per effettuare dei log in remoto, ma come già accennato, con questo sitema non è possibile scrivere con fopen() su file già esistenti. Per fare una procedura di log distribuito è più indicata la funzione syslog().


Capitolo 40. Gestione della connessione

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.


Capitolo 41. Connessioni Persistenti ai Database

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


Capitolo 42. Modalità sicura (Safe mode)

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.


Security and Safe Mode

Tabella 42-1. Direttive di configurazione della Modalità sicura e Sdella icurezza

NomeDefaultChangeableChangelog
safe_mode"0"PHP_INI_SYSTEM 
safe_mode_gid"0"PHP_INI_SYSTEMDisponibile dal PHP 4.1.0.
safe_mode_include_dirNULLPHP_INI_SYSTEMDisponibile 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_basedirNULLPHP_INI_SYSTEM 
disable_functions""php.ini onlyDisponibile dal PHP 4.0.1.
disable_classes""php.ini onlyDisponibile dal PHP 4.3.2.
Per ulteriori dettagli e definizione delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

safe_mode boolean

Abilita o disabilita la modalità sicura di PHP's. Leggere il capitolo Sicurezza per ulteriori informazioni.

safe_mode_gid boolean

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.

safe_mode_include_dir string

UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).

As of PHP 4.2.0, this directive can take a 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/"

safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Nota: If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

When a script tries to open a file with, for example, fopen() or gzopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.

The special value . indicates that the 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.

disable_functions string

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.

disable_classes string

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
Eseguendo questo script.php
<?php
 readfile('/etc/passwd'); 
?>
results in this error when Safe Mode is enabled:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not 
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

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>
If you run the same script.php with this open_basedir setting then this is the result:
Warning: open_basedir restriction in effect. File is in wrong directory in 
/docroot/script.php on line 2

È possibile inoltre disabilitare le singole funzioni. Se si aggiunge la seguente riga al file php.ini:
disable_functions readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in 
/docroot/script.php on line 2


Funzioni limitate/disabilitate dalla modalità sicura (safe-mode)

Questo è un elenco probabilmente ancora incompleto e forse non esatto delle funzioni limitate da Safe Mode.

Tabella 42-2. Funzioni limitate dalla modalità sicura

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


Capitolo 43. Utilizzo di PHP da linea di comando

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

    DirettivaCLI SAPI valore di defaultCommento
    html_errorsFALSE 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_flushTRUE 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_time0 (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_argvTRUE

    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

    CostanteDescrizione
    STDIN Un flusso già aperto allo stdin. Questo evita di aprirlo con
    <?php
    $stdin = fopen('php://stdin', 'r');
    
    ?>
    Se si desidera leggere una singola linea dallo stdin, si può utilizzare
    <?php 
    $line = trim(fgets(STDIN)); // reads one line from STDIN 
    fscanf(STDIN, "%d\n", $number); // reads number from STDIN 
    ?>
    STDOUT Un flusso già aperto allo stdout. Questo evita di aprirlo con
    <?php
    
    $stdout = fopen('php://stdout', 'w');
    
    ?>
    STDERR Un flusso già aperto allo stderr. Questo evita di aprirlo con
    <?php
    
    $stderr = fopen('php://stderr', 'w');
    
    ?>

    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");'
    Non occorre chiudere esplicitamente questi flussi, saranno chiusi automaticamente dal PHP alla fine dello script.

  • 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
    Questo evidenzia chiaramente come il PHP cambi la directory corrente con quella in cui si trova lo script.

    Utilizzando la versione CLI SAPI abbiamo:
    $ pwd
    /tmp
    
    $ php -f another_directory/test.php
    /tmp
    Questo permette una grande flessibilità nello scrivere tools in PHP.

    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:

  1. Dire al PHP di eseguire certi file.

    php my_script.php
    
    php -f my_script.php
    Entrambi i metodi (con o senza l'opzione -f) eseguono il file my_script.php. Si può scegliere qualsiasi nome per lo script da eseguire - non è obbligatorio che gli script PHP finiscano con l'estensione .php, ma possono avere qualsiasi nome o estensione che si desideri.

  2. Passare il codice PHP da eseguire direttamente da linea di comando.

    php -r 'print_r(get_defined_constants());'
    Occorre prestare molta attenzione alla sostituzione delle variabili di shell e all'uso degli apici.

    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.

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

Non si possono combinare tra loro questi tre metodi di esecuzione del codice.

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);
?>
Assumento che questo file sia chiamato test nella directory corrente, si può eseguire:
$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Come si può notare in questo caso non vi è necessità di prestare attenzione nel passare i parametri che iniziano con -.

I parametro lunghi sono disponibili dal PHP 4.3.3.

Tabella 43-3. Opzioni della linea di comando,

ParametroParametro lungoDescrizione
-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:
$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php
Se non si specifica questa opzione, il file viene ricercato nelle directory di default.

-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 è:
-d configuration_directive[=value]

Esempi (le linee vanno a capo per motivi di layout):
# Omettendo il valore si imposta la direttiva data a "1"
$ php -d max_execution_time 
      -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passando un valore vuoto si imposta la direttiva a ""
php -d max_execution_time= 
    -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# La direttiva di configurazione viene impostata a qualsiasi valore passato dopo il carattere '='
$  php -d max_execution_time=20 
       -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php 
       -d max_execution_time=doesntmakesense 
       -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

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

Nota: Questa opzione non è abbinabile all'opzione -r.

-m--modules

Utilizzare questa opzione per visualizzare i moduli PHP e di Zend integrati (e quindi caricati):
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

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

Nota: Quando si utilizza questo metodo occorre prestare attenzione ad evitare collisioni con la sostituzione delle varibili eseguita dalla shell sulla linea di comando.

Ecco un esempio che visualizza un errore di parsing
$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='
In questo caso il problema è dovuto alla sostituzione della variabile eseguita da sh/bash anche quando si usano i doppi apici ". Poichè la viriabile $foo non è definita, essa verrà espansa con 'niente' generando il seguente codice PHP:
$ php -r " = get_defined_constants();"
Il metodo corretto richiede l'uso dell'apice singolo '. Le variabili racchiuse in stringhe delimite dall'apice singolo non vengono espanse da sh/bash.
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
Se si utilizzano shell differenti rispetto a sh/bash, si potrebbe incorrere in altri problemi. In tal caso aprite una segnalazione di errore a http://bugs.php.net/ Tuttavia si può facilmente incorrere in problemi nell'avere variabili di shell nel codice o nell'utilizzare le barre rovesciate (backslash) per l'escape. Siete avvertiti.

Nota: L'opzione -r è disponibile solo nella CLI SAPI e non nella CGI SAPI.

-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.
$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

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

Nota: Questa opzione non funziona abbinata all'opzione -r.

-v--version

Visualizza le versioni di PHP, PHP SAPI, e Zend nello standard output, ad esempio:
$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-w--strip

Visualizza il sorgente senza gli spazi e i commenti.

Nota: Questa opzione non funziona abbinata all'opzione -r.

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

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

Questo è uno script PHP da linea di comando con una opzione.

  Utilizzo:
  <?php echo $argv[0]; ?> <opzione>

  <opzione> può essere qualsiasi parola che si desidera
  stampata. Con --help, -help, -h,
  o -? si ottiene questo aiuto.
<?php
} else {
    echo $argv[1];
}
?>

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:

Esempio 43-2. File batch per eseguire uno script PHP da linea di comando (script.bat)

@c:\php\cli\php.exe script.php %1 %2 %3 %4

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.

VI. Guida Funzioni

Sommario
I. Funzioni .NET
II. Funzioni Apache
III. Alternative PHP Cache
IV. Advanced PHP debugger
V. Funzioni di Array
VI. Funzioni Aspell [deprecated]
VII. Funzioni Matematiche BCMath a precisione arbitraria
VIII. PHP bytecode Compiler
IX. Funzioni di compressione Bzip2
X. Funzioni Calendar
XI. Funzioni API CCVS [deprecate]
XII. Funzioni per Classi/Oggetti
XIII. Classkit Functions
XIV. Funzioni ClibPDF
XV. Funzioni di supporto COM per Windows
XVI. Funzioni di Crack
XVII. Funzioni di tipo dei caratteri
XVIII. Funzioni CURL, Client URL Library
XIX. Funzioni di pagamento Cybercash
XX. Crédit Mutuel CyberMUT functions
XXI. Funzioni di amministrazione Cyrus IMAP
XXII. Funzioni di Data e Ora
XXIII. DB++ Functions
XXIV. Database (dbm-style) Abstraction Layer Functions
XXV. Funzioni dBase
XXVI. Funzioni DBM
XXVII. dbx Functions
XXVIII. Funzioni per l'IO diretto
XXIX. Funzioni per le directory
XXX. DOM Functions
XXXI. Funzioni DOM XML
XXXII. Funzioni di gestione degli errori e di logging
XXXIII. Exif Functions
XXXIV. Expect Functions
XXXV. File Alteration Monitor Functions
XXXVI. Funzioni Forms Data Format
XXXVII. Funzioni filePro
XXXVIII. Filesystem Functions
XXXIX. Funzioni Firebird/InterBase
XL. Firebird/Interbase Functions (PDO_FIREBIRD)
XLI. Funzioni FriBiDi
XLII. FrontBase Functions
XLIII. Funzioni FTP
XLIV. Function Handling Functions
XLV. Gettext
XLVI. Funzioni GMP
XLVII. Net_Gopher
XLVIII. Funzioni HTTP
XLIX. Hyperwave Functions
L. Hyperwave API Functions
LI. IBM DB2, Cloudscape and Apache Derby Functions
LII. ICAP Functions [deprecated]
LIII. Iconv
LIV. ID3 Functions
LV. Funzioni di Amministrazione IIS
LVI. Funzioni per le immagini
LVII. IMAP, POP3 and NNTP Functions
LVIII. Informix Functions
LIX. Ingres II Functions
LX. IRC Gateway Functions
LXI. PHP / Java Integration
LXII. KADM5
LXIII. LDAP Functions
LXIV. libxml Functions
LXV. Lotus Notes Functions
LXVI. Funzioni LZF
LXVII. Funzioni di Mail
LXVIII. mailparse Functions
LXIX. Funzioni Matematiche
LXX. MaxDB PHP Extension
LXXI. MCAL Functions
LXXII. Mcrypt Encryption Functions
LXXIII. MCVE Payment Functions
LXXIV. Memcache Functions
LXXV. Mhash Functions
LXXVI. Mimetype Functions
LXXVII. Ming functions for Flash
LXXVIII. Miscellaneous Functions
LXXIX. mnoGoSearch Functions
LXXX. Funzioni per Microsoft SQL Server
LXXXI. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
LXXXII. Mohawk Software Session Handler Functions
LXXXIII. mSQL Functions
LXXXIV. Multibyte String Functions
LXXXV. muscat Functions
LXXXVI. MySQL Functions
LXXXVII. MySQL Functions (PDO_MYSQL)
LXXXVIII. MySQL Improved Extension
LXXXIX. Ncurses Terminal Screen Control Functions
XC. Funzioni di rete
XCI. Newt Functions
XCII. NSAPI-specific Functions
XCIII. Object Aggregation/Composition Functions
XCIV. Proprietà object e method call overloading
XCV. Funzioni Oracle 8
XCVI. Funzioni ODBC (Unificate)
XCVII. ODBC and DB2 functions (PDO_ODBC)
XCVIII. oggvorbis
XCIX. OpenAL Audio Bindings
C. OpenSSL Functions
CI. Funzioni Oracle
CII. Oracle Functions (PDO_OCI)
CIII. Output Control Functions
CIV. Ovrimos SQL Functions
CV. Paradox File Access
CVI. Parsekit Functions
CVII. Process Control Functions
CVIII. Funzioni per le espressioni regolari (Perl compatibili)
CIX. PDF functions
CX. PDO Functions
CXI. PHP Opzioni&Informazioni
CXII. Funzioni POSIX
CXIII. Funzioni per le espressioni regolari (POSIX estesa)
CXIV. Funzioni PostgreSQL
CXV. PostgreSQL Functions (PDO_PGSQL)
CXVI. Funzioni per le Stampanti
CXVII. Funzioni per l'esecuzione di programmi
CXVIII. PostScript document creation
CXIX. Pspell Functions
CXX. Funzioni qtdom
CXXI. Radius
CXXII. Rar Functions
CXXIII. GNU Readline
CXXIV. GNU Recode Functions
CXXV. RPM Header Reading Funzioni
CXXVI. runkit Functions
CXXVII. Satellite CORBA client extension [deprecated]
CXXVIII. SDO Functions
CXXIX. SDO XML Data Access Service Functions
CXXX. SDO Relational Data Access Service Functions
CXXXI. Funzioni per i semafori, la memoria condivisa ed IPC
CXXXII. SESAM Database Functions
CXXXIII. PostgreSQL Session Save Handler
CXXXIV. Funzioni di gestione della sessione
CXXXV. Funzioni relative alla memoria condivisa
CXXXVI. SimpleXML functions
CXXXVII. Funzioni per SNMP
CXXXVIII. SOAP Functions
CXXXIX. Funzioni relative ai Socket
CXL. Standard PHP Library (SPL) Functions
CXLI. SQLite
CXLII. SQLite Functions (PDO_SQLITE)
CXLIII. Secure Shell2 Functions
CXLIV. Stream Functions
CXLV. Stringhe
CXLVI. Shockwave Flash Functions
CXLVII. Sybase Functions
CXLVIII. TCP Wrappers Functions
CXLIX. Tidy Functions
CL. Tokenizer Functions
CLI. Unicode Functions
CLII. URL Functions
CLIII. Funzioni per la gestione delle variabili
CLIV. Verisign Payflow Pro Functions
CLV. Funzioni vpopmail
CLVI. Funzioni W32api
CLVII. WDDX Functions
CLVIII. win32service Functions
CLIX. xattr Functions
CLX. xdiff Functions
CLXI. Funzioni relative al parser XML
CLXII. Funzioni XML-RPC
CLXIII. XMLReader functions
CLXIV. XSL functions
CLXV. Funzioni XSLT
CLXVI. YAZ Functions
CLXVII. YP/NIS Functions
CLXVIII. Funzioni per File Zip (Accesso di Sola Lettura)
CLXIX. Funzioni di compressione Zlib

I. Funzioni .NET

Introduzione

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.

Sommario
dotnet_load -- Carica un modulo DOTNET

dotnet_load

(no version information, might be only in CVS)

dotnet_load -- Carica un modulo DOTNET

Descrizione

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

II. Funzioni Apache

Introduzione

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.


Installazione

Per l'installazione di PHP su Apache vedere il capitolo sull'installazione.


Configurazione di Runtime

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.

Esempio 1. disabilitazione dell'interprete PHP in una directory mediante .htaccess

php_flag engine off

Tabella 1. Opzioni di configurazione di Apache

NomeDefaultModificabileFunzione
engineOnPHP_INI_ALLaccende o spegne l'interprete PHP
child_terminateOffPHP_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_modifiedOffPHP_INI_ALLmanda la data di modifica degli script nell'header Last-Modified:
xbithackOffPHP_INI_ALLinterpreta i file con il bit di esecuzione impostato, a prescindere dalla loro estensione

Breve descrizione dei parametri di configurazione.

engine boolean

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.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
apache_child_terminate -- Interrompe il processo apache dopo la presente richiesta
apache_get_modules -- Get a list of loaded Apache modules
apache_get_version -- Fetch Apache version
apache_getenv -- Get an Apache subprocess_env variable
apache_lookup_uri --  Esegue una richiesta parziale della URI specificata e restituisce tutte le informazioni
apache_note -- Ricava o imposta una variabile nella tabella notes di Apache
apache_request_headers -- Estrae tutti gli header della richiesta HTTP
apache_reset_timeout -- Reset the Apache write timer
apache_response_headers --  Estrae tutti gli header della risposta HTTP
apache_setenv -- Imposta una variabile Apache subprocess_env
ascii2ebcdic -- Traduce una stringa da ASCII a EBCDIC
ebcdic2ascii -- Traduce una stringa da string EBCDIC ad ASCII
getallheaders -- Estrae tutti gli header della richiesta HTTP
virtual -- Esegue una sotto-richiesta Apache

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5)

apache_child_terminate -- Interrompe il processo apache dopo la presente richiesta

Descrizione

bool apache_child_terminate ( void )

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

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5)

apache_get_modules -- Get a list of loaded Apache modules

Descrizione

array apache_get_modules ( void )

Get a list of loaded Apache modules.

Valori restituiti

An array of loaded Apache modules.

Log delle modifiche

VersioneDescrizione
5.0.0 Became available when using Apache 1, or the PHP Apache 2 filter API. Before this time, it was only available when using the Apache 2 handler API.

Esempi

Esempio 1. apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

apache_get_version

(PHP 4 >= 4.3.2, PHP 5)

apache_get_version -- Fetch Apache version

Descrizione

string apache_get_version ( void )

Fetch the Apache version.

Valori restituiti

Returns the Apache version on success, or FALSE on failure.

Log delle modifiche

VersioneDescrizione
4.3.4 Became available with Apache 1.
5.0.0 Became available with the Apache 2 filter API.

Esempi

Esempio 1. apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

Il precedente esempio visualizzerà qualcosa simile a:

Apache/1.3.29 (Unix) PHP/4.3.4

Vedere anche:

phpinfo()

apache_getenv

(PHP 4 >= 4.3.0, PHP 5)

apache_getenv -- Get an Apache subprocess_env variable

Descrizione

string apache_getenv ( string variable [, bool walk_to_top] )

Get an Apache environment variable as specified by variable.

This function requires Apache 2 otherwise it's undefined.

Elenco dei parametri

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Valori restituiti

The value of the Apache environment variable on success, or FALSE on failure

Esempi

Esempio 1. apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

Il precedente esempio visualizzerà qualcosa simile a:

42.24.42.240

Vedere anche:

apache_sentenv()
getenv()
Superglobals

apache_lookup_uri

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

apache_lookup_uri --  Esegue una richiesta parziale della URI specificata e restituisce tutte le informazioni

Descrizione

object apache_lookup_uri ( string nomefile )

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

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
    echo 'file exists!';
}
?>

Questo esempio produrrà un risultato simile al seguente:

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.php HTTP/1.1
    [method] => GET
    [mtime] => 0
    [clength] => 0
    [chunked] => 0
    [content_type] => application/x-httpd-php
    [no_cache] => 0
    [no_local_copy] => 1
    [unparsed_uri] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!

Nota: apache_lookup_uri() funziona solo quando PHP è installato come modulo Apache.

apache_note

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

apache_note -- Ricava o imposta una variabile nella tabella notes di Apache

Descrizione

string apache_note ( string nome_nota [, string valore] )

apache_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

(PHP 4 >= 4.3.0, PHP 5)

apache_request_headers -- Estrae tutti gli header della richiesta HTTP

Descrizione

array apache_request_headers ( void )

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.

Esempio 1. esempio di apache_request_headers()

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

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

(no version information, might be only in CVS)

apache_reset_timeout -- Reset the Apache write timer

Descrizione

bool apache_reset_timeout ( void )

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Note

Nota: Questa funzione è disabilitata nella modalitàsafe-mode

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_response_headers --  Estrae tutti gli header della risposta HTTP

Descrizione

array apache_response_headers ( void )

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

(PHP 4 >= 4.2.0, PHP 5)

apache_setenv -- Imposta una variabile Apache subprocess_env

Descrizione

int apache_setenv ( string varibile, string valore [, bool vai_in_cima] )

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.

Esempio 1. Impostazione di una variabile di environment di Apache utilizzando apache_setenv()

<?php
apache_setenv("EXAMPLE_VAR", "Valore di prova");
?>

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

(PHP 3 >= 3.0.17)

ascii2ebcdic -- Traduce una stringa da ASCII a EBCDIC

Descrizione

int ascii2ebcdic ( string ascii_str )

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

(PHP 3 >= 3.0.17)

ebcdic2ascii -- Traduce una stringa da string EBCDIC ad ASCII

Descrizione

int ebcdic2ascii ( string ebcdic_str )

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

(PHP 3, PHP 4, PHP 5)

getallheaders -- Estrae tutti gli header della richiesta HTTP

Descrizione

array getallheaders ( void )

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

(PHP 3, PHP 4, PHP 5)

virtual -- Esegue una sotto-richiesta Apache

Descrizione

int virtual ( string nomefile )

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

III. Alternative PHP Cache

Introduzione

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.


Installazione

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 .


Configurazione di Runtime

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

NameDefaultChangeableChangelog
apc.enabled1PHP_INI_ALL 
apc.shm_segments1PHP_INI_SYSTEM 
apc.shm_size30PHP_INI_SYSTEM 
apc.optimization0PHP_INI_ALL 
apc.num_files_hint1000PHP_INI_SYSTEM 
apc.ttl0PHP_INI_SYSTEM 
apc.gc_ttl3600PHP_INI_SYSTEM 
apc.cache_by_defaultOnPHP_INI_SYSTEM 
apc.filters""PHP_INI_SYSTEM 
apc.mmap_file_mask""PHP_INI_SYSTEM 
apc.slam_defense0PHP_INI_SYSTEM 
apc.file_update_protection2PHP_INI_SYSTEM 
apc.enable_cli0PHP_INI_SYSTEM> APC 3.0.6
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

apc.enabled boolean

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

apc.shm_segments integer

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.

apc.shm_size integer

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.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

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.

apc.ttl integer

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.

apc.gc_ttl integer

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.

apc.cache_by_default boolean

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.

apc.filters string

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.

apc.mmap_file_mask string

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.

apc.slam_defense integer

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.

apc.file_update_protection integer

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.

apc.enable-cli integer

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.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
apc_cache_info --  Retrieves cached information (and meta-data) from APC's data store
apc_clear_cache --  Clears the APC cache
apc_define_constants --  Defines a set of constants for later retrieval and mass-definition
apc_delete --  Removes a stored variable from the cache
apc_fetch --  Fetch a stored variable from the cache
apc_load_constants --  Loads a set of constants from the cache
apc_sma_info --  Retrieves APC's Shared Memory Allocation information
apc_store --  Cache a variable in the data store

apc_cache_info

(PECL)

apc_cache_info --  Retrieves cached information (and meta-data) from APC's data store

Descrizione

array apc_cache_info ( [string cache_type] )

Valori restituiti

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.

Esempi

Esempio 1. A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

apc_clear_cache

(PECL)

apc_clear_cache --  Clears the APC cache

Descrizione

bool apc_clear_cache ( [string cache_type] )

apc_define_constants

(PECL)

apc_define_constants --  Defines a set of constants for later retrieval and mass-definition

Descrizione

bool apc_define_constants ( string key, array constants [, bool case_sensitive] )

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

Elenco dei parametri

key

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

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.

case_sensitive

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

Il precedente esempio visualizzerà:

123

apc_delete

(PECL)

apc_delete --  Removes a stored variable from the cache

Descrizione

bool apc_delete ( string key )

Elenco dei parametri

key

The key used to store the value (with apc_store()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo'));
// this is obviously useless in this form
?>

Vedere anche:

apc_store()
apc_fetch()

apc_fetch

(PECL)

apc_fetch --  Fetch a stored variable from the cache

Descrizione

mixed apc_fetch ( string key )

Elenco dei parametri

key

The key used to store the value (with apc_store()).

Valori restituiti

The stored variable on success; FALSE on failure

Esempi

Esempio 1. A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

Il precedente esempio visualizzerà:

string(3) "BAR"

apc_load_constants

(PECL)

apc_load_constants --  Loads a set of constants from the cache

Descrizione

bool apc_load_constants ( string key [, bool case_sensitive] )

Elenco dei parametri

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

Il precedente esempio visualizzerà:

123

apc_sma_info

(PECL)

apc_sma_info --  Retrieves APC's Shared Memory Allocation information

Descrizione

array apc_sma_info ( void )

Valori restituiti

Array of Shared Memory Allocation data; FALSE on failure.

Esempi

Esempio 1. A apc_sma_info() example

<?php
print_r(apc_sma_info());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

apc_store

(PECL)

apc_store --  Cache a variable in the data store

Descrizione

bool apc_store ( string key, mixed var [, int ttl] )

Nota: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).

Elenco dei parametri

key

Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.

var

The variable to store

ttl

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

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

Il precedente esempio visualizzerà:

string(3) "BAR"

IV. Advanced PHP debugger

Introduzione

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


Installazione

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)


Building on Win32

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. APD Configuration Options

NameDefaultChangeableChangelog
apd.dumpdirNULLPHP_INI_ALL 
apd.statement_tracing"0"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

apd.dumpdir string

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

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


How to use PHP-APD in your scripts

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

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

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

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.


Contact information

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.

Sommario
apd_breakpoint -- Stops the interpreter and waits on a CR from the socket
apd_callstack -- Returns the current call stack as an array
apd_clunk -- Throw a warning and a callstack
apd_continue -- Restarts the interpreter
apd_croak -- Throw an error, a callstack and then exit
apd_dump_function_table -- Outputs the current function table
apd_dump_persistent_resources -- Return all persistent resources as an array
apd_dump_regular_resources -- Return all current regular resources as an array
apd_echo -- Echo to the debugging socket
apd_get_active_symbols -- Get an array of the current variables names in the local scope
apd_set_pprof_trace -- Starts the session debugging
apd_set_session_trace -- Starts the session debugging
apd_set_session -- Changes or sets the current debugging level
apd_set_socket_session_trace -- Starts the remote session debugging
override_function -- Overrides built-in functions
rename_function -- Renames orig_name to new_name in the global function_table

apd_breakpoint

(PECL)

apd_breakpoint -- Stops the interpreter and waits on a CR from the socket

Description

bool apd_breakpoint ( int debug_level )

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

apd_callstack

(no version information, might be only in CVS)

apd_callstack -- Returns the current call stack as an array

Description

array apd_callstack ( void )

Returns the current call stack as an array

Esempio 1. apd_callstack() example

<?php
print_r(apd_callstack());
?>

apd_clunk

(no version information, might be only in CVS)

apd_clunk -- Throw a warning and a callstack

Description

void apd_clunk ( string warning [, string delimiter] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack. The default line delimiter is "<BR />\n".

Esempio 1. apd_clunk() example

<?php
apd_clunk("Some Warning","<P>");
?>

apd_continue

(PECL)

apd_continue -- Restarts the interpreter

Description

bool apd_continue ( int debug_level )

Usually sent via the socket to restart the interpreter.

Esempio 1. apd_continue() example

<?php
apd_continue(0);
?>

apd_croak

(no version information, might be only in CVS)

apd_croak -- Throw an error, a callstack and then exit

Description

void apd_croak ( string warning [, string delimiter] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit. The default line delimiter is "<BR />\n".

Esempio 1. apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

apd_dump_function_table

(no version information, might be only in CVS)

apd_dump_function_table -- Outputs the current function table

Description

void apd_dump_function_table ( void )

Outputs the current function table.

Esempio 1. apd_dump_function_table() example

<?php
apd_dump_function_table();
?>

apd_dump_persistent_resources

(no version information, might be only in CVS)

apd_dump_persistent_resources -- Return all persistent resources as an array

Description

array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Esempio 1. apd_dump_persistent_resources() example

<?php
print_r(apd_dump_persistent_resources());
?>

apd_dump_regular_resources

(no version information, might be only in CVS)

apd_dump_regular_resources -- Return all current regular resources as an array

Description

array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Esempio 1. apd_dump_regular_resources() example

<?php
print_r(apd_dump_regular_resources());
?>

apd_echo

(PECL)

apd_echo -- Echo to the debugging socket

Description

bool apd_echo ( string output )

Usually sent via the socket to request information about the running script.

Esempio 1. apd_echo() example

<?php
apd_echo($i);
?>

apd_get_active_symbols

(no version information, might be only in CVS)

apd_get_active_symbols -- Get an array of the current variables names in the local scope

Description

array apd_get_active_symbols ( )

Returns the names of all the variables defined in the active scope, (not their values)

Esempio 1. apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>

apd_set_pprof_trace

(PECL)

apd_set_pprof_trace -- Starts the session debugging

Description

void apd_set_pprof_trace ( [string dump_directory] )

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.

Esempio 1. apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

apd_set_session_trace

(no version information, might be only in CVS)

apd_set_session_trace -- Starts the session debugging

Description

void apd_set_session_trace ( int debug_level [, string dump_directory] )

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

Esempio 1. apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>

apd_set_session

(no version information, might be only in CVS)

apd_set_session -- Changes or sets the current debugging level

Description

void apd_set_session ( int debug_level )

This 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

Esempio 1. apd_set_session() example

<?php
apd_set_session(9);
?>

apd_set_socket_session_trace

(no version information, might be only in CVS)

apd_set_socket_session_trace -- Starts the remote session debugging

Description

bool apd_set_socket_session_trace ( string ip_address_or_unix_socket_file, int socket_type, int port, int debug_level )

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

Esempio 1. apd_set_socket_session_trace() example

<?php
  apd_set_socket_session_trace("127.0.0.1",APD_AF_INET,7112,0);
?>

override_function

(PECL)

override_function -- Overrides built-in functions

Description

bool override_function ( string function_name, string function_args, string function_code )

Syntax similar to create_function(). Overrides built-in functions (replaces them in the symbol table).

Esempio 1. override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>

rename_function

(PECL)

rename_function -- Renames orig_name to new_name in the global function_table

Description

bool rename_function ( string original_name, string new_name )

Renames orig_name to new_name in the global function_table. Useful for temporarily overriding builtin functions.

Esempio 1. rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>

V. Funzioni di Array

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.

CASE_LOWER (integer)

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

CASE_UPPER è usata con array_change_key_case() per convertire le chiavi degli array in maiuscolo.

flag per l'ordinamento:

SORT_ASC (integer)

SORT_ASC è usata con array_multisort() per ordinare in senso crescente.

SORT_DESC (integer)

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

SORT_REGULAR è usata per comparare gli oggetti in modo normale.

SORT_NUMERIC (integer)

SORT_NUMERIC è usata per comparare gli oggetti in modo numerico.

SORT_STRING (integer)

SORT_STRING è usata per comparare gli oggetti come se fossero stringhe.

SORT_LOCALE_STRING (integer)

SORT_LOCALE_STRING è utilizzata per confrontare gli oggetti come stringhe, basandosi sul locale corrente. Aggiunto nel PHP 4.3.12 e 5.0.2.

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

EXTR_REFS (integer)

Sommario
array_change_key_case -- Restituisce un array con tutte le chiavi cambiate in maiuscolo o in minuscolo
array_chunk -- Spezza un array in tronconi
array_combine --  Crea un'array utilizzando un'array per le chiavi e un'altro per i suoi valori
array_count_values -- Conta tutti i valori di un array
array_diff_assoc -- Calcola la differenza tra due o più array con un ulteriore controllo sull'indice
array_diff_key -- Computes the difference of arrays using keys for comparison
array_diff_uassoc --  Computes the difference of arrays with additional index check which is performed by a user supplied callback function
array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparison
array_diff -- Calcola la differenza di due o più array
array_fill -- Riempie un array con i valori specificati
array_filter --  Filtra gli elementi di un array usando una funzione callback
array_flip -- Scambia tutte le chiavi di un array con i loro valori associati
array_intersect_assoc -- Calcola l'intersezione degli array con un ulteriore controllo sugli indici
array_intersect_key -- Computes the intersection of arrays using keys for comparison
array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function
array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison
array_intersect -- Calcola l'intersezione degli arrays
array_key_exists -- Controlla se l'indice (o chiave) specificato esiste nell'array
array_keys -- Restituisce tutte le chiavi di un array
array_map --  Applica la funzione callback a tutti gli elementi dell'array dato
array_merge_recursive -- Fonde due o più array in modo ricorsivo
array_merge -- Fonde uno o più array
array_multisort -- Ordina array multipli o multidimensionali
array_pad --  Riempie con un valore un array fino alla lunghezza specificata
array_pop -- Estrae l'elemento alla fine dell'array
array_product --  Calculate the product of values in an array
array_push --  Accoda uno o più elementi ad un array
array_rand --  Estrae a caso uno o più elementi da un array
array_reduce --  Riduce iterativamente l'array a un singolo valore utilizzando una funzione callback
array_reverse --  Restituisce un array con gli elementi in ordine invertito
array_search --  Ricerca un dato valore in un array e ne restituisce la chiave corrispondente, se la ricerca ha successo.
array_shift --  Estrae l'elemento alla testa dell'array
array_slice -- Estrae un sottoinsieme da un array
array_splice --  Rimuove una porzione dell'array e la sostituisce con altro
array_sum --  Calcola la somma dei valori di un array
array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function
array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function
array_udiff -- Computes the difference of arrays by using a callback function for data comparison
array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback function
array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
array_uintersect -- Computes the intersection of arrays, compares data by a callback function
array_unique -- Rimuove i valori duplicati di un array
array_unshift --  Inserisce uno o più elementi all'inizio dell'array
array_values -- Restituisce tutti i valori di un array
array_walk_recursive --  Apply a user function recursively to every member of an array
array_walk --  Esegue una funzione su ogni elemento dell'array
array --  Crea un array
arsort --  Ordina un array in ordine decrescente e mantiene le associazioni degli indici
asort -- Ordina un array e mantiene le associazioni degli indici
compact --  Crea un array contenente variabili e il loro valore
count -- Conta gli elementi in una variabile, o le proprietà in un oggetto
current -- Restituisce l'elemento corrente di un array
each --  Restituisce la corrente coppia chiave/valore di un array e incrementa il puntatore dell'array
end --  Sposta il puntatore interno dell'array all'ultimo elemento
extract --  Importa le variabili nella tabella dei simboli
in_array -- Controlla se un valore è presente in un array
key -- Estrae la chiave corrente da un array associativo
krsort -- Ordina rispetto alle chiavi di un array in ordine inverso
ksort -- Ordina rispetto alle chiavi di un array
list --  Assegna valori a delle variabili come se fossero un array
natcasesort --  Ordina un array usando un algoritmo di "ordine naturale" non sensibile alle maiuscole/minuscole
natsort --  Ordina un array usando un algoritmo di "ordine naturale"
next --  Incrementa il puntatore interno dell'array
pos -- Restituisce l'elemento corrente di un array
prev -- Decrementa il puntatore interno dell'array
range --  Crea un array contenente una serie di elementi
reset --  Reimposta il puntatore interno di un array sulla posizione iniziale
rsort -- Ordina un array in ordine decrescente
shuffle -- Mescola un array
sizeof -- Alias di count()
sort -- Ordina un array
uasort --  Ordina un array mediante una funzione definita dall'utente e mantiene le associazioni
uksort --  Ordina rispetto alle chiavi di un array mediante una funzione definita dall'utente
usort --  Ordina un array mediante una funzione definita dall'utente

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case -- Restituisce un array con tutte le chiavi cambiate in maiuscolo o in minuscolo

Descrizione

array array_change_key_case ( array input [, int case] )

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

Esempio 1. esempio di array_change_key_case()

<?php
$input_array = array("PriMo" => 1, "SecOndO" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

Il precedente esempio visualizzerà:

Array
(
    [PRIMO] => 1
    [SECONDO] => 2
)

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

(PHP 4 >= 4.2.0, PHP 5)

array_chunk -- Spezza un array in tronconi

Descrizione

array array_chunk ( array input, int dimensione [, bool mantieni_chiavi] )

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

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

array_combine

(PHP 5)

array_combine --  Crea un'array utilizzando un'array per le chiavi e un'altro per i suoi valori

Descrizione

array array_combine ( array keys, array values )

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

Esempio 1. Esempio di array_combine()

<?php
$a = array('verde', 'rosso', 'giallo');
$b = array('avocado', 'mela', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

Il risultato è:

Array
(
    [verde]  => avocado
    [rosso]  => mela
    [giallo] => banana
)

Vedere anche array_merge(), array_walk() e array_values().

array_count_values

(PHP 4, PHP 5)

array_count_values -- Conta tutti i valori di un array

Descrizione

array array_count_values ( array input )

array_count_values() restituisce un array che ha i valori dell'array input per chiavi e la loro frequenza in input come valori.

Esempio 1. Esempio di array_count_values()

<?php
$array = array(1, "ciao", 1, "mondo", "ciao");
print_r(array_count_values($array));
?>

Il precedente esempio visualizzerà:

Array
(
    [1] => 2
    [ciao] => 2
    [mondo[ => 1
)

Vedere anche count(), array_unique(), array_values() e count_chars().

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc -- Calcola la differenza tra due o più array con un ulteriore controllo sull'indice

Descrizione

array array_diff_assoc ( array array1, array array2 [, array ...] )

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

<?php
$array1 = array("a" => "verde", "b" => "marrone", "c" => "blu", "rosso");
$array2 = array("a" => "verde", "giallo", "rosso");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

Il risultato è:

Array
(
    [b] => marrone
    [c] => blu
    [0] => rosso
)

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

(PHP 5 >= 5.1.0RC1)

array_diff_key -- Computes the difference of arrays using keys for comparison

Description

array array_diff_key ( array array1, array array2 [, array ...] )

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

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

Il precedente esempio visualizzerà:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

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

array_diff_uassoc

(PHP 5)

array_diff_uassoc --  Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Description

array array_diff_uassoc ( array array1, array array2 [, array ..., callback key_compare_func] )

array_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

<?php
function key_compare_func($a, $b) 
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

Il precedente esempio visualizzerà:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

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

array_diff_ukey

(PHP 5 >= 5.1.0RC1)

array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparison

Description

array array_diff_ukey ( array array1, array array2 [, array ..., callback key_compare_func] )

array_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

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

Il precedente esempio visualizzerà:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

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

(PHP 4 >= 4.0.1, PHP 5)

array_diff -- Calcola la differenza di due o più array

Descrizione

array array_diff ( array array1, array array2 [, array ...] )

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

<?php
$array1 = array("a" => "verde", "rosso", "blu", "rosso");
$array2 = array("b" => "verde", "giallo", "rosso");
$risultato = array_diff($array1, $array2);

print_r($result);
?>

Occorrenze multiple in $array1 sono tutte trattate nello stesso modo. Questo codice mostrerà:

Array
(
    [1] => blu
)

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

(PHP 4 >= 4.2.0, PHP 5)

array_fill -- Riempie un array con i valori specificati

Descrizione

array array_fill ( int inizio, int num, mixed valore )

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.

Esempio 1. esempio di array_fill()

<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>

$a ora è:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

Vedere anche str_repeat() e range().

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter --  Filtra gli elementi di un array usando una funzione callback

Descrizione

array array_filter ( array input [, callback callback] )

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

<?php
function dispari($var) 
{
    return($var % 2 == 1);
}

function pari($var) 
{
    return($var % 2 == 0);
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Dispari :\n";
print_r(array_filter($array1, "dispari");
echo "Pari :\n";
print_r(array_filter($array2, "pari");
?>

Il precedente esempio visualizzerà:

Dispari :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Pari:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

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.

Esempio 2. array_filter() senza callback

<?php

$entry = array(
             0 => 'pippo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r(array_filter($entry));
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => pippo
    [2] => -1
)

Vedere anche array_map() e array_reduce().

array_flip

(PHP 4, PHP 5)

array_flip -- Scambia tutte le chiavi di un array con i loro valori associati

Descrizione

array array_flip ( array trans )

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.

Esempio 1. Esempio di array_flip()

<?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?>

Esempio 2. Esempio di array_flip(): collisione

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

ora $trans è:

Array
(
    [1] => b
    [2] => c
)

Vedere anche array_values(), array_keys() e array_reverse().

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_intersect_assoc -- Calcola l'intersezione degli array con un ulteriore controllo sugli indici

Descrizione

array array_intersect_assoc ( array array1, array array2 [, array ...] )

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

Esempio 1. esempio di array_intersect_assoc()

<?php
$array1 = array("a" => "verde", "b" => "marrone", "c" => "blu", "rosso");
$array2 = array("a" => "verde", "giallo", "rosso");
$result_array = array_intersect_assoc($array1, $array2);
?>

$result_array sarà:

Array
(
    [a] => verde
)

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

array_intersect_key

(PHP 5 >= 5.1.0RC1)

array_intersect_key -- Computes the intersection of arrays using keys for comparison

Description

array array_intersect_key ( array array1, array array2 [, array ...] )

array_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

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));
?>

Il precedente esempio visualizzerà:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
})

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

array_intersect_uassoc

(PHP 5)

array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function

Description

array array_intersect_uassoc ( array array1, array array2 [, array ..., callback key_compare_func] )

array_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

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

Il precedente esempio visualizzerà:

Array
(
    [b] => brown
)

See also array_intersect(), array_intersect_assoc(), array_uintersect_assoc(), array_uintersect_uassoc(), array_intersect_key() and array_intersect_ukey().

array_intersect_ukey

(PHP 5 >= 5.1.0RC1)

array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison

Description

array array_intersect_ukey ( array array1, array array2 [, array ..., callback key_compare_func] )

array_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

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

Il precedente esempio visualizzerà:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
})

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

(PHP 4 >= 4.0.1, PHP 5)

array_intersect -- Calcola l'intersezione degli arrays

Descrizione

array array_intersect ( array array1, array array2 [, array ...] )

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.

Esempio 1. Esempio di array_intersect()

<?php
$array1 = array("a" => "verde", "rosso", "blu");
$array2 = array("b" => "verde", "giallo", "rosso");
$risultato = array_intersect($array1, $array2);
?>

In questo modo $result sarà:

Array
(
    [a] => verde
    [0] => rosso
)

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

array_key_exists

(PHP 4 >= 4.1.0, PHP 5)

array_key_exists -- Controlla se l'indice (o chiave) specificato esiste nell'array

Descrizione

bool array_key_exists ( mixed chiave, array cerca )

array_key_exists() restituisce TRUE se il parametro chiave esiste nell'array. chiave può essere qualsiasi valore accettabile per un indice di array.

Esempio 1. esempio di array_key_exists()

<?php
$un_array = array("primo" => 1, "secondo" => 4);
if (array_key_exists("primo", $un_array)) {
    echo "L'elemento 'primo' è nell'array";
    }
    ?>

Nota: Il nome di questa funzione è key_exists() nel PHP 4.0.6.

Vedere anche isset(), array_keys() e in_array().

array_keys

(PHP 4, PHP 5)

array_keys -- Restituisce tutte le chiavi di un array

Descrizione

array array_keys ( array input [, mixed valore_ricerca] )

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

?php
$array = array(0 => 100, "colore" => "rosso");
print_r(array_keys($array))

$array = array("blu", "rosso", "verde", "blu", "blu");
print_r(array_keys($array, "blu"));

$array = array("colore" => array("blu", "rosso", "verde"),
               "misura" =&gt; array("piccola", "media", "grande"));
print_r(array_keys($array));
?>

Il risultato di questo programma sarà:

Array
(
    [0] => 0
    [1] => colore
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => colore
    [1] => misura
)

Vedere anche array_values() e array_key_exists().

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map --  Applica la funzione callback a tutti gli elementi dell'array dato

Descrizione

array array_map ( callback funzione, array arr1 [, array ...] )

array_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 1. Esempio di array_map()

<?php
function cubo($n) 
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cubo", $a);
print_r($b);
?>

In questo modo $b sarà:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Esempio 2. array_map() - usare più array

<?php
function mostra_Spagnolo($n, $m) 
{
    return("Il numero $n si dice $m in Spagnolo");
}

function mappa_Spagnolo($n, $m) 
{
    return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("mostra_Spagnolo", $a, $b);
print_r($c);

$d = array_map("mappa_Spagnolo", $a, $b);
print_r($d);
?>

Il precedente esempio visualizzerà:

//stampa di $c
Array
(
    [0] => Il numero 1 si dice uno in Spagnolo
    [1] => Il numero 2 si dice dos in Spagnolo
    [2] => Il numero 3 si dice tres in Spagnolo
    [3] => Il numero 4 si dice cuatro in Spagnolo
    [4] => Il numero 5 si dice cinco in Spagnolo
)

// stampa di $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

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

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("uno", "due", "tre", "quattro", "cinque");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => uno
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => due
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => tre
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => quattro
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => cinque
            [2] => cinco
        )

)

Vedere anche array_filter(), array_reduce(), array_walk() e information about the callback type.

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive -- Fonde due o più array in modo ricorsivo

Descrizione

array array_merge_recursive ( array array1, array array2 [, array ...] )

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

<?php
$ar1 = array("colore" => array ("preferito" => "rosso"), 5);
$ar2 = array(10, "colore" => array ("preferito" => "verde", "blu"));
$risultato = array_merge_recursive($ar1, $ar2);
?>

La variabile $risultato sarà:

Array
(
    [colore] => Array
        (
             [preferito] => Array
                (
                    [0] => rosso
                    [1] => verde
                )

            [0] => blu
        )

    [0] => 5
    [1] => 10
)

Vedere anche array_merge().

array_merge

(PHP 4, PHP 5)

array_merge -- Fonde uno o più array

Descrizione

array array_merge ( array array1 [, array array2 [, array ...]] )

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

<?php
$array1 = array("colore" => "rosso", 2, 4);
$array2 = array("a", "b", "colore" => "verde", "forma" => "trapezio", 4);
$risultato = array_merge($array1, $array2);
print_r($risultato);
?>

La variabile $risultato sarà:

Array
(
    [colore] => verde
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [forma] => trapezio
    [4] => 4
)

Esempio 2. Esempio di array_merge()

<?php
$array1 = array();
$array2 = array(1 => "dati");
$result = array_merge($array1, $array2);
?>

Non dimenticarsi che le chiavi numeriche saranno rinumerate!

Array
(
    [0] => data
)

Se si vogliono preservare gli array e li si vuole solo concatenare, usare l'operatore +:

<?php
$array1 = array();
$array2 = array(1 => "dati");
$result = $array1 + $array2;
?>

La chiave numerica sarà preservata e così pure l'associazione.

Array
(
    [1] => data
)

Esempio 3. esempio di array_merge()

<?php
$array_uno = array(0 => "mario", 1 => "roberto", 2 => "andrea", 3 => "dante");
$array_due = array("mario => "roberto", "andrea" => "dante", "mario" => "giacomo");

unset($array_uno[2]);

$risultato_uno = array_merge($array_uno);
$risultato_due = array_merge($array_due);

print_r($risultato_uno);
print_r($risultato_due);
?>

Il risultato sarà:

Array
(
    [0] => mario
    [1] => roberto
    [2] => dante
)
Array
(
    [mario] => giacomo
    [andrea] => dante
)

Nota: Le chiavi condivise verranno sovrascritte dalla prima chiave processata.

Vedere anche array_merge_recursive() e array_combine() e operatori sugli array.

array_multisort

(PHP 4, PHP 5)

array_multisort -- Ordina array multipli o multidimensionali

Descrizione

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, 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

<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

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.

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(1)
  [1]=> int(1)
  [2]=> string(1) "2"
  [3]=> int(3)
}

Esempio 2. Ordinamento di array multidimensionali

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

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

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

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:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

I dati sono in un array, chiamato data. Di solito questo si ottiene ciclando, ad esempio, con mysql_fetch_assoc().

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

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.

<?php
// Ottiene un array di colonne
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Ordina 'volume' in senso discendente, 'edition' in senso ascendente
// Aggiungere $data come ultimo parametr per ordinare sulla chiave comune
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

Il set di dati è ora ordinato, e apparirà così:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

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.

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

array_pad

(PHP 4, PHP 5)

array_pad --  Riempie con un valore un array fino alla lunghezza specificata

Descrizione

array array_pad ( array input, int pad_size, mixed pad_value )

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

<?php
$input = array(12, 10, 9);

$risultato = array_pad($input, 5, 0);
// risultato diventa array(12, 10, 9, 0, 0)

$risultato = array_pad($input, -7, -1);
// risultato diventa array(-1, -1, -1, -1, 12, 10, 9)

$risultato = array_pad($input, 2, "noop");
// ridimensionamento non efettuato
?>

Vedere anche array_fill() e range().

array_pop

(PHP 4, PHP 5)

array_pop -- Estrae l'elemento alla fine dell'array

Descrizione

mixed array_pop ( array array )

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.

Nota: Questa funzione farà il reset() del puntatore dell'array dopo l'uso.

Esempio 1. esempio di array_pop()

<?php
$pila = array("arancia", "banana", "mela", "lampone");
$frutto = array_pop($pila);
print_r($pila);
?>

Dopo questa istruzione, $pila avrà solo 3 elementi:

Array
(
    [0] => arancia
    [1] => banana
    [2] => mela
)

e lampone verrà assegnato alla variabile $frutto.

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

(PHP 5 >= 5.1.0RC1)

array_product --  Calculate the product of values in an array

Description

number array_product ( array array )

array_product() returns the product of values in an array as an integer or float.

Esempio 1. array_product() examples

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>

Il precedente esempio visualizzerà:

product(a) = 384

array_push

(PHP 4, PHP 5)

array_push --  Accoda uno o più elementi ad un array

Descrizione

int array_push ( array array, mixed var [, mixed ...] )

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;
?>
ripetuto per ogni var.

Restituisce il nuovo numero di elementi nell'array.

Esempio 1. esempio di array_push()

<?php
$pila = array("arancia", "banana");
array_push($pila, "mela", "lampone");
print_r($pila);
?>

In questo esempio $pila avrà i seguenti elementi:

Array
(
    [0] => arancia
    [1] => banana
    [2] => mela
    [3] => lampone
)

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

(PHP 4, PHP 5)

array_rand --  Estrae a caso uno o più elementi da un array

Descrizione

mixed array_rand ( array input [, int num_req] )

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.

Esempio 1. esempio di array_rand()

<?
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$chiavi = array_rand($input, 2);
echo $input[$chiavi[0]] . "\n";
echo $input[$chiavi[1]] . "\n";
?>

Vedere anche shuffle().

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce --  Riduce iterativamente l'array a un singolo valore utilizzando una funzione callback

Descrizione

mixed array_reduce ( array input, callback funzione [, int initial] )

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

Esempio 1. esempio di array_reduce()

<?php
function rsum($v, $w) 
{
    $v += $w;
    return $v;
}

function rmul($v, $w) 
{
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?>

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

(PHP 4, PHP 5)

array_reverse --  Restituisce un array con gli elementi in ordine invertito

Descrizione

array array_reverse ( array array [, bool mantieni_chiavi] )

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

<?php
$input  = array("php", 4.0, array("verde", "rosso"));
$risultato = array_reverse($input);
$resultato_chiavi = array_reverse($input, true);
?>

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

Array
(
    [0] => Array
        (
            [0] => verde
            [1] => rosso
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => verde
            [1] => rosso
        )

    [1] => 4
    [0] => php
)

Nota: Il secondo parametro è stato aggiunto in PHP 4.0.3.

Vedere anche array_flip().

array_search

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

Descrizione

mixed array_search ( mixed ago, array pagliaio [, bool strict] )

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.

Esempio 1. esempio di array_search()

<?php
$array = array(0 => 'blu', 1 => 'rosso', 2 => 'verde', 3 => 'rosso');

$chiave = array_search('verde', $array); // $chiave = 2;
$chiave = array_search('rosso', $array); // $chiave = 1;
?>

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

(PHP 4, PHP 5)

array_shift --  Estrae l'elemento alla testa dell'array

Descrizione

mixed array_shift ( array 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.

Nota: Questa funzione farà il reset() del puntatore dell'array dopo l'uso.

Esempio 1. esempio di array_shift()

<?php
$pila = array("arancia", "banana", "mela", lampone");
$frutto = array_shift($pila);
print_r($pila);
?>

In questo modo $pila rimarrà con 3 elementi:

Array
(
    [0] => banana
    [1] => mela
    [2] => lampone
)

e arancia sarà assegnata a $frutto.

Vedere anche array_unshift(), array_push() e array_pop().

array_slice

(PHP 4, PHP 5)

array_slice -- Estrae un sottoinsieme da un array

Descrizione

array array_slice ( array array, int offset [, int length] )

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

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // restituisce "c", "d" e "e"
$output = array_slice($input, 2, -1);  // restituisce "c", "d"
$output = array_slice($input, -2, 1);  // restituisce "d"
$output = array_slice($input, 0, 3);   // restituisce "a", "b" e "c"
?>

Vedere anche array_splice() e unset().

array_splice

(PHP 4, PHP 5)

array_splice --  Rimuove una porzione dell'array e la sostituisce con altro

Descrizione

array array_splice ( array &input, int offset [, int length [, array replacement]] )

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

<?php
$input = array("rosso", "verde", "blu", "giallo");
array_splice($input, 2);
// $input è ora array("rosso", "verde")

$input = array("rosso", "verde", "blu", "giallo");
array_splice($input, 1, -1);
// $input è ora array("rosso", "giallo")

$input = array("rosso", "verde", "blu", "giallo");
array_splice($input, 1, count($input), "arancio");
// $input è ora array("rosso", "arancio")

$input = array("rosso", "verde", "blu", "giallo");
array_splice($input, -1, 1, array("nero", "marrone"));
// $input è ora array("rosso", "verde",
//          "blu", "nero", "marrone")

$input = array("rosso", "verde", "blu", "giallo");
array_splice($input, 3, 0, "viola");
// $input è ora array("rosso", "verde",
//          "blu", "viola", "giallo");
?>

Vedere anche array_slice()i, unset() e array_merge().

array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sum --  Calcola la somma dei valori di un array

Descrizione

mixed array_sum ( array array )

array_sum() restituisce la somma dei valori dell'array sotto forma di integer o float.

Esempio 1. esempi di array_sum()

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

Il precedente esempio visualizzerà:

sum(a) = 20
sum(b) = 6.9

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

array_udiff_assoc

(PHP 5)

array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function

Description

array array_udiff_assoc ( array array1, array array2 [, array ..., callback data_compare_func] )

array_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

<?php
class cr {
    private $priv_member;
    function cr($val) 
    {
        $this->priv_member = $val;
    }
    
    function comp_func_cr($a, $b) 
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

Il precedente esempio visualizzerà:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

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

array_udiff_uassoc

(PHP 5)

array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Description

array array_udiff_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func] )

array_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

<?php
class cr {
    private $priv_member;
    function cr($val) 
    {
        $this->priv_member = $val;
    }

    function comp_func_cr($a, $b) 
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
    
    function comp_func_key($a, $b) 
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

Il precedente esempio visualizzerà:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

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

array_udiff

(PHP 5)

array_udiff -- Computes the difference of arrays by using a callback function for data comparison

Description

array array_udiff ( array array1, array array2 [, array ..., callback data_compare_func] )

array_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

<?php
class cr {
    private $priv_member;
    function cr($val) 
    {
        $this->priv_member = $val;
    }
    
    function comp_func_cr($a, $b) 
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

Il precedente esempio visualizzerà:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

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

array_uintersect_assoc

(PHP 5)

array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback function

Description

array array_uintersect_assoc ( array array1, array array2 [, array ..., callback data_compare_func] )

array_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

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

Il precedente esempio visualizzerà:

Array
(
    [a] => green
)

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

array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

Description

array array_uintersect_uassoc ( array array1, array array2 [, array ..., callback data_compare_func, callback key_compare_func] )

array_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

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

Il precedente esempio visualizzerà:

Array
(
    [a] => green
    [b] => brown
)

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

array_uintersect

(PHP 5)

array_uintersect -- Computes the intersection of arrays, compares data by a callback function

Description

array array_uintersect ( array array1, array array2 [, array ..., callback data_compare_func] )

array_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

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

Il precedente esempio visualizzerà:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

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

(PHP 4 >= 4.0.1, PHP 5)

array_unique -- Rimuove i valori duplicati di un array

Descrizione

array array_unique ( array array )

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.

Esempio 1. esempio di array_unique()

<?php
$input = array("a" => "verde", "rosso", "b" => "verde", "blu", "rosso");
$risultato = array_unique($input);
print_r($result);
?>

Questo mostrerà:

Array
(
    [b] => verde
    [1] => blu
    [2] => rosso
)

Esempio 2. array_unique() e i tipi

<?php
$input = array(4, "4", "3", 4, 3, "3");
$risultato = array_unique($input);
var_dump($risultato);
?>

Questo script mostrerà:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

array_unshift

(PHP 4, PHP 5)

array_unshift --  Inserisce uno o più elementi all'inizio dell'array

Descrizione

int array_unshift ( array array, mixed var [, mixed ...] )

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.

Esempio 1. esempio di array_unshift()

<?php
$lista = array("arancia", "banana");
array_unshift($lista, "mela", "lampone");
?>

In questo modo $lista conterrà i seguenti elementi:

Array
(
    [0] => mela
    [1] => lampone
    [2] => arancia
    [3] => banana
)

Vedere anche array_shift(), array_push() e array_pop().

array_values

(PHP 4, PHP 5)

array_values -- Restituisce tutti i valori di un array

Descrizione

array array_values ( array input )

array_values() restituisce tutti i valori dell'array input e indicizza numericamente l'array.

Esempio 1. esempio di array_values()

<?php
$array = array("taglia" => "XL", "colore" => "oro");
print_r(array_values($array));
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => XL
    [1] => oro
)

Vedere anche array_keys().

array_walk_recursive

(PHP 5)

array_walk_recursive --  Apply a user function recursively to every member of an array

Description

bool array_walk_recursive ( array &input, callback funcname [, mixed userdata] )

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

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key) 
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

Il precedente esempio visualizzerà:

a holds apple
b holds banana
sour holds lemon

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.

array_walk

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

array_walk --  Esegue una funzione su ogni elemento dell'array

Descrizione

bool array_walk ( array &array, callback funzione [, mixed datiutente] )

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

<?php
$frutta = array("d"=>"limone", "a"=>"arancia", "b"=>"banana", "c"=>"mela");

function modifica(&$elemento1, $chiave, $prefisso) 
{
    $elemento1 = "$prefisso: $elemento1";
}

function stampa($elemento2, $chiave) 
{
    echo "$chiave. $elemento2<br />\n";
}

echo "Prima ...:\n";
array_walk($frutta, 'stampa');

array_walk($frutta, 'modifica', 'frutto');
echo "... e dopo:\n";

array_walk($frutta, 'stampa');
?>

Il risultato del programma sarà:

Prima ...:
d. limone
a. arancia
b. banana
c. mela
... e dopo:
d. frutto: limone
a. frutto: arancia
b. frutto: banana
c. frutto: mela

Vedere anche array_walk_recursive(), create_function(), list(), foreach, each(), call_user_func_array() e array_map()

array

(PHP 3, PHP 4, PHP 5)

array --  Crea un array

Descrizione

array array ( [mixed ...] )

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.

Esempio 1. Esempio di array()

<?php
$frutta = array (
    "frutta"  => array("a" => "arancia", "b" => "banana", "c" => "mela"),
    "numeri"  => array(1, 2, 3, 4, 5, 6),
    "buche"   => array("prima", 5 => "seconda", "terza")
)
?>

Esempio 2. Indice automatico con array()

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

che stamperà:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

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

Esempio 3. Indice 1-based con array()

<?php
$primotrimestre = array(1 => 'Gennaio', 'Febbraio', 'Marzo');
print_r($primotrimestre);
?>

che stamperà:

Array
(
    [1] => Gennaio
    [2] => Febbraio
    [3] => Marzo
)

Vedere anche array_pad(), list(), foreach e range().

arsort

(PHP 3, PHP 4, PHP 5)

arsort --  Ordina un array in ordine decrescente e mantiene le associazioni degli indici

Descrizione

bool arsort ( array array [, int sort_flags] )

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.

Esempio 1. esempio di arsort()

<?php
$frutta = array("d" => "limone", "a" => "arancia", "b" => "banana", "c" => "mela");
arsort($frutta);
reset($frutta);
while (list($chiave, $valore) = each($frutta)) {
    echo "$chiave = $valore\n";
}
?>

Questo esempio mostrerà:

c = mela
d = limone
b = banana
a = arancia

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

vedere anche asort(), rsort(), ksort() e sort().

asort

(PHP 3, PHP 4, PHP 5)

asort -- Ordina un array e mantiene le associazioni degli indici

Descrizione

bool asort ( array array [, int sort_flags] )

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.

Esempio 1. esempio di asort()

<?php
$frutta = array("d"=>"limone", "a"=>"arancia", "b"=>"banana", "c"=>"mela");
asort($frutta);
reset($frutta);
while (list($chiave, $valore) = each($frutta)) {
    echo "$chiave = $valore\n";
}
?>

Questo esempio mostrerà:

a = arancia
b = banana
d = limone
c = mela

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

Vedere anche arsort(), rsort(), ksort() e sort().

compact

(PHP 4, PHP 5)

compact --  Crea un array contenente variabili e il loro valore

Descrizione

array compact ( mixed varname [, mixed ...] )

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

Esempio 1. esempio di compact()

<?php
$citta = "Milano";
$provincia = "MI";
$evento = "SMAU";

$var_luoghi = array("citta", "provincia");

$risultato = compact("evento", "niente", $var_luoghi);
?>

In questo modo, $risultato sarà:

Array
(
    [event] => SMAU
    [citta] => Milano
    [provincia] => MI
)

Vedere anche extract().

count

(PHP 3, PHP 4, PHP 5)

count -- Conta gli elementi in una variabile, o le proprietà in un oggetto

Descrizione

int count ( mixed var [, int mode] )

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 1. esempio di count()

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$risultato = count($a);
//$risultato == 3

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
$risultato = count($b);
// $risultato == 3;

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?>

Esempio 2. esempio di count() ricorsiva (PHP >= 4.2.0)

<?php
$cibo = array('frutta' => array('arancia', 'banana', 'mela'),
              'verdura' => array('carota', 'zucchina', 'piselli'));

// conteggio ricorsivo
echo count($cibp,COUNT_RECURSIVE); // output 8

// conteggio normale
echo count($cibo);                 // output 2

?>

Vedere anche is_array(), isset() e strlen().

current

(PHP 3, PHP 4, PHP 5)

current -- Restituisce l'elemento corrente di un array

Descrizione

mixed current ( array array )

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
$trasporti = array('piedi', 'bicicletta', 'automobile', 'aereo');
$mode = current($trasporti); // $mode = 'piedi';
$mode = next($trasporti);    // $mode = 'bicicletta';
$mode = current($trasporti); // $mode = 'bicicletta';
$mode = prev($trasporti);    // $mode = 'piedi';
$mode = end($trasporti);     // $mode = 'aereo';
$mode = current($trasporti); // $mode = 'aereo';
?>

Vedere anche end(), key(), next(), prev() e reset().

each

(PHP 3, PHP 4, PHP 5)

each --  Restituisce la corrente coppia chiave/valore di un array e incrementa il puntatore dell'array

Descrizione

array each ( array array )

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

Esempio 1. esempi dieach()

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar ora contiene la seguente coppia chiave/valore:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

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

Esempio 2. Attraversamento di un array con each()

<?php
$frutta = array('a' => 'albicocca', 'b' => 'banana', 'c' => 'ciliegia');

reset($frutta);
while (list($chiave, $valore) = each($frutta)) {
    echo "$chiave => $valore\n";
}
?>

Outputs:

a => albicocca
b => banana
c => ciliegia

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

(PHP 3, PHP 4, PHP 5)

end --  Sposta il puntatore interno dell'array all'ultimo elemento

Descrizione

mixed end ( array array )

end() fa avanzare il puntatore di array all'ultimo elemento, e restituisce il suo valore.

Esempio 1. Un semplice esempio di end()

<?php

$frutti = array('mela', 'banana', 'mirtillo');
echo end($frutti); // mirtillo
      
?>

Vedere anche current(), each(), prev(), next() e reset().

extract

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

extract --  Importa le variabili nella tabella dei simboli

Descrizione

int extract ( array var_array [, int extract_type [, string prefix]] )

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:

EXTR_OVERWRITE

Se avviene una collisione, sovrascrive la variabile esistente.

EXTR_SKIP

Se avviene una collisione, non sovrascrive la variabile esistente.

EXTR_PREFIX_SAME

Se avviene una collisione, mette come prefisso al nome della variabile il parametro prefix.

EXTR_PREFIX_ALL

Mette come prefisso di tutte le variabili il parametro prefix. Dal PHP 4.0.5 questo avviene anche per i valori numerici.

EXTR_PREFIX_INVALID

Mette come prefisso, solo per i nomi di variabili invalidi/numerici, il parametro prefix. Questa opzione è stata aggiunta in PHP 4.0.5.

EXTR_IF_EXISTS

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.

EXTR_PREFIX_IF_EXISTS

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.

EXTR_REFS

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

<?php

/* Si supponga che $array_variabili sia un array restituito da
   wddx_deserialize */

$dimensione = "grande";
$array_variabili = array("colore" => "blu",
                         "dimensione"  => "media",
                         "forma" => "sfera");
extract($array_variabili, EXTR_PREFIX_SAME, "wddx");

echo "$colore, $dimensione, $forma, $wddx_dimensione\n";

?>

L'esempio mostrerà:

blu, grande, sfera, media

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

in_array

(PHP 4, PHP 5)

in_array -- Controlla se un valore è presente in un array

Descrizione

bool in_array ( mixed ago, array pagliaio [, bool strict] )

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

<?
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Trovato Irix";
}
if (in_array("mac", $os)) {
    echo "Trovato mac";
}
?>

La seconda condizione fallisce perché in_array() tiene conto di maiuscole e minuscole, quindi il programma mostrerà:

Trovato Irix

Esempio 2. esempio di in_array() con strict

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' trovato con controllo strict\n"
}

if (in_array(1.13, $a, true)) {
    echo "1.13 trovato con controllo strict\n"
}
?>

Questo mostrerà:

1.13 trovato con controllo strict

Esempio 3. in_array() con un array come ago

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' trovato\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' non trovato\n";
}

if (in_array('o', $a)) {
    echo "'o' trovato\n";
}
?>

Questo ritornerà:

'ph' trovato
  'o' trovato

Vedere anche array_search(), array_key_exists() e isset().

key

(PHP 3, PHP 4, PHP 5)

key -- Estrae la chiave corrente da un array associativo

Descrizione

mixed key ( array array )

key() restituisce la chiave corrispondente all'attuale posizione del puntatore interno all'array.

Esempio 1. esempio di key()

<?php
$array = array(
    'frutto1' => 'mela',
    'frutto2' => 'arancia',
    'frutto3' => 'uva',
    'frutto4' => 'mela',
    'frutto5' => 'mela');

// questo ciclo mostra tutte le chiavi
// dell'array associativo che sono uguali a 'mela'
while ($nome_frutto = current($array)( {
    if ($nome_frutto == 'mela') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

Vedere anche current() e next().

krsort

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

krsort -- Ordina rispetto alle chiavi di un array in ordine inverso

Descrizione

bool krsort ( array array [, int sort_flags] )

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.

Esempio 1. Esempio di krsort()

<?php
$frutti = array("d"=>"limone", "a"=>"arancio", "b"=>"banana", "c"=>"mela");
krsort($frutti);
reset($frutti);
while (list($chiave, $valore) = each($frutti)) {
    echo "$chiave = $valore\n";
}
?>

Questo esempio mostrerà:

d = limone
c = mela
b = banana
a = arancio

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

ksort

(PHP 3, PHP 4, PHP 5)

ksort -- Ordina rispetto alle chiavi di un array

Descrizione

bool ksort ( array array [, int sort_flags] )

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.

Esempio 1. esempio di ksort()

<?php
$frutti = array("d"=>"limone", "a"=>"arancia", "b"=>"banana", "c"=>"mela");
ksort($frutti);
reset($frutti);
while (list($chiave, $valore) = each($frutti)) {
    echo "$chiave = $valore\n";
}
?>

Questo esempio mostrerà:

a = arancia
b = banana
c = mela
d = limone

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.

list

(PHP 3, PHP 4, PHP 5)

list --  Assegna valori a delle variabili come se fossero un array

Descrizione

void list ( mixed ... )

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

<?php

$info = array('caffè', 'scuro', 'caffeina');

// assegna a tutte le variabili
list($bevanda, $colore, $componente) = $info;
echo "Il $bevanda è $colore e la $componente lo rende speciale.\n";

// assegna solo in parte
list($bevanda, , $componente) = $info;
echo "Il $bevanda ha la $componente.\n";

// oppure assegnamo solo l'ultima variabile
list( , , $componente) = $info;
echo"Ho voglia di $bevanda!\n";

?>

Esempio 2. Esempio di uso di list()

<table>
 <tr>
  <th>Nome dell'impiegato</th>
  <th>Stipendio</th>
 </tr>

<?php

$risultato = mysql_query("SELECT id, nome, stipendio FROM impiegati", $conn);
while (list($id, $nome, $stipendio) = mysql_fetch_row ($risultato)) {
    echo (" <tr>\n".
          "  <td><a href=\"info.php?id=$id\">$nome</a></td>\n".
          "  <td>$stipendio</td>\n".
          " </tr>\n");
}

?>

</table>

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

<?php

$info = array('caffè', 'nero', 'caffeina');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Restituisce il segente risultato (si noti l'ordine degli elementi rispetto all'ordine con cui sono stati scritti nella sintassi di list()).

array(3) {
  [2]=>
  string(8) "caffeina"
  [1]=>
  string(4) "nero"
  [0]=>
  string(5) "caffè"
}

Vedere anche each() e array() e extract().

natcasesort

(PHP 4, PHP 5)

natcasesort --  Ordina un array usando un algoritmo di "ordine naturale" non sensibile alle maiuscole/minuscole

Descrizione

void natcasesort ( array array )

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

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Ordinamento standard\n";
print_r($array1);

natcasesort($array2);
echo "\nOrdinamento naturale (con maiuscole non significative)\n";
print_r($array2);
?>

Questo codice genererà il seguente risultato:

Ordinamento standard
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Ordinamento naturale (con maiuscole non significative)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

Per maggiori informazioni vedere la pagina di Martin Pool Natural Order String Comparison .

Vedere anche sort(), natsort(), strnatcmp() e strnatcasecmp().

natsort

(PHP 4, PHP 5)

natsort --  Ordina un array usando un algoritmo di "ordine naturale"

Descrizione

void natsort ( array array )

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

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

sort($array1);
echo "Ordinamento standard\n";
print_r($array1);

natsort($array2);
echo "\nOrdinamento naturale\n";
print_r($array2);
?>

Questo codice genererà il seguente risultato:

Ordinamento standard
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Ordinamento naturale
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Per ulteriori informazioni vedere la pagina di Martin Pool Natural Order String Comparison .

Vedere anche natcasesort(), strnatcmp() e strnatcasecmp().

next

(PHP 3, PHP 4, PHP 5)

next --  Incrementa il puntatore interno dell'array

Descrizione

mixed next ( array array )

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

<?php
$trasporti = array('piedi', 'bicicletta', 'automobile', 'aereo');
$mode = current($trasporti); // $mode = 'piedi';
$mode = next($trasporti);    // $mode = 'bicicletta';
$mode = next($trasporti);    // $mode = 'automobile';
$mode = prev($trasporti);    // $mode = 'piedi';
$mode = end($trasporti);     // $mode = 'aereo';
?>

Vedere anche current(), end(), prev() e reset().

pos

(PHP 3, PHP 4, PHP 5)

pos -- Restituisce l'elemento corrente di un array

Descrizione

Questo è un alias di current().

prev

(PHP 3, PHP 4, PHP 5)

prev -- Decrementa il puntatore interno dell'array

Descrizione

mixed prev ( array array )

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

<?php
$trasporti = array('piedi', 'bicicletta', 'automobile', 'aereo');
$mode = current($trasporti); // $mode = 'piedi';
$mode = next($trasporti);    // $mode = 'bicicletta';
$mode = next($trasporti);    // $mode = 'automobile';
$mode = prev($trasporti);    // $mode = 'piedi';
$mode = end($trasporti);     // $mode = 'aereo';
?>

Vedere anche current(), end(), next() e reset().

range

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

range --  Crea un array contenente una serie di elementi

Descrizione

array range ( int min, int max [, int step] )

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

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $numero) {
    echo $numero;
}

// Il parametro step è stato introdotto nel PHP 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $numero) {
    echo $numero;
}

// L'utilizzo dei caratteri è stato aggiunto nel PHP 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $lettera) {
    echo $lettera;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $lettera) {
    echo $lettera;
}
?>

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

(PHP 3, PHP 4, PHP 5)

reset --  Reimposta il puntatore interno di un array sulla posizione iniziale

Descrizione

mixed reset ( array array )

reset() riporta il puntatore di array sul primo elemento e ne restituisce il valore.

Esempio 1. esempio di reset()

<?php

$array = array('passo uno', 'passo due', 'passo tre', 'passo quattro');
  
// di default, il puntatore è sul primo elemento  
echo current($array) . "<br />\n"; // "passo uno"

// salta due passi    
next($array);                                 
next($array);
echo current($array) . "<br />\n"; // "passo tre"
  
// reset del puntatore, ricomincia dal passo uno
reset($array);
echo current($array) . "<br />\n"; // "passo uno"
  
?>

Vedere anche current(), each(), next(), e prev().

rsort

(PHP 3, PHP 4, PHP 5)

rsort -- Ordina un array in ordine decrescente

Descrizione

bool rsort ( array array [, int sort_flags] )

Questa funzione ordina un array in ordine decrescente.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. esempio di rsort()

<?php
$frutti = array("limone", "arancia", "banana", "mela");
rsort($frutti);
reset($frutti);
while (list($chiave, $valore) = each($frutti)) {
    echo "$chiave = $valore\n";
}
?>

Questo esempio mostrerà:

0 = mela
1 = limone
2 = banana
3 = arancia

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

Vedere anche arsort(), asort(), ksort(), sort() e usort().

shuffle

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

shuffle -- Mescola un array

Descrizione

void shuffle ( array array )

Questa funzione mescola un array (rende casuale l'ordine degli elementi).

Esempio 1. esempio di shuffle()

<?php
$numeri = range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numeri);
while (list(, $numero) = each($numeri)) {
    echo "$numero ";
}
?>

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

sizeof

(PHP 3, PHP 4, PHP 5)

sizeof -- Alias di count()

Descrizione

La funzione è un alias di count().

sort

(PHP 3, PHP 4, PHP 5)

sort -- Ordina un array

Descrizione

bool sort ( array &array [, int sort_flags] )

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

<?php

$frutti = array("limone", "arancia", "banana", "mela");
sort($frutti);
reset($frutti);
while (list($chiave, $valore) = each($frutti)) {
    echo "frutti[" . $chiave . "] = " . $valore . "\n";
}

?>

Questo esempio mostrerà:

frutti[0] = arancia
frutti[1] = banana
frutti[2] = limone
frutti[3] = mela

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

uasort

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

uasort --  Ordina un array mediante una funzione definita dall'utente e mantiene le associazioni

Descrizione

bool uasort ( array array, callback cmp_function )

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

Nota: Vedere usort() e uksort() per esempio di funzioni di comparazione.

Vedere anche usort(), uksort(), sort(), asort(), arsort(), ksort() e rsort().

uksort

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

uksort --  Ordina rispetto alle chiavi di un array mediante una funzione definita dall'utente

Descrizione

bool uksort ( array array, callback cmp_function )

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

<?php
function cmp($a, $b) 
{
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}

$a = array(4 => "quattro", 3 => "tre", 20 => "venti", 10 => "dieci");

uksort($a, "cmp");

while (list($chiave, $valore) = each($a)) {
    echo "$chiave: $valore\n";
}
?>

Questo esempio mostrerà:

20: venti
10: dieci
4: quattro
3: tre

Vedere anche usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() e rsort().

usort

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

usort --  Ordina un array mediante una funzione definita dall'utente

Descrizione

bool usort ( array &array, callback cmp_function )

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.

Esempio 1. esempio di usort()

<?php
function cmp($a, $b) 
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

while (list($chiave, $valore) = each($a)) {
    echo "$chiave: $valore\n";
}
?>

Questo esempio mostrerà:

0: 1
1: 2
2: 3
3: 5
4: 6

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

<?php
function cmp($a, $b) 
{
    return strcmp($a["frutto"], $b["frutto"]);
}

$frutti[0]["frutto"] = "limoni";
$frutti[1]["frutto"] = "arance";
$frutti[2]["frutto"] = "uva";

usort($frutti, "cmp");

while (list($chiave, $valore) = each($frutti)) {
    echo "\$frutti[$chiave]: " . $valore["frutto"] . "\n";
}
?>

Quando si ordina un array multidimensionale, $a e $b contengono riferimenti al primo indice dell'array.

Questo esempio mostrerà:

$frutti[0]: arance
$frutti[1]: limoni
$frutti[2]: uva

Esempio 3. esempio di usort() usando una funzione membro di un oggetto

<?php
class OggettoTest {
    var $nome;

    function OggettoTest($nome) 
    {
        $this->nome = $nome;
    }

    /* Questa è la funzione statica di comparazione: */
    function comp_ogg($a, $b) 
    {
        $al = strtolower($a->nome);
        $bl = strtolower($b->nome);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new OggettoTest("c");
$a[] = new OggettoTest("b");
$a[] = new OggettoTest("d");

usort($a, array("OggettoTest", "comp_ogg"));

foreach ($a as $voce) {
    echo $voce->nome."\n";
}
?>

Questo esempio mostrerà:

b
c
d

Vedere anche uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort() e rsort().

VI. Funzioni Aspell [deprecated]

Introduzione

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.


Requisiti

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


Installazione

In PHP 4, these functions are only available if PHP was configured with --with-aspell=[DIR].


Vedere anche:

Vedere anche pspell.

Sommario
aspell_check_raw --  Controlla una parola senza togliere le maiuscole o cercare di eliminare gli spazi inutili [deprecated]
aspell_check -- Controlla una parola [deprecated]
aspell_new -- Carca un nuovo dizionario [deprecated]
aspell_suggest -- Suggerisce correzioni di una parola [deprecated]

aspell_check_raw

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

Descrizione

bool aspell_check_raw ( int link_dizionario, string parola )

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.

Esempio 1. aspell_check_raw()

<?php

$aspell_link = aspell_new("italiano");

if (aspell_check_raw($aspell_link, "prova")) {
    echo "La parola &grave; corretta";
} else {
    echo "Spiacente, parola non corretta";
}

?>

aspell_check

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

aspell_check -- Controlla una parola [deprecated]

Descrizione

bool aspell_check ( int link_dizionario, string parola )

aspell_check() controlla la compitazione di una parola e restituisce TRUE se è corretta, FALSE altrimenti.

Esempio 1. aspell_check()

<?php

$aspell_link = aspell_new("italiano");

if (aspell_check($aspell_link, "provva")) {
    echo "La parola &egrave; corretta";
} else {
    echo "Spiacente, parola non corretta";
}

?>

aspell_new

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

aspell_new -- Carca un nuovo dizionario [deprecated]

Descrizione

int aspell_new ( string master [, string personal] )

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.

Esempio 1. aspell_new()

<?
$aspell_link = aspell_new("italiano");
?>

aspell_suggest

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

aspell_suggest -- Suggerisce correzioni di una parola [deprecated]

Descrizione

array aspell_suggest ( int link_dizionario, string parola )

aspell_suggest() restituisce un array di possibili correzioni per la parola data.

Esempio 1. aspell_suggest()

<?php

$aspell_link = aspell_new("italiano");

if (!aspell_check($aspell_link, "prova")) {
    $suggerimenti = aspell_suggest($aspell_link, "prova");

    foreach ($suggerimenti as $suggerimento) {
        echo "Possibile parola corretta: $suggerimento<br>\n"; 
    }
}

?>

VII. Funzioni Matematiche BCMath a precisione arbitraria

Introduzione

Per la matematica a precisione arbitraria PHP offre il Binary Calculator che supporta numeri di qualsiasi dimensione e precisione, rappresentati da stringhe;


Requisiti

Dalla versione 4.0.4 del PHP, libbcmath è inclusa nella distribuzione. Non c'è bisogno di altre librerie esterne per questa estensione.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione di BC math

NomeDefaultModificabile in
bcmath.scale0PHP_INI_ALL
Per ulteriori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

bcmath.scale integer

Numero di cifre decimali per tutte le funzioni bcmath. Vedere anche bcscale().


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
bcadd -- Somma due numeri a precisione arbitraria
bccomp -- Confronta due numeri a precisione arbitraria
bcdiv -- Divide due numeri a precisione arbitraria
bcmod --  Ricava il modulo di un numero a precisione arbitraria
bcmul -- Moltiplica due numeri a precisione arbitraria
bcpow --  Effettua l'elevamento a potenza
bcpowmod --  Effettua l'elevamento a potenza, applicando quindi il modulo
bcscale --  Imposta il valore di precisione di default per tutte le funzioni matematich BCMath
bcsqrt --  Ottiene la radice quadrata di un numero a precisione arbitraria
bcsub --  Sottrae un numero a precisione arbitraria da un altro

bcadd

(PHP 3, PHP 4, PHP 5)

bcadd -- Somma due numeri a precisione arbitraria

Descrizione

string bcadd ( string primo operando, string secondo operando [, int precisione] )

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.

Esempi

Esempio 1. Esempio di bcadd()

<?php

$a = 1.234;
$b = 5;

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

Vedere anche:

bcsub().

bccomp

(PHP 3, PHP 4, PHP 5)

bccomp -- Confronta due numeri a precisione arbitraria

Descrizione

int bccomp ( string primo_operando, string secondo_operando [, int precisione] )

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.

Esempi

Esempio 1. esempio di bccomp()

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

bcdiv

(PHP 3, PHP 4, PHP 5)

bcdiv -- Divide due numeri a precisione arbitraria

Descrizione

string bcdiv ( string primo operando, string secondo operando [, int precisione] )

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.

Esempi

Esempio 1. esempio di bcdiv()

<?php

echo bcdiv(105, 6.55957, 3);  // 16.007

?>

Vedere anche:

bcmul().

bcmod

(PHP 3, PHP 4, PHP 5)

bcmod --  Ricava il modulo di un numero a precisione arbitraria

Descrizione

string bcmod ( string operando, string modulo )

Ricava il modulo di operando usando modulo.

Esempi

Esempio 1. esempio di bcmod()

<?php
echo bcmod(4, 2); // 0
echo bcmod(2, 4); // 2
?>

Vedere anche:

bcdiv().

bcmul

(PHP 3, PHP 4, PHP 5)

bcmul -- Moltiplica due numeri a precisione arbitraria

Descrizione

string bcmul ( string primo operando, string secondo operando [, int precisione] )

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.

Esempi

Esempio 1. esempio di bcmul()

<?php
echo bcmul(1.34747474747, 35, 3); // 47.162
echo bcmul(2, 4); // 8
?>

Vedere anche:

bcdiv().

bcpow

(PHP 3, PHP 4, PHP 5)

bcpow --  Effettua l'elevamento a potenza

Descrizione

string bcpow ( string x, string y [, int precisione] )

Eleva x alla potenza y. Il parametro opzionale precisione può essere usato per impostare il numero di cifre dopo il punto decimale nel risultato.

Esempi

Esempio 1. bcpow() example

<?php

echo bcpow(4.2, 3, 2); // 74.08

?>

Vedere anche:

bcpowmod() e bcsqrt().

bcpowmod

(PHP 5)

bcpowmod --  Effettua l'elevamento a potenza, applicando quindi il modulo

Descrizione

string bcpowmod ( string x, string y, string modulo [, int precisione] )

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.

Esempi

Le seguenti istruzioni sono funzionalmente identiche. La versione bcpowmod(), comunque, esegue in meno tempo e può accettare parametri più grandi.

<?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a e $b sono uguali. 

?>

Vedere anche:

bcpow() e bcmod().

bcscale

(PHP 3, PHP 4, PHP 5)

bcscale --  Imposta il valore di precisione di default per tutte le funzioni matematich BCMath

Descrizione

bool bcscale ( int precisione )

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

Esempi

Esempio 1. esempio di bcscale()

<?php

// precisione di default : 3
bcscale(3);
echo bcdiv(105, 6.55957); // 16.007

// la stessa cosa, senza utilizzare bcscale()
echo bcdiv(105, 6.55957, 3); // 16.007

?>

bcsqrt

(PHP 3, PHP 4, PHP 5)

bcsqrt --  Ottiene la radice quadrata di un numero a precisione arbitraria

Descrizione

string bcsqrt ( string operando [, int precisione] )

Restituisce la radice quadrata di operando. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.

Esempi

Esempio 1. esempio di bcsqrt()

<?php

echo bcsqrt(2, 3); // 1.414

?>

Vedere anche:

bcpow().

bcsub

(PHP 3, PHP 4, PHP 5)

bcsub --  Sottrae un numero a precisione arbitraria da un altro

Descrizione

string bcsub ( string primo operando, string secondo operando [, int precisione] )

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.

Esempi

Esempio 1. esempio di bcsub()

<?php

$a = 1.234;
$b = 5;
 
echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

Vedere anche:

bcadd().

VIII. PHP bytecode Compiler

Introduzione

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 first of these goals is achieved using the bcompiler_write_header(), bcompiler_write_file() and bcompiler_write_footer() functions. The bytecode files can be written as either uncompressed or plain. To use the generated bytecode, you can simply include it with include or require statements.

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.


Installazione

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.


Contact Information

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.

Sommario
bcompiler_load_exe -- Reads and creates classes from a bcompiler exe file
bcompiler_load -- Reads and creates classes from a bz compressed file
bcompiler_parse_class -- Reads the bytecodes of a class and calls back to a user function
bcompiler_read -- Reads and creates classes from a filehandle
bcompiler_write_class -- Writes an defined class as bytecodes
bcompiler_write_constant -- Writes a defined constant as bytecodes
bcompiler_write_exe_footer -- Writes the start pos, and sig to the end of a exe type file
bcompiler_write_file -- Writes a php source file as bytecodes
bcompiler_write_footer -- Writes the single character \x00 to indicate End of compiled data
bcompiler_write_function -- Writes an defined function as bytecodes
bcompiler_write_functions_from_file -- Writes all functions defined in a file as bytecodes
bcompiler_write_header -- Writes the bcompiler header

bcompiler_load_exe

(PECL)

bcompiler_load_exe -- Reads and creates classes from a bcompiler exe file

Description

bool bcompiler_load_exe ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?>

bcompiler_load

(PECL)

bcompiler_load -- Reads and creates classes from a bz compressed file

Description

bool bcompiler_load ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_load() example

<?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?>

bcompiler_parse_class

(PECL)

bcompiler_parse_class -- Reads the bytecodes of a class and calls back to a user function

Description

bool bcompiler_parse_class ( string class, string callback )

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.

Esempio 1. bcompiler_parse_class() example

<?php

function readByteCodes($data) {
  print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

bcompiler_read

(PECL)

bcompiler_read -- Reads and creates classes from a filehandle

Description

bool bcompiler_read ( resource filehandle )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_read() example

<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

bcompiler_write_class

(PECL)

bcompiler_write_class -- Writes an defined class as bytecodes

Description

bool bcompiler_write_class ( resource filehandle, string className [, string extends] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

See also bcompiler_write_header(), and bcompiler_write_footer().

bcompiler_write_constant

(PECL)

bcompiler_write_constant -- Writes a defined constant as bytecodes

Description

bool bcompiler_write_constant ( resource filehandle, string constantName )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_write_constant() example

<?php
define("MODULE_MAX", 30);

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

See also bcompiler_write_header(), and bcompiler_write_footer().

bcompiler_write_exe_footer

(PECL)

bcompiler_write_exe_footer -- Writes the start pos, and sig to the end of a exe type file

Description

bool bcompiler_write_exe_footer ( resource filehandle, int startpos )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

The startpos is the file position at which the Bytecodes start, and can be obtained using ftell($fh).

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

<?php
/* creating the output file (example.exe) */
$fh = fopen("example.exe", "w");
/* 1) writing a stub (phpe.exe) */
$size = filesize("phpe.exe");
$fr = fopen("phpe.exe", "r");
fwrite($fh, fread($fr, $size), $size);
$startpos = ftell($fh);
/* 2) writing bytecodes */
bcompiler_write_header($fh);
bcompiler_write_class($fh, "myclass");
bcompiler_write_function($fh, "main");
bcompiler_write_footer($fh);
/* 3) writing EXE footer */
bcompiler_write_exe_footer($fh, $startpos);
/* closing the output file */
fclose($fh);
?>

See also bcompiler_write_header(), bcompiler_write_class(), and bcompiler_write_footer().

bcompiler_write_file

(PECL)

bcompiler_write_file -- Writes a php source file as bytecodes

Description

bool bcompiler_write_file ( resource filehandle, string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

See also bcompiler_write_header(), and bcompiler_write_footer().

bcompiler_write_footer

(PECL)

bcompiler_write_footer -- Writes the single character \x00 to indicate End of compiled data

Description

bool bcompiler_write_footer ( resource filehandle )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_write_footer() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_class($fh,"DB_common");
bcompiler_write_footer($fh);
fclose($fh);

?>

See also bcompiler_write_header(), and bcompiler_write_header().

bcompiler_write_function

(PECL)

bcompiler_write_function -- Writes an defined function as bytecodes

Description

bool bcompiler_write_function ( resource filehandle, string functionName )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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).

Esempio 1. bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

See also bcompiler_write_header(), and bcompiler_write_footer().

bcompiler_write_functions_from_file

(PECL)

bcompiler_write_functions_from_file -- Writes all functions defined in a file as bytecodes

Description

bool bcompiler_write_functions_from_file ( resource filehandle, string fileName )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

See also bcompiler_write_header(), and bcompiler_write_footer().

bcompiler_write_header

(PECL)

bcompiler_write_header -- Writes the bcompiler header

Description

bool bcompiler_write_header ( resource filehandle [, string write_ver] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. bcompiler_write_header() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

See also bcompiler_write_file(), bcompiler_write_class(), bcompiler_write_function(), and bcompiler_write_footer().

IX. Funzioni di compressione Bzip2

Introduzione

Le funzioni bzip2 sono utilizzate per leggere e scrivere in modo trasparente i file compressi con bzip2 (.bz2).


Requisiti

Questo modulo tuilizza le funzioni della libreria bzip2 di Julian Seward. Questo modulo richiede che la versione di bzip2/libbzip2 sia >= 1.0.x.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione definisce un tipo di risorsa: un puntatore a file che identifica il file bz2 su cui lavorare.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

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

<?php

$nomefile = "/tmp/filediprova.bz2";
$str = "Questa è una stringa di prova.\n";

// apre il file in lettura
$bz = bzopen($nomefile, "w");

// scrive la stringa sul file
bzwrite($bz, $str);

// chiude il file
bzclose($bz);

// apre il file in lettura
$bz = bzopen($nomefile, "r");

// legge 10 caratteri
echo bzread($bz, 10);

// stampa fino alla fine del file (o fino ai prossimi 1024 caratteri) e chiude il file.
echo bzread($bz);

bzclose($bz);

?>
Sommario
bzclose -- Chiude un puntatore a un file bzip2
bzcompress -- Comprime una stringa nel formato bzip2
bzdecompress -- Decomprime dati codificati con bzip2
bzerrno -- Restituisce il codice d'errore bzip2
bzerror -- Restituisce il codice d'errore bzip2 e la stringa corrispondente in un array
bzerrstr -- restituisce la stringa di errore bzip2
bzflush -- Forza la scrittura di tutti i dati nel buffer
bzopen -- Apre un file compresso bzip2
bzread -- Esegue la lettura binaria di un file bzip2
bzwrite -- Esegue la scrittura binaria di un file bzip2

bzclose

(PHP 4 >= 4.3.3, PHP 5)

bzclose -- Chiude un puntatore a un file bzip2

Descrizione

int bzclose ( resource bz )

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

(PHP 4 >= 4.3.3, PHP 5)

bzcompress -- Comprime una stringa nel formato bzip2

Descrizione

string bzcompress ( string sorgente [, int dimblocco [, int workfactor]] )

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.

Esempio 1. Esempio di bzcompress()

<?php
$str = "dati di prova";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

See also bzdecompress().

bzdecompress

(PHP 4 >= 4.3.3, PHP 5)

bzdecompress -- Decomprime dati codificati con bzip2

Descrizione

string bzdecompress ( string sorgente [, int small] )

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

Esempio 1. bzdecompress()

<?php
$stringa_iniziale = "Sto facendo il mio lavoro?";
$bzstr = bzcompress($start_str);

echo "Stirnga Compressa: ";
echo $bzstr;
echo "\n<br />\n";

$stringa = bzdecompress($bzstr);
echo "Stringa Decompressa: ";
echo $str;
echo "\n<br />\n";
?>

See also bzcompress().

bzerrno

(PHP 4 >= 4.3.3, PHP 5)

bzerrno -- Restituisce il codice d'errore bzip2

Descrizione

int bzerrno ( resource bz )

Restituisce il codice di un qualsiasi errore bzip2 restituito dal puntatore al file bz.

Vedere anche bzerror() e bzerrstr().

bzerror

(PHP 4 >= 4.3.3, PHP 5)

bzerror -- Restituisce il codice d'errore bzip2 e la stringa corrispondente in un array

Descrizione

array bzerror ( resource bz )

Restituisce il codice e la stringa di errore, sotto forma di array associativo, di un errore bzip2 restituito dal puntatore bz.

Esempio 1. Esempio di bzerror()

<?php
$errore = bzerror($bz);

echo $errore["errno"];
echo $errore["errstr"];
?>

Vedere anche bzerrno() e bzerrstr().

bzerrstr

(PHP 4 >= 4.3.3, PHP 5)

bzerrstr -- restituisce la stringa di errore bzip2

Descrizione

string bzerrstr ( resource bz )

Resituisce la stringa di errore bzip2 restituito dal puntatore bz.

Vedere anche bzerrno() e bzerror().

bzflush

(PHP 4 >= 4.3.3, PHP 5)

bzflush -- Forza la scrittura di tutti i dati nel buffer

Descrizione

int bzflush ( resource 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.

Vedere anche bzread() e bzwrite().

bzopen

(PHP 4 >= 4.3.3, PHP 5)

bzopen -- Apre un file compresso bzip2

Descrizione

resource bzopen ( string nomefile, string modo )

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.

Esempio 1. Esempio dibzopen()

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("non sono riuscito ad aprire in lettura $file");

bzclose($bz);

?>

Vedere anche bzclose().

bzread

(PHP 4 >= 4.3.3, PHP 5)

bzread -- Esegue la lettura binaria di un file bzip2

Descrizione

string bzread ( resource bz [, int lunghezza] )

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.

Esempio 1. Esempio di bzread()

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Non ho potuto aprire $file");

$File_decompresso = '';
while (!feof($bz)) {
   $file_decompresso .= bzread($bz, 4096);
}
bzclose($bz);

echo "Il contenuto di $file è: <br />\n";
echo $file_decompresso;

?>

Vedere anche bzwrite(), feof() e bzopen().

bzwrite

(PHP 4 >= 4.3.3, PHP 5)

bzwrite -- Esegue la scrittura binaria di un file bzip2

Descrizione

int bzwrite ( resource bz, string dati [, int lunghezza] )

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.

Esempio 1. Esempio di bzwrite()

<?php
$str = "dati non compressi";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

Vedere anche bzread() e bzopen().

X. Funzioni Calendar

Introduzione

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.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

CAL_GREGORIAN (integer)

CAL_JULIAN (integer)

CAL_JEWISH (integer)

CAL_FRENCH (integer)

CAL_NUM_CALS (integer)

CAL_DOW_DAYNO (integer)

CAL_DOW_SHORT (integer)

CAL_DOW_LONG (integer)

CAL_MONTH_GREGORIAN_SHORT (integer)

CAL_MONTH_GREGORIAN_LONG (integer)

CAL_MONTH_JULIAN_SHORT (integer)

CAL_MONTH_JULIAN_LONG (integer)

CAL_MONTH_JEWISH (integer)

CAL_MONTH_FRENCH (integer)

Le seguenti costanti sono disponibili dal PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)

CAL_EASTER_ROMAN (integer)

CAL_EASTER_ALWAYS_GREGORIAN (integer)

CAL_EASTER_ALWAYS_JULIAN (integer)

Le seguenti costanti sono disponibili dal PHP 5.0.0 :

CAL_JEWISH_ADD_ALAFIM_GERESH (integer)

CAL_JEWISH_ADD_ALAFIM (integer)

CAL_JEWISH_ADD_GERESHAYIM (integer)

Sommario
cal_days_in_month -- Restituisce il numero di giorni di un mese per un dato anno e calendario
cal_from_jd -- Converte dal Giorno Giuliano ad un calendario
cal_info -- Restituisce informazioni su un particolare calendario
cal_to_jd -- Converte da un calendario a un Giorno Giuliano
easter_date --  Restituisce un timestamp Unix della mezzanotte del giorno di Pasqua di un dato anno
easter_days --  Restituisce il numero di giorni tra il 21 Marzo e Pasqua, dato un anno
FrenchToJD --  Converte una data del Calendario Repubblicano Francese in un Giorno Giuliano
GregorianToJD --  Converte una data Gregoriana in un Giorno Giuliano
JDDayOfWeek -- Restituisce il giorno della settimana
JDMonthName -- Restituisce il nome di un mese
JDToFrench --  Converte un Giorno Giuliano in una data del Calendario Repubblicano Francese
JDToGregorian -- Converte il Giorno Giuliano in data Gregoriana
jdtojewish --  Converte un Giorno Giuliano nel Calendario Giudeo
JDToJulian --  Converte un Giorno Giuliano in una data Giuliana
jdtounix -- Converte un Giorno Giuliano in un timestamp Unix
JewishToJD --  Converte una data del Calendario Giudeo in Giorno Giuliano
JulianToJD --  Converte una data Giuliana in un Giorno Giuliano
unixtojd -- Converte un timestamp Unix in un Giorno Giuliano

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_month -- Restituisce il numero di giorni di un mese per un dato anno e calendario

Descrizione

int cal_days_in_month ( int calendario, int mese, int anno )

Questa funzione restituisce il numero di giorni che compongono il mese dell'anno nel calendar specificato.

Esempio 1. esempio di cal_days_in_month()

<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "C'erano $num giorni nell'agosto del 2003";
?>

Vedere anche jdtounix().

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jd -- Converte dal Giorno Giuliano ad un calendario

Descrizione

array cal_from_jd ( int giornogiuliano, int calendario )

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

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

Questo mostrerà:

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

Vedere anche cal_to_jd().

cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info -- Restituisce informazioni su un particolare calendario

Descrizione

array cal_info ( [int calendario] )

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

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd -- Converte da un calendario a un Giorno Giuliano

Descrizione

int cal_to_jd ( int calendario, int mese, int giorno, int anno )

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

easter_date

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_date --  Restituisce un timestamp Unix della mezzanotte del giorno di Pasqua di un dato anno

Descrizione

int easter_date ( [int anno] )

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

Esempio 1. esempio di easter_date()

<?php

echo date("d M Y", easter_date(1999));        // 04 Apr 1999
echo date("d M Y", easter_date(2000));        // 23 Apr 2000
echo date("d M Y", easter_date(2001));        // 15 Apr 2001

?>

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.

easter_days

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

easter_days --  Restituisce il numero di giorni tra il 21 Marzo e Pasqua, dato un anno

Descrizione

int easter_days ( [int anno [, int metodo]] )

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

Esempio 1. esempio di easter_days()

<?php

echo easter_days(1999);        // 14, quindi il 4 Aprile
echo easter_days(1492);        // 32, quindi il 22 Aprile
echo easter_days(1913);        //  2, quindi il 23 Marzo

?>

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

FrenchToJD

(PHP 3, PHP 4, PHP 5)

FrenchToJD --  Converte una data del Calendario Repubblicano Francese in un Giorno Giuliano

Description

int frenchtojd ( int mese, int giorno, int anno )

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

GregorianToJD

(PHP 3, PHP 4, PHP 5)

GregorianToJD --  Converte una data Gregoriana in un Giorno Giuliano

Descrizione

int gregoriantojd ( int mese, int giorno, int anno )

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.

Esempio 1. Calendar functions

<?php
$jd = GregorianToJD(10, 11, 1970);
echo "$jd\n";
$gregorian = JDToGregorian($jd);
echo "$gregorian\n";
?>

JDDayOfWeek

(PHP 3, PHP 4, PHP 5)

JDDayOfWeek -- Restituisce il giorno della settimana

Descrizione

mixed jddayofweek ( int giornogiuliano, int modo )

Restituisce il giorno della settimana. Può restituire una stringa o un intero a seconda del modo.

Tabella 1. Modi

ModoSignificato
0 Restituisce il numero del giorno come intero (0=domenica, 1=lunedì, etc)
1 Restituisce una stringa contenente il giorno della settimana (in inglese-gregoriano)
2 Restituisce una stringa contenente il giorno della settimana abbreviato (in inglese-gregoriano)

JDMonthName

(PHP 3, PHP 4, PHP 5)

JDMonthName -- Restituisce il nome di un mese

Descrizione

string jdmonthname ( int giornogiuliano, int 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

ModoSignificatoValori
0Gregoriano abbreviatoJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1GregorianoJanuary, February, March, April, May, June, July, August, September, October, November, December
2Giuliano abbreviatoJan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3GiulianoJanuary, February, March, April, May, June, July, August, September, October, November, December
4GiudeoTishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5Repubblicano FranceseVendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

JDToFrench

(PHP 3, PHP 4, PHP 5)

JDToFrench --  Converte un Giorno Giuliano in una data del Calendario Repubblicano Francese

Descrizione

string jdtofrench ( int giornogiuliano )

Converte un Giorno Giuliano in una data del calendario Repubblicano Francese.

JDToGregorian

(PHP 3, PHP 4, PHP 5)

JDToGregorian -- Converte il Giorno Giuliano in data Gregoriana

Descrizione

string jdtogregorian ( int giornogiuliano )

Converte il Giorno Giuliano in una stringa contenente la data Gregoriana nel formato "mese/giorno/anno".

jdtojewish

(PHP 3, PHP 4, PHP 5)

jdtojewish --  Converte un Giorno Giuliano nel Calendario Giudeo

Descrizione

string jdtojewish ( int giornogiuliano [, bool ebraico [, int fl]] )

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.

Esempio 1. esempio di jdtojewish()

<?php
echo jdtojewish(gregoriantojd(10, 8, 2002), true,
       CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH); 
?>

JDToJulian

(PHP 3, PHP 4, PHP 5)

JDToJulian --  Converte un Giorno Giuliano in una data Giuliana

Descrizione

string jdtojulian ( int giornogiuliano )

Converte un Giorno Giuliano in una stringa contenente la data del calendario Giuliano nel formato "mese/giorno/anno".

jdtounix

(PHP 4, PHP 5)

jdtounix -- Converte un Giorno Giuliano in un timestamp Unix

Descrizione

int jdtounix ( int giornogiuliano )

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

JewishToJD

(PHP 3, PHP 4, PHP 5)

JewishToJD --  Converte una data del Calendario Giudeo in Giorno Giuliano

Descrizione

int jewishtojd ( int mese, int giorno, int anno )

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.

JulianToJD

(PHP 3, PHP 4, PHP 5)

JulianToJD --  Converte una data Giuliana in un Giorno Giuliano

Descrizione

int juliantojd ( int mese, int giorno, int anno )

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.

unixtojd

(PHP 4, PHP 5)

unixtojd -- Converte un timestamp Unix in un Giorno Giuliano

Descrizione

int unixtojd ( [int timestamp] )

Restituisce il Giorno Giuliano di un timestamp Unix (secondi dal 1/1/1970), o del giorno corrente se timestamp non è specificato.

Vedere anche jdtounix().

XI. Funzioni API CCVS [deprecate]

Introduzione

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.


Installazione

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


Vedere anche:

RedHat non supporta più CCVS; comunque una documentazione leggermente datata è ancora disponibile presso http://www.redhat.com/docs/manuals/ccvs/.

Sommario
ccvs_add -- Aggiunge dati ad una transazione
ccvs_auth --  Esegue un test di autorizzazione al credito su una transazione
ccvs_command --  Esegue un comando caratteristico di un particolare protocollo, quindi non disponibile nelle API di CCVS
ccvs_count --  Conta quante transazioni di un dato tipo sono archiviate nel sistema
ccvs_delete -- Cancella una transazione
ccvs_done -- Ferma il processo CCVS e ripulisce gli oggetti creati
ccvs_init -- Inizializza CCVS per il successivo utilizzo
ccvs_lookup --  Cerca una voce di un determinato tipo nel database #
ccvs_new -- Crea una nuova transazione, vuota
ccvs_report -- Restituisce lo stato del processo di comunicazione
ccvs_return --  Trasferisce fondi dal merchant al titolare della carta di credito
ccvs_reverse --  Esegue uno storno su un'autorizzazione già processata
ccvs_sale --  Trasferisce fondi dal titolare della carta di credito al merchant
ccvs_status -- Controlla lo stato di una fattura
ccvs_textvalue -- Restuisce il valore testuale reso dalla precedente chiamata di funzione
ccvs_void --  Esegue uno storno su una transazione già completata

ccvs_add

(4.0.2 - 4.2.3 only)

ccvs_add -- Aggiunge dati ad una transazione

Descrizione

string ccvs_add ( string sessione, string fattura, string tipo_arg, string valore_arg )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_auth

(4.0.2 - 4.2.3 only)

ccvs_auth --  Esegue un test di autorizzazione al credito su una transazione

Descrizione

string ccvs_auth ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_command

(4.0.2 - 4.2.3 only)

ccvs_command --  Esegue un comando caratteristico di un particolare protocollo, quindi non disponibile nelle API di CCVS

Descrizione

string ccvs_command ( string sessione, string tipo, string val_arg )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_count

(4.0.2 - 4.2.3 only)

ccvs_count --  Conta quante transazioni di un dato tipo sono archiviate nel sistema

Descrizione

int ccvs_count ( string sessione, string tipo )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_delete

(4.0.2 - 4.2.3 only)

ccvs_delete -- Cancella una transazione

Descrizione

string ccvs_delete ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_done

(4.0.2 - 4.2.3 only)

ccvs_done -- Ferma il processo CCVS e ripulisce gli oggetti creati

Descrizione

string ccvs_done ( string sessione )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_init

(4.0.2 - 4.2.3 only)

ccvs_init -- Inizializza CCVS per il successivo utilizzo

Descrizione

string ccvs_init ( string nome )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_lookup

(4.0.2 - 4.2.3 only)

ccvs_lookup --  Cerca una voce di un determinato tipo nel database #

Descrizione

string ccvs_lookup ( string sessione, string fattura, int num )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_new

(4.0.2 - 4.2.3 only)

ccvs_new -- Crea una nuova transazione, vuota

Descrizione

string ccvs_new ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_report

(4.0.2 - 4.2.3 only)

ccvs_report -- Restituisce lo stato del processo di comunicazione

Descrizione

string ccvs_report ( string sessione, string tipo )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_return

(4.0.2 - 4.2.3 only)

ccvs_return --  Trasferisce fondi dal merchant al titolare della carta di credito

Descrizione

string ccvs_return ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_reverse

(4.0.2 - 4.2.3 only)

ccvs_reverse --  Esegue uno storno su un'autorizzazione già processata

Descrizione

string ccvs_reverse ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_sale

(4.0.2 - 4.2.3 only)

ccvs_sale --  Trasferisce fondi dal titolare della carta di credito al merchant

Descrizione

string ccvs_sale ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_status

(4.0.2 - 4.2.3 only)

ccvs_status -- Controlla lo stato di una fattura

Descrizione

string ccvs_status ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_textvalue

(4.0.2 - 4.2.3 only)

ccvs_textvalue -- Restuisce il valore testuale reso dalla precedente chiamata di funzione

Descrizione

string ccvs_textvalue ( string sessione )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ccvs_void

(4.0.2 - 4.2.3 only)

ccvs_void --  Esegue uno storno su una transazione già completata

Descrizione

string ccvs_void ( string sessione, string fattura )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

XII. Funzioni per Classi/Oggetti

Introduzione

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


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

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

<?php

// classe base con proprietà e metodi
class Ortaggio {

    var $commestibile;
    var $colore;

    function Ortaggio($commestibile, $colore="verde")
    {
        $this->commestibile = $commestibile;
        $this->colore = $colore;
    }

    function e_commestibile()
    {
        return $this->commestibile;
    }

    function che_colore_ha()
    {
        return $this->colore;
    }
    
} // Fine della classe ortaggio

// Estensione della classe base
class Spinaci extends Ortaggio {

    var $cotto = false;

    function Spinaci() 
    {
        $this->Ortaggio( true, "verde" );
    }

    function cuocilo() 
    {
        $this->cotto = true;
    }

    function e_cotto() 
    {
        return $this->cotto;
    }
    
} // Fine della classe spinaci

?>

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

<pre>
<?php

include "classi.inc";

// Funzioni di utilità

function visualizza_var($oggetto) 
{
    $matrice = get_object_vars($oggetto);
    while (list($prop, $val) = each($matrice))
        echo "\t$prop = $val\n";
}

function visualizza_metodi($oggetto) 
{
    $matrice = get_class_methods(get_class($oggetto));
    foreach ($matrice as $metodo)
        echo "\tfunzione $metodo()\n";
}

function padri_classe($oggetto, $classe) 
{
    if (is_subclass_of($$oggetto, $classe)) {
        echo "Oggetto $oggetto appartiene alla classe ".get_class($$oggetto);
        echo " derivata da $classe\n";
    } else {
        echo "Oggetto $oggetto non deriva da una sottoclasse di $classe\n";
    }
}

// Istanzia 2 oggetti

$pomodoro = new Ortaggio(true,"rosso");
$frondoso = new Spinaci();

// Visualizza le informazioni sugli oggetti
echo "pomodoro: CLASSE " . get_class($pomodoro) . "\n";
echo "frondoso: CLASSE " . get_class($frondoso);
echo ", PADRE " . get_parent_class($frondoso) . "\n";

// visualizza le proprietà di pomodoro
echo "\npomodoro: Proprietà\n";
visualizza_var($pomodoro);

// e i metodi di frondoso
echo "\nfrondoso: Metodi\n";
visualizza_metodi($frondoso);

echo "\nPadri:\n";
padri_classe("frondoso", "Spinaci");
padri_classe("frondoso", "Ortaggio");
?>
</pre>

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

[...]
Padri:
Oggetto frondoso non deriva da una sottoclasse di Spinaci
Oggetto frondoso appartiene alla classe spinaci derivata da Ortaggio

Sommario
call_user_method_array --  Richiama il metodo dato con un array di parametri [deprecated]
call_user_method --  Chiama un metodo dell'oggetto indicato [deprecated]
class_exists -- Verifica se una classe è stata definita
get_class_methods -- Restituisce un array con i nomi dei metodi della classe
get_class_vars --  Restituisce un array con le proprietà di default della classe
get_class -- Restituisce il nome della classe di un oggetto
get_declared_classes -- Restituisce un array con il nome delle classi definite
get_declared_interfaces --  Returns an array of all declared interfaces
get_object_vars -- Restituisce un array associativo con le proprietà dell'oggetto
get_parent_class -- Restituisce il nome della classe genitrice di un oggetto o di una classe
interface_exists -- Checks if the interface has been defined
is_a --  Restituisce TRUE se l'oggetto appartiene a questa classe o se ha questa classe tra i suoi genitori
is_subclass_of --  Restituisce TRUE se l'oggetto ha questa classe come uno dei suoi genitori
method_exists -- Verifica se il metodo esiste nella classe
property_exists --  Checks if the object or class has a property

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array --  Richiama il metodo dato con un array di parametri [deprecated]

Descrizione

mixed call_user_method_array ( string nome_metodo, object &obj, array paramarr )

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

call_user_method

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

call_user_method --  Chiama un metodo dell'oggetto indicato [deprecated]

Descrizione

mixed call_user_method ( string nome_metodo, object &obj [, mixed parametro [, mixed ...]] )

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

class_exists

(PHP 4, PHP 5)

class_exists -- Verifica se una classe è stata definita

Descrizione

bool class_exists ( string nome_classe [, bool autoload] )

Questa funzione restituisce TRUE se la classe indicata dal parametro nome_classe è stata definita, altrimenti restituisce FALSE .

Esempio 1. Esempio di uso di class_exists()

<?php
// Verifica se la classe esiste prima di richiamarla
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
 
?>

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

<?php
function __autoload($class) 
{
    include($class . '.php');
    // Check to see it the include defined the class
    if ( !class_exists($class, false) ) {
        trigger_error("Unable to load class $class", E_USER_ERROR);
       }

}
 
if( class_exists('MyClass') ) {
    $myclass = new MyClass();
}
 
?>

Nota: Il parametro autoload è stato aggiunto in PHP 5

Vedere anche interface_exists() e get_declared_classes().

get_class_methods

(PHP 4, PHP 5)

get_class_methods -- Restituisce un array con i nomi dei metodi della classe

Descrizione

array get_class_methods ( string nome_classe )

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:

<?php
$metodi_della_classe = get_class_methods($mia_classe); // vedere di seguito l'esempio completo
?>

Esempio 1. Esempio di get_class_methods()

<?php

class miaclasse {
    // costruttore
    function miaclasse()
    {
        return(true);
    }
    
    // metodo 1
    function funzione1() 
    {
        return(true);
    }

    // metodo 2
    function funzione2() 
    {
        return(true);
    }
}

$mio_oggetto = new miaclasse();

$metodi = get_class_methods(get_class($mio_oggetto));

foreach ($metodi as $nome_metodo) {
    echo "$nome_metodo\n";
}

?>

Il precedente esempio visualizzerà:

miaclasse
funzione1
funzione2

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

get_class_vars

(PHP 4, PHP 5)

get_class_vars --  Restituisce un array con le proprietà di default della classe

Descrizione

array get_class_vars ( string nome_classe )

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

<?php

class miaclasse {

    var $var1; // questa variabile non ha un valore di default...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4; // PHP 5
    // costruttore
    function miaclasse() {
        // Modifico qualche proprietà
        $this->var1 = "foo"; 
        $this->var2 = "bar";
        return(true);
    }

}

$mia_classe = new miaclasse();

$variabili = get_class_vars(get_class($mia_classe));

foreach ($variabili as $nome => $valore) {
    echo "$nome : $valore\n";
}

?>

Il precedente esempio visualizzerà:

// Versioni di PHP antecedenti alla 4.2.0
var2 : xyz
var3 : 100

// Dalla versione 4.2.0
var1:
var2 : xyz
var3 : 100

Vedere anche get_class_methods() e get_object_vars()

get_class

(PHP 4, PHP 5)

get_class -- Restituisce il nome della classe di un oggetto

Descrizione

string get_class ( object oggetto )

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

<?php

class foo 
    {
    function foo() {
    // qualche istruzione
    }

    function name() 
    {
        echo "Nome della classe: " , get_class($this) , "\n";
    }
}

// creo un oggetto
$bar = new foo();

// chiamata dall'esterno
echo "Il suo nome è: " , get_class($bar) , "\n";

// chiamata dall'interno
$bar->name();

?>

Il precedente esempio visualizzerà:

Il suo nome è: foo
Nome della classe:  foo

Vedere anche get_parent_class(), gettype() e is_subclass_of()

get_declared_classes

(PHP 4, PHP 5)

get_declared_classes -- Restituisce un array con il nome delle classi definite

Descrizione

array get_declared_classes ( void )

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.

Esempio 1. Esempio di uso di get_declared_classes()

<?php
print_r(get_declared_classes());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

Vedere anche class_exists() e get_declared_interfaces().

get_declared_interfaces

(PHP 5)

get_declared_interfaces --  Returns an array of all declared interfaces

Description

array get_declared_interfaces ( void )

This function returns an array of the names of the declared interfaces in the current script.

Esempio 1. get_declared_interfaces() example

<?php
print_r(get_declared_interfaces());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

See also get_declared_classes().

get_object_vars

(PHP 4, PHP 5)

get_object_vars -- Restituisce un array associativo con le proprietà dell'oggetto

Descrizione

array get_object_vars ( object oggetto )

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

<?php
class Point2D {
    var $x, $y;
    var $etichetta;

    function Point2D($x, $y) 
    {
        $this->x = $x;
        $this->y = $y;
    }

    function setetichetta($etichetta) 
    {
        $this->etichetta = $etichetta;
    }

    function getPoint() 
    {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "etichetta" => $this->etichetta);
    }
}

// "$etichetta" è dichiarata ma non definita
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

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

?>

Il precedente esempio visualizzerà:

Array 
( 
     [x] => 1.233 
     [y] => 3.445 
     [label] =>
) 
    
Array 
( 
     [x] => 1.233 
     [y] => 3.445 
     [label] => point #1 
)

Vedere anche get_class_methods() e get_class_vars().

get_parent_class

(PHP 4, PHP 5)

get_parent_class -- Restituisce il nome della classe genitrice di un oggetto o di una classe

Descrizione

string get_parent_class ( mixed oggetto )

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

<?php

class dad {
    function dad() 
    {
    // Qualche istruzione
    }
}

class child extends dad {
    function child() 
    {
        echo "Io sono figlio di " , get_parent_class($this) , "\n";
    }
}

class child2 extends dad {
    function child2() 
    {
        echo "Pure io sono figlio di " , get_parent_class('child2') , "\n";
    }
}

$foo = new child();
$bar = new child2();

?>

Il precedente esempio visualizzerà:

Io sono figlio di dad
Pure io sono figlio di dad

Vedere anche get_class(), is_subclass_of()

interface_exists

(PHP 5 >= 5.0.2)

interface_exists -- Checks if the interface has been defined

Description

bool interface_exists ( string interface_name [, bool autoload] )

This function returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

Esempio 1. interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

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

is_a

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

Descrizione

bool is_a ( object object, string class_name )

Questa funzione restituisce TRUE appartiene a questa classe oppure ha questa classe tra i suoi genitori, FALSE in caso diverso.

Esempio 1. Esempio di uso di is_a()

<?php
// Definisce una classe 
class WidgetFactory
{
  var $oink = 'moo';
}
 
// crea un nuovo oggetto
$WF = new WidgetFactory();
 
if (is_a($WF, 'WidgetFactory')) {
  echo "yes, \$WF is still a WidgetFactory\n";
}
?>

In PHP 5 la funzione is_a() è sconsigliata in favore di instanceof. L'esempio precedente, in PHP 5, può essere riscritto come:

Esempio 2. Utilizzo dell'operatore instanceof in PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Yes, $WF is a WidgetFactory';
}
?>

Vedere anche get_class(), get_parent_class() e is_subclass_of().

is_subclass_of

(PHP 4, PHP 5)

is_subclass_of --  Restituisce TRUE se l'oggetto ha questa classe come uno dei suoi genitori

Descrizione

bool is_subclass_of ( mixed oggetto, string nome_classe )

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

<?php
// definisce una classe
class WidgetFactory
{
  var $oink = 'moo';
}
 
// definisce una classe figlio
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}
 
// crea un nuovo oggetto
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();
 
if (is_subclass_of($WFC, 'WidgetFactory')) {
  echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WFC is not a subclass of WidgetFactory\n";
}
 
if (is_subclass_of($WF, 'WidgetFactory')) {
  echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WF is not a subclass of WidgetFactory\n";
}
// utilizzabile dal PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
  echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
  echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>

Il precedente esempio visualizzerà:

yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory

Vedere anche get_class(), get_parent_class() e is_a().

method_exists

(PHP 4, PHP 5)

method_exists -- Verifica se il metodo esiste nella classe

Descrizione

bool method_exists ( object object, string nome_metodo )

Questa funzione restituisce TRUE se il metodo indicato dal parametro nome_metodo è stato nell'oggetto indicato da oggetto, altrimenti FALSE.

Esempio 1. Esempio di uso di method_exists()

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

Il precedente esempio visualizzerà:

bool(true)

property_exists

(PHP 5 >= 5.1.0RC1)

property_exists --  Checks if the object or class has a property

Descrizione

bool property_exists ( mixed class, string property )

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.

Elenco dei parametri

class

A string with the class name or an object of the class to test for

property

The name of the property

Valori restituiti

Returns TRUE if the property exists or FALSE otherwise.

Esempi

Esempio 1. A property_exists() example

<?php

class myClass {
    public $mine;
    private $xpto;
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //false, isn't public

?>

Vedere anche:

method_exists()

XIII. Classkit Functions

Introduzione

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.


Installazione

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


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

CLASSKIT_ACC_PRIVATE (int)

Marks the method private

CLASSKIT_ACC_PROTECTED (int)

Marks the method protected

CLASSKIT_ACC_PUBLIC (int)

Marks the method public

Sommario
classkit_import -- Import new class method definitions from a file
classkit_method_add -- Dynamically adds a new method to a given class
classkit_method_copy -- Copies a method from class to another
classkit_method_redefine -- Dynamically changes the code of the given method
classkit_method_remove -- Dynamically removes the given method
classkit_method_rename -- Dynamically changes the name of the given method

classkit_import

(PECL)

classkit_import -- Import new class method definitions from a file

Descrizione

array classkit_import ( string filename )

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.

Elenco dei parametri

filename

The filename of the class method definitions to import

Valori restituiti

Associative array of imported methods

Esempi

Esempio 1. classkit_import() example

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

Il precedente esempio visualizzerà:

foo!
bar!

classkit_method_add

(PECL)

classkit_method_add -- Dynamically adds a new method to a given class

Descrizione

bool classkit_method_add ( string classname, string methodname, string args, string code [, int flags] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Elenco dei parametri

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. classkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

Il precedente esempio visualizzerà:

16

classkit_method_copy

(PECL)

classkit_method_copy -- Copies a method from class to another

Descrizione

bool classkit_method_copy ( string dClass, string dMethod, string sClass [, string sMethod] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Elenco dei parametri

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. classkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

Il precedente esempio visualizzerà:

foo!

classkit_method_redefine

(PECL)

classkit_method_redefine -- Dynamically changes the code of the given method

Descrizione

bool classkit_method_redefine ( string classname, string methodname, string args, string code [, int flags] )

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.

Elenco dei parametri

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. classkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

Il precedente esempio visualizzerà:

Before: foo!
After: bar!

classkit_method_remove

(PECL)

classkit_method_remove -- Dynamically removes the given method

Descrizione

bool classkit_method_remove ( string classname, string methodname )

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.

Elenco dei parametri

classname

The class in which to remove the method

methodname

The name of the method to remove

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. classkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
    
    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

Il precedente esempio visualizzerà:

bar

classkit_method_rename

(PECL)

classkit_method_rename -- Dynamically changes the name of the given method

Descrizione

bool classkit_method_rename ( string classname, string methodname, string newname )

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.

Elenco dei parametri

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. classkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

Il precedente esempio visualizzerà:

foo!

XIV. Funzioni ClibPDF

Introduzione

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.


Requisiti

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.


Installazione

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


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

CPDF_PM_NONE (integer)

CPDF_PM_OUTLINES (integer)

CPDF_PM_THUMBS (integer)

CPDF_PM_FULLSCREEN (integer)

CPDF_PL_SINGLE (integer)

CPDF_PL_1COLUMN (integer)

CPDF_PL_2LCOLUMN (integer)

CPDF_PL_2RCOLUMN (integer)


Esempi

Esempio 1. Semplice esempio ClibPDF

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 50);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 50);
cpdf_lineto($cpdf, 740, 330);
cpdf_stroke($cpdf);
cpdf_finalize_page($cpdf, 1);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

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

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php");
cpdf_set_title($pdf, "Analog Clock");

while ($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);

  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */

  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

  /* linee dei minuti */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha < 360; $alpha += 6) {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
  }

  cpdf_restore($pdf);
  cpdf_save($pdf);

  /* linee dei 5 minuti */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha < 360; $alpha += 30) {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* disegna la lancetta delle ore */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* disegna la lancetta dei minuti */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* disegna la lancetta dei secondi */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* disegna un piccolo cerchio al centro */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>

Vedere anche:

Vedere anche la documentazione del modulo PDFlib.

Sommario
cpdf_add_annotation -- Aggiunge un'annotazione
cpdf_add_outline -- Aggiunge un segnalibro per la pagina corrente
cpdf_arc -- Disegna un arco
cpdf_begin_text -- Avvia una sezione di testo
cpdf_circle -- Disegna un cerchio
cpdf_clip -- Taglia dal path corrente
cpdf_close -- Chiude il documento PDF
cpdf_closepath_fill_stroke -- Close, fill and stroke current path
cpdf_closepath_stroke -- Chiude il path e disegna una linea lungo il path
cpdf_closepath -- Chiude la path corrente
cpdf_continue_text -- Scrive del testo nella riga seguente
cpdf_curveto -- Disegna una curva
cpdf_end_text -- Termina la sezione di testo
cpdf_fill_stroke -- Fill and stroke current path
cpdf_fill -- Riempie il path corrente
cpdf_finalize_page -- Chiude la pagina
cpdf_finalize -- Chiude il documento
cpdf_global_set_document_limits -- Sets document limits for any pdf document
cpdf_import_jpeg -- Apre un'immagine JPEG
cpdf_lineto -- Disegna una linea
cpdf_moveto -- Setta il punto corrente
cpdf_newpath -- Inizia un nuovo path
cpdf_open -- Apre un nuovo documento pdf
cpdf_output_buffer -- Scrive il documento pdf nel buffer di memoria
cpdf_page_init -- Inizia una nuova pagina
cpdf_place_inline_image -- Inserisce un'immagine nella pagina
cpdf_rect -- Disegna un rettangolo
cpdf_restore -- Ristabilisce le impostazioni salvate in precedenza
cpdf_rlineto -- Disegna una linea
cpdf_rmoveto -- Setta il punto corrente
cpdf_rotate_text --  Setta l'angolo di rotazione del testo
cpdf_rotate -- Effettua una rotazione
cpdf_save_to_file -- Salva il documento pdf in un file
cpdf_save -- Salva le impostazioni correnti
cpdf_scale -- Applica il coefficiente di scala
cpdf_set_action_url --  Imposta un link
cpdf_set_char_spacing -- Imposta la spaziatura fra caratteri
cpdf_set_creator -- Imposta il campo creatore nel documento pdf
cpdf_set_current_page -- Imposta la pagina corrente
cpdf_set_font_directories --  Imposta le directory in cui cercare quando si utilizzano font esterni
cpdf_set_font_map_file --  Imposta la tabella di associazione tra nome di file e nome di font, quando si usano font esterni
cpdf_set_font -- Seleziona l'aspetto e la dimensione del font corrente
cpdf_set_horiz_scaling -- Imposta il fattore di scala orizzontale del testo
cpdf_set_keywords -- Imposta i campi chiave del documento pdf
cpdf_set_leading -- Imposta la distanza fra righe di testo
cpdf_set_page_animation -- Sets duration between pages
cpdf_set_subject -- Imposta il campo soggetto del documento pdf
cpdf_set_text_matrix -- Imposta la matrice di testo
cpdf_set_text_pos -- Imposta la posizione del testo
cpdf_set_text_rendering -- Determines how text is rendered
cpdf_set_text_rise -- Sets the text rise
cpdf_set_title -- Imposta il campo titolo del documento pdf
cpdf_set_viewer_preferences --  How to show the document in the viewer
cpdf_set_word_spacing -- Imposta la spaziatura fra parole
cpdf_setdash -- Sets dash pattern
cpdf_setflat -- Sets flatness
cpdf_setgray_fill -- Imposta il grigio come colore per il riempimento
cpdf_setgray_stroke -- Sets drawing color to gray value
cpdf_setgray -- Imposta il grigio come colore per il disegno e il riempimento
cpdf_setlinecap -- Sets linecap parameter
cpdf_setlinejoin -- Sets linejoin parameter
cpdf_setlinewidth -- Imposta la larghezza delle linee
cpdf_setmiterlimit -- Sets miter limit
cpdf_setrgbcolor_fill -- Sets filling color to rgb color value
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
cpdf_setrgbcolor -- Imposta il valore del colore rgb come colore per il disegno e il riempimento
cpdf_show_xy -- Output text at position
cpdf_show -- Scrive il testo alla posizione corrente
cpdf_stringwidth -- Restituisce la larghezza del testo nel font corrente
cpdf_stroke -- Disegna una linea lungo il path
cpdf_text -- Scrive il testo con i parametri
cpdf_translate -- Sets origin of coordinate system

cpdf_add_annotation

(PHP 3 >= 3.0.12, PHP 4, PHP 5 <= 5.0.4)

cpdf_add_annotation -- Aggiunge un'annotazione

Descrizione

bool cpdf_add_annotation ( int documento_pdf, float llx, float lly, float urx, float ury, string titolo, string contenuto [, int modo] )

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.

cpdf_add_outline

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_add_outline -- Aggiunge un segnalibro per la pagina corrente

Descrizione

int cpdf_add_outline ( int documento_pdf, int lastoutline, int sublevel, int open, int pagenr, string testo )

La funzione cpdf_add_outline() aggiunge un segnalibro con il testo testo che punta alla pagina corrente.

Esempio 1. Aggiungere il contorno alla pagina

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
// ...
// alcuni disegni
// ...
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

cpdf_arc

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_arc -- Disegna un arco

Descrizione

bool cpdf_arc ( int documento_pdf, float x-coor, float y-coor, float raggio, float inizio, float fine [, int modo] )

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

cpdf_begin_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_begin_text -- Avvia una sezione di testo

Descrizione

bool cpdf_begin_text ( int pdf_document )

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

Esempio 1. Output di testo

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Un p&ograve; di testo");
cpdf_end_text($pdf)
?>

Vedere anche cpdf_end_text().

cpdf_circle

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_circle -- Disegna un cerchio

Descrizione

bool cpdf_circle ( int documento_pdf, float x-coor, float y-coor, float raggio [, int modo] )

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

cpdf_clip

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_clip -- Taglia dal path corrente

Descrizione

bool cpdf_clip ( int documento_pdf )

La funzione cpdf_clip() taglia tutti i disegni dal path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_close

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_close -- Chiude il documento PDF

Descrizione

bool cpdf_close ( int documento_pdf )

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

cpdf_closepath_fill_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

bool cpdf_closepath_fill_stroke ( int pdf_document )

The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path. 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().

cpdf_closepath_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath_stroke -- Chiude il path e disegna una linea lungo il path

Descrizione

bool cpdf_closepath_stroke ( int documento_pdf )

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

cpdf_closepath

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_closepath -- Chiude la path corrente

Descrizione

bool cpdf_closepath ( int documento_pdf )

La funzione cpdf_closepath() chiude la path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_continue_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_continue_text -- Scrive del testo nella riga seguente

Descrizione

bool cpdf_continue_text ( int documento_pdf, string testo )

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

cpdf_curveto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_curveto -- Disegna una curva

Descrizione

bool cpdf_curveto ( int documento_pdf, float x1, float y1, float x2, float y2, float x3, float y3 [, int modo] )

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

cpdf_end_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_end_text -- Termina la sezione di testo

Descrizione

bool cpdf_end_text ( int documento_pdf )

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.

Esempio 1. Output di testo

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Un p&ograve; di testo");
cpdf_end_text($pdf)
?>

Vedere anche cpdf_begin_text().

cpdf_fill_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_fill_stroke -- Fill and stroke current path

Description

bool cpdf_fill_stroke ( int pdf_document )

The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path. 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().

cpdf_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_fill -- Riempie il path corrente

Descrizione

bool cpdf_fill ( int documento_pdf )

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

cpdf_finalize_page

(PHP 3 >= 3.0.10, PHP 4, PHP 5 <= 5.0.4)

cpdf_finalize_page -- Chiude la pagina

Descrizione

bool cpdf_finalize_page ( int documento_pdf, int numero_pagina )

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

cpdf_finalize

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_finalize -- Chiude il documento

Descrizione

bool cpdf_finalize ( int documento_pdf )

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

cpdf_global_set_document_limits

(PHP 4, PHP 5 <= 5.0.4)

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

bool cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects )

The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also cpdf_open().

cpdf_import_jpeg

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_import_jpeg -- Apre un'immagine JPEG

Descrizione

int cpdf_import_jpeg ( int documento_pdf, string nome_file, float x-coor, float y-coor, float angolo, float larghezza, float altezza, float scala-x, float scala-y, int gsave [, int modo] )

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

cpdf_lineto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_lineto -- Disegna una linea

Descrizione

bool cpdf_lineto ( int documento_pdf, float x-coor, float y-coor [, int modo] )

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

cpdf_moveto

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_moveto -- Setta il punto corrente

Descrizione

bool cpdf_moveto ( int documento_pdf, float x-coor, float y-coor [, int modo] )

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.

cpdf_newpath

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_newpath -- Inizia un nuovo path

Descrizione

bool cpdf_newpath ( int documento_pdf )

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.

cpdf_open

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_open -- Apre un nuovo documento pdf

Descrizione

int cpdf_open ( int compressione [, string nome_file] )

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

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 memoria

Description

bool cpdf_output_buffer ( int documento_pdf )

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

cpdf_page_init

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_page_init -- Inizia una nuova pagina

Descrizione

bool cpdf_page_init ( int documento_pdf, int numero_pagina, int orientamento, float altezza, float larghezza [, float unità] )

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

cpdf_place_inline_image

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_place_inline_image -- Inserisce un'immagine nella pagina

Descrizione

bool cpdf_place_inline_image ( int documento_pdf, int immagine, float x-coor, float y-coor, float angolo, float larghezza, float altezza [, int modo] )

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

cpdf_rect

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_rect -- Disegna un rettangolo

Descrizione

bool cpdf_rect ( int documento_pdf, float x-coor, float y-coor, float larghezza, float altezza [, int modo] )

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
 
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
 
// imposta il colore di riempimento a rosso
cpdf_setrgbcolor($cpdf, 1, 0, 0);
 
// traccia il rettangolo di (180 * 100)
cpdf_rect($cpdf, 645, 400, 180, 100);
 
// riempie il rettangolo
cpdf_fill($cpdf);
 
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
 
?>

cpdf_restore

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_restore -- Ristabilisce le impostazioni salvate in precedenza

Descrizione

bool cpdf_restore ( int documento_pdf )

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

Esempio 1. Salvare/Richiamare

<?php
cpdf_save($pdf);
// effettuare qualsiasi tipo di rotazione, trasformazione, ...
cpdf_restore($pdf)
?>

Vedere anche cpdf_save().

cpdf_rlineto

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rlineto -- Disegna una linea

Descrizione

bool cpdf_rlineto ( int documento_pdf, float x-coor, float y-coor [, int modo] )

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

cpdf_rmoveto

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rmoveto -- Setta il punto corrente

Descrizione

bool cpdf_rmoveto ( int documento_pdf, float x-coor, float y-coor [, int modo] )

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

cpdf_rotate_text

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_rotate_text --  Setta l'angolo di rotazione del testo

Descrizione

bool cpdf_rotate_text ( int documento pdf, float angolo )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cpdf_rotate

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_rotate -- Effettua una rotazione

Descrizione

bool cpdf_rotate ( int documento_pdf, float angolo )

La funzione cpdf_rotate() effettua una rotazione di angolo gradi. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_save_to_file

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_save_to_file -- Salva il documento pdf in un file

Descrizione

bool cpdf_save_to_file ( int documento_pdf, string nome_file )

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

cpdf_save

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_save -- Salva le impostazioni correnti

Descrizione

bool cpdf_save ( int documento_pdf )

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

cpdf_scale

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_scale -- Applica il coefficiente di scala

Descrizione

bool cpdf_scale ( int documento_pdf, float scala-x, float scala-y )

La funzione cpdf_scale() applica il coefficiente di scala in entrambe le direzioni. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_set_action_url

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_action_url --  Imposta un link

Descrizione

bool cpdf_set_action_url ( int documento_pdf, float xll, float yll, float xur, float xur, string url [, int modo] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cpdf_set_char_spacing

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_char_spacing -- Imposta la spaziatura fra caratteri

Descrizione

bool cpdf_set_char_spacing ( int documento_pdf, float spaziatura )

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

cpdf_set_creator

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_creator -- Imposta il campo creatore nel documento pdf

Descrizione

bool cpdf_set_creator ( int pdf_document, string creatore )

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

cpdf_set_current_page

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_current_page -- Imposta la pagina corrente

Descrizione

bool cpdf_set_current_page ( int documento_pdf, int numero_pagina )

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

cpdf_set_font_directories

(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

Descrizione

bool cpdf_set_font_directories ( int documento_pdf, string pfmdir, string pfbdir )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cpdf_set_font_map_file

(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

Descrizione

bool cpdf_set_font_map_file ( int documento_pdf, string nome_file )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cpdf_set_font

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_font -- Seleziona l'aspetto e la dimensione del font corrente

Descrizione

bool cpdf_set_font ( int documento_pdf, string nome_font, float dimensione, string codifica )

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

cpdf_set_horiz_scaling

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_horiz_scaling -- Imposta il fattore di scala orizzontale del testo

Descrizione

bool cpdf_set_horiz_scaling ( int documento_pdf, float scala )

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

cpdf_set_keywords

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_keywords -- Imposta i campi chiave del documento pdf

Descrizione

bool cpdf_set_keywords ( int pdf_document, string parole_chiave )

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

cpdf_set_leading

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_leading -- Imposta la distanza fra righe di testo

Descrizione

bool cpdf_set_leading ( int documento_pdf, float distanza )

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

cpdf_set_page_animation

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_page_animation -- Sets duration between pages

Description

bool cpdf_set_page_animation ( int pdf_document, int transition, float duration )

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.

cpdf_set_subject

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_subject -- Imposta il campo soggetto del documento pdf

Descrizione

bool cpdf_set_subject ( int pdf_document, string soggetto )

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

cpdf_set_text_matrix

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_matrix -- Imposta la matrice di testo

Descrizione

bool cpdf_set_text_matrix ( int documento_pdf, array matrice )

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.

cpdf_set_text_pos

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_pos -- Imposta la posizione del testo

Descrizione

bool cpdf_set_text_pos ( int documento_pdf, float x-coor, float y-coor [, int modo] )

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

cpdf_set_text_rendering

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_rendering -- Determines how text is rendered

Description

bool cpdf_set_text_rendering ( int pdf_document, int rendermode )

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.

cpdf_set_text_rise

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_text_rise -- Sets the text rise

Description

bool cpdf_set_text_rise ( int pdf_document, float value )

The cpdf_set_text_rise() function sets the text rising to value units. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_set_title

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_title -- Imposta il campo titolo del documento pdf

Descrizione

bool cpdf_set_title ( int pdf_document, string titolo )

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

cpdf_set_viewer_preferences

(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_viewer_preferences --  How to show the document in the viewer

Description

bool cpdf_set_viewer_preferences ( int pdfdoc, array preferences )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cpdf_set_word_spacing

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_set_word_spacing -- Imposta la spaziatura fra parole

Descrizione

bool cpdf_set_word_spacing ( int documento_pdf, float spaziatura )

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

cpdf_setdash

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setdash -- Sets dash pattern

Description

bool cpdf_setdash ( int pdf_document, float white, float black )

The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_setflat

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setflat -- Sets flatness

Description

bool cpdf_setflat ( int pdf_document, float value )

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.

cpdf_setgray_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray_fill -- Imposta il grigio come colore per il riempimento

Descrizione

bool cpdf_setgray_fill ( int documento_pdf, float valore )

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

cpdf_setgray_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

bool cpdf_setgray_stroke ( int pdf_document, float gray_value )

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

cpdf_setgray

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setgray -- Imposta il grigio come colore per il disegno e il riempimento

Descrizione

bool cpdf_setgray ( int documento_pdf, float valore_grigio )

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

cpdf_setlinecap

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinecap -- Sets linecap parameter

Description

bool cpdf_setlinecap ( int pdf_document, int value )

The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_setlinejoin

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinejoin -- Sets linejoin parameter

Description

bool cpdf_setlinejoin ( int pdf_document, int value )

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.

cpdf_setlinewidth

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setlinewidth -- Imposta la larghezza delle linee

Description

bool cpdf_setlinewidth ( int documento_pdf, float larghezza )

La funzione cpdf_setlinewidth() imposta la larghezza delle linee a larghezza. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

cpdf_setmiterlimit

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setmiterlimit -- Sets miter limit

Description

bool cpdf_setmiterlimit ( int pdf_document, float value )

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.

cpdf_setrgbcolor_fill

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

bool cpdf_setrgbcolor_fill ( int pdf_document, float red_value, float green_value, float blue_value )

The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.

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

cpdf_setrgbcolor_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

bool cpdf_setrgbcolor_stroke ( int pdf_document, float red_value, float green_value, float blue_value )

The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value. 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().

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 riempimento

Descrizione

bool cpdf_setrgbcolor ( int documento_pdf, float valore_rosso, float valore_verde, float valore_blu )

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

cpdf_show_xy

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_show_xy -- Output text at position

Description

bool cpdf_show_xy ( int pdf_document, string text, float x-coor, float y-coor [, int mode] )

The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor). 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().

cpdf_show

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_show -- Scrive il testo alla posizione corrente

Descrizione

bool cpdf_show ( int documento_pdf, string testo )

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

cpdf_stringwidth

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_stringwidth -- Restituisce la larghezza del testo nel font corrente

Descrizione

float cpdf_stringwidth ( int documento_pdf, string testo )

La funzione cpdf_stringwidth() restituisce la larghezza della stringa in testo. Richiede che un font sia settato in precedenza.

Vedere anche cpdf_set_font().

cpdf_stroke

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_stroke -- Disegna una linea lungo il path

Description

bool cpdf_stroke ( int documento_pdf )

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

cpdf_text

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_text -- Scrive il testo con i parametri

Descrizione

bool cpdf_text ( int documento_pdf, string testo, float x-coor, float y-coor [, int modo [, float orientamento [, int allineamento]]] )

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

cpdf_translate

(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)

cpdf_translate -- Sets origin of coordinate system

Description

bool cpdf_translate ( int pdf_document, float x-coor, float y-coor [, int mode] )

The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor). 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.

XV. Funzioni di supporto COM per Windows

Introduzione

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.


Requisiti

Le funzioni COM sono disponibili solo sulle versioni Windows di PHP.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. opzioni di configurazione Com

NomeDefaultModificabile inLog variazioni
com.allow_dcom"0"PHP_INI_SYSTEMDisponibile dal PHP 4.0.5.
com.autoregister_typelib"0"PHP_INI_SYSTEMPHP_INI_SYSTEM in PHP 4. Disponibile in PHP 4.1.0.
com.autoregister_verbose"0"PHP_INI_SYSTEMPHP_INI_SYSTEM in PHP 4. Disponibile dal PHP 4.1.0.
com.autoregister_casesensitive"1"PHP_INI_SYSTEMPHP_INI_SYSTEM in PHP 4. Disponibile dal PHP 4.1.0.
com.code_page""PHP_INI_ALLDisponibile dal PHP 5.0.0.
com.typelib_file""PHP_INI_SYSTEMDisponibile dal PHP 4.0.5.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

com.allow_dcom

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.

com.autoregister_typelib

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 .

com.autoregister_verbose

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.

com.autoregister_casesensitive

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.

com.code_page

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.

com.typelib_file

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.


Costanti predefinite

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.

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)


Vedere anche:

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)

Sommario
COM -- classe COM
DOTNET -- DOTNET class
VARIANT -- classe VARIANT
com_addref --  Incrementa il contatore di referenze.
com_create_guid --  Generate a globally unique identifier (GUID)
com_event_sink --  Connect events from a COM object to a PHP object
com_get_active_object --  Returns a handle to an already running instance of a COM object
com_get --  Ricava il valore di una proprietà di un componente COM
com_invoke --  Chiama un metodo di un componente COM.
com_isenum -- Recupera un IEnumVariant
com_load_typelib -- Carica una Typelib
com_load --  Crea un nuovo riferimento a un componente COM
com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds
com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface
com_propget -- Alias di com_get()
com_propput -- Alias di com_set()
com_propset -- Alias di com_set()
com_release --  Decrementa il contaotre di referenze.
com_set --  Assegna un valore a una proprietà di un oggetto COM
variant_abs --  Returns the absolute value of a variant
variant_add --  "Adds" two variant values together and returns the result
variant_and --  performs a bitwise AND operation between two variants and returns the result
variant_cast --  Convert a variant into a new variant object of another type
variant_cat --  concatenates two variant values together and returns the result
variant_cmp --  Compares two variants
variant_date_from_timestamp --  Returns a variant date representation of a unix timestamp
variant_date_to_timestamp --  Converts a variant date/time value to unix timestamp
variant_div --  Returns the result from dividing two variants
variant_eqv --  Performs a bitwise equivalence on two variants
variant_fix --  Returns the integer portion ? of a variant
variant_get_type -- Returns the type of a variant object
variant_idiv --  Converts variants to integers and then returns the result from dividing them
variant_imp --  Performs a bitwise implication on two variants
variant_int --  Returns the integer portion of a variant
variant_mod --  Divides two variants and returns only the remainder
variant_mul --  multiplies the values of the two variants and returns the result
variant_neg --  Performs logical negation on a variant
variant_not --  Performs bitwise not negation on a variant
variant_or --  Performs a logical disjunction on two variants
variant_pow --  Returns the result of performing the power function with two variants
variant_round --  Rounds a variant to the specified number of decimal places
variant_set_type --  Convert a variant into another type "in-place"
variant_set --  Assigns a new value for a variant object
variant_sub --  subtracts the value of the right variant from the left variant value and returns the result
variant_xor --  Performs a logical exclusion on two variants

COM

(no version information, might be only in CVS)

COM -- classe COM

Sinossi

$obj = new COM("server.object")

Descrizione

La classe COM fornisce un ambiente per integrare i componenti (D)COM negli script PHP.

Metodi

string COM::COM ( string nome_modulo [, string nome_server [, int codepage]] )

costruttore della classe COM. Parametri:

nome_modulo

nome o class-id del componente desiderato.

nome_server

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.

codepage

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)

<?php
// esecuzione di Word
$word = new COM("word.application") or die("Non sono riuscito ad eseguire Word");
echo "Word caricato, versione {$word->Version}\n";

//lo porta in primo piano
$word->Visible = 1;

//apre un documento vuoto
$word->Documents->Add();

//esegue un po' di operazioni inutili
$word->Selection->TypeText("Questa è una prova...");
$word->Documents[1]->SaveAs("Prova inutile.doc");

//chiude Word
$word->Quit();

//libera l'oggetto
$word->Release();
$word = null;
?>

Esempio 2. esempio di COM (2)

<?php

$conn = new COM("ADODB.Connection") or die("non riesco ad attivare ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM unatabella");    // Recordset

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

for ($i=0; $i < $num_colonne; $i++) {
    $campi[$i] = $rs->Fields($i);
}

$contorighe = 0;
while (!$rs->EOF) {
    for ($i=0; $i < $num_colonne; $i++) {
        echo $campi[$i]->value . "\t";
    }
    echo "\n";
    $contorighe++;            // incrementa contorighe
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs->Release();
$conn->Release();

$rs = null;
$conn = null;

?>

DOTNET

(no version information, might be only in CVS)

DOTNET -- DOTNET class

Sinossi

$obj = new DOTNET("assembly", "classname")

Description

The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.

Methods

string DOTNET::DOTNET ( string assembly_name, string class_name [, int codepage] )

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.

Esempio 1. DOTNET example

<?php
  $stack = new DOTNET("mscorlib", "System.Collections.Stack"); 
  $stack->Push(".Net"); 
  $stack->Push("Hello "); 
  echo $stack->Pop() . $stack->Pop(); 
?>

Nota: You need to install the .Net runtime on your web server to take advantage of this feature.

VARIANT

(no version information, might be only in CVS)

VARIANT -- classe VARIANT

Sinossi

$vVar = new VARIANT($var)

Descrizione

Un semplice contenitore per includere le variabili in strutture VARIANT.

Metodi

string VARIANT::VARIANT ( [mixed valore [, int tipo [, int codepage]]] )

costruttore della classe VARIANT. Parametri:

valore

valore iniziale. se omesso viene creato un oggetto VT_EMPTY.

tipo

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.

codepage

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.

com_addref

(PHP 4 >= 4.1.0)

com_addref --  Incrementa il contatore di referenze.

Descrizione

void com_addref ( void )

Incrementa il contatore di referenze.

com_create_guid

(PHP 5)

com_create_guid --  Generate a globally unique identifier (GUID)

Description

string com_create_guid ( void )

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.

com_event_sink

(PHP 4 >= 4.2.3, PHP 5)

com_event_sink --  Connect events from a COM object to a PHP object

Description

bool com_event_sink ( variant comobject, object sinkobject [, mixed sinkinterface] )

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

<?php
class IEEventSinker {
  var $terminated = false;

  function ProgressChange($progress, $progressmax) {
    echo "Download progress: $progress / $progressmax\n";
  }

  function DocumentComplete(&$dom, $url) {
    echo "Document $url complete\n";
  }

  function OnQuit() {
    echo "Quit!\n";
    $this->terminated = true;
  }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$sink =& new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.php.net");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

See also com_print_typeinfo(), com_message_pump().

com_get_active_object

(PHP 5)

com_get_active_object --  Returns a handle to an already running instance of a COM object

Description

variant com_get_active_object ( string progid [, int code_page] )

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.

com_get

(PHP 3 >= 3.0.3, PHP 4)

com_get --  Ricava il valore di una proprietà di un componente COM

Descrizione

mixed com_get ( resource oggetto_com, string nome_prop )

Restituisce il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore.

com_invoke

(PHP 4)

com_invoke --  Chiama un metodo di un componente COM.

Descrizione

mixed com_invoke ( resource oggetto_com, string nome_funzione [, mixed parametri, ...] )

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.

com_isenum

(PHP 4 >= 4.1.0)

com_isenum -- Recupera un IEnumVariant

Descrizione

void com_isenum ( object modulo_com )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5)

com_load_typelib -- Carica una Typelib

Descrizione

void com_load_typelib ( string nome_typelib [, int ignora_maiuscole] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

com_load

(PHP 4)

com_load --  Crea un nuovo riferimento a un componente COM

Descrizione

string com_load ( string nome_modulo [, string nome_server [, int codepage]] )

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.

com_message_pump

(PHP 4 >= 4.2.3, PHP 5)

com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds

Description

bool com_message_pump ( [int timeoutms] )

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

com_print_typeinfo

(PHP 4 >= 4.2.3, PHP 5)

com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface

Description

bool com_print_typeinfo ( object comobject [, string dispinterface [, bool wantsink]] )

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

com_propget

(PHP 3 >= 3.0.3, PHP 4)

com_propget -- Alias di com_get()

Descrizione

Questa funzione è un alias di com_get().

com_propput

(PHP 3 >= 3.0.3, PHP 4)

com_propput -- Alias di com_set()

Descrizione

Questa funzione è un alias di com_set().

com_propset

(PHP 3 >= 3.0.3, PHP 4)

com_propset -- Alias di com_set()

Descrizione

Questa funzione è un alias di com_set().

com_release

(PHP 4 >= 4.1.0)

com_release --  Decrementa il contaotre di referenze.

Descrizione

void com_release ( void )

Decrementa il contatore di referenze.

com_set

(PHP 3 >= 3.0.3, PHP 4)

com_set --  Assegna un valore a una proprietà di un oggetto COM

Descrizione

void com_set ( resource oggetto_com, string nome_prop, mixed valore )

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.

variant_abs

(PHP 5)

variant_abs --  Returns the absolute value of a variant

Description

mixed variant_abs ( mixed val )

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.

variant_add

(PHP 5)

variant_add --  "Adds" two variant values together and returns the result

Description

mixed variant_add ( mixed left, mixed right )

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

IfThen
Both expressions are of the string typeConcatenation
One expression is a string type and the other a characterAddition
One expression is numeric and the other is a stringAddition
Both expressions are numericAddition
Either expression is NULLNULL is returned
Both expressions are emptyInteger 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.

variant_and

(PHP 5)

variant_and --  performs a bitwise AND operation between two variants and returns the result

Description

mixed variant_and ( mixed left, mixed right )

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 isIf right isthen the result is
TRUETRUETRUE
TRUEFALSEFALSE
TRUENULLNULL
FALSETRUEFALSE
FALSEFALSEFALSE
FALSENULLFALSE
NULLTRUENULL
NULLFALSEFALSE
NULLNULLNULL

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.

variant_cast

(PHP 5)

variant_cast --  Convert a variant into a new variant object of another type

Description

variant variant_cast ( variant variant, int type )

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

variant_cat

(PHP 5)

variant_cat --  concatenates two variant values together and returns the result

Description

mixed variant_cat ( mixed left, mixed right )

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.

variant_cmp

(PHP 5)

variant_cmp --  Compares two variants

Description

int variant_cmp ( mixed left, mixed right [, int lcid [, int flags]] )

Compares left with right and returns one of the following values:

Tabella 1. Variant Comparision Results

valuemeaning
VARCMP_LTleft is less than right
VARCMP_EQleft is equal to right
VARCMP_GTleft is greater than right
VARCMP_NULLEither 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

valuemeaning
NORM_IGNORECASECompare case insensitively
NORM_IGNORENONSPACEIgnore nonspacing characters
NORM_IGNORESYMBOLSIgnore symbols
NORM_IGNOREWIDTHIgnore string width
NORM_IGNOREKANATYPEIgnore Kana type
NORM_IGNOREKASHIDAIgnore 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.

variant_date_from_timestamp

(PHP 5)

variant_date_from_timestamp --  Returns a variant date representation of a unix timestamp

Description

variant variant_date_from_timestamp ( int timestamp )

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

variant_date_to_timestamp

(PHP 5)

variant_date_to_timestamp --  Converts a variant date/time value to unix timestamp

Description

int variant_date_to_timestamp ( variant variant )

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

variant_div

(PHP 5)

variant_div --  Returns the result from dividing two variants

Description

mixed variant_div ( mixed left, mixed right )

Divides left by right and returns the result, subject to the following rules:

Tabella 1. Variant Division Rules

IfThen
Both expressions are of the string, date, character, boolean typeDouble is returned
One expression is a string type and the other a characterDivision and a double is returned
One expression is numeric and the other is a stringDivision and a double is returned.
Both expressions are numericDivision and a double is returned
Either expression is NULLNULL is returned
right is empty and left is anything but emptyA 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 emptyA 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.

variant_eqv

(PHP 5)

variant_eqv --  Performs a bitwise equivalence on two variants

Description

mixed variant_eqv ( mixed left, mixed right )

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.

variant_fix

(PHP 5)

variant_fix --  Returns the integer portion ? of a variant

Description

mixed variant_fix ( mixed variant )

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.

variant_get_type

(PHP 5)

variant_get_type -- Returns the type of a variant object

Description

int variant_get_type ( variant variant )

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.

variant_idiv

(PHP 5)

variant_idiv --  Converts variants to integers and then returns the result from dividing them

Description

mixed variant_idiv ( mixed left, mixed right )

Converts left and right to integer values, and then performs integer division according the following rules:

Tabella 1. Variant Integer Division Rules

IfThen
Both expressions are of the string, date, character, boolean typeDivision and integer is returned
One expression is a string type and the other a characterDivision
One expression is numeric and the other is a stringDivision
Both expressions are numericDivision
Either expression is NULLNULL is returned
Both expressions are emptyA 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.

variant_imp

(PHP 5)

variant_imp --  Performs a bitwise implication on two variants

Description

mixed variant_imp ( mixed left, mixed right )

Performs a bitwise implication operation, according to the following truth table:

Tabella 1. Variant Implication Table

If left isIf right isthen the result is
TRUETRUETRUE
TRUEFALSETRUE
TRUENULLTRUE
FALSETRUETRUE
FALSEFALSETRUE
FALSENULLTRUE
NULLTRUETRUE
NULLFALSENULL
NULLNULLNULL

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.

variant_int

(PHP 5)

variant_int --  Returns the integer portion of a variant

Description

mixed variant_int ( mixed variant )

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.

variant_mod

(PHP 5)

variant_mod --  Divides two variants and returns only the remainder

Description

mixed variant_mod ( mixed left, mixed right )

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.

variant_mul

(PHP 5)

variant_mul --  multiplies the values of the two variants and returns the result

Description

mixed variant_mul ( mixed left, mixed right )

Multiplies left by right and returns the result, subject to the following rules:

Tabella 1. Variant Multiplication Rules

IfThen
Both expressions are of the string, date, character, boolean typeMultiplication
One expression is a string type and the other a characterMultiplication
One expression is numeric and the other is a stringMultiplication
Both expressions are numericMultiplication
Either expression is NULLNULL is returned
Both expressions are emptyEmpty 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.

variant_neg

(PHP 5)

variant_neg --  Performs logical negation on a variant

Description

mixed variant_neg ( mixed variant )

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.

variant_not

(PHP 5)

variant_not --  Performs bitwise not negation on a variant

Description

mixed variant_not ( mixed variant )

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.

variant_or

(PHP 5)

variant_or --  Performs a logical disjunction on two variants

Description

mixed variant_or ( mixed left, mixed right )

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 isIf right isthen the result is
TRUETRUETRUE
TRUEFALSETRUE
TRUENULLTRUE
FALSETRUETRUE
FALSEFALSEFALSE
FALSENULLNULL
NULLTRUETRUE
NULLFALSENULL
NULLNULLNULL

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.

variant_pow

(PHP 5)

variant_pow --  Returns the result of performing the power function with two variants

Description

mixed variant_pow ( mixed left, mixed right )

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.

variant_round

(PHP 5)

variant_round --  Rounds a variant to the specified number of decimal places

Description

mixed variant_round ( mixed variant, int decimals )

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.

variant_set_type

(PHP 5)

variant_set_type --  Convert a variant into another type "in-place"

Description

void variant_set_type ( variant variant, int type )

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

variant_set

(PHP 5)

variant_set --  Assigns a new value for a variant object

Description

void variant_set ( variant variant, mixed value )

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.

variant_sub

(PHP 5)

variant_sub --  subtracts the value of the right variant from the left variant value and returns the result

Description

mixed variant_sub ( mixed left, mixed right )

Subtracts right from left using the following rules:

Tabella 1. Variant Subtraction Rules

IfThen
Both expressions are of the string typeSubtraction
One expression is a string type and the other a characterSubtraction
One expression is numeric and the other is a stringSubtraction.
Both expressions are numericSubtraction
Either expression is NULLNULL is returned
Both expressions are emptyEmpty 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.

variant_xor

(PHP 5)

variant_xor --  Performs a logical exclusion on two variants

Description

mixed variant_xor ( mixed left, mixed right )

Performs a logical exclusion, according to the following truth table:

Tabella 1. Variant XOR Rules

If left isIf right isthen the result is
TRUETRUEFALSE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
NULLNULLNULL

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.

XVI. Funzioni di Crack

Introduzione

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.


Requisiti

Maggiori informazioni riguardo CrackLib possono essere trovate, insieme alla libreria, a http://www.crypticide.com/users/alecm/.


Installazione

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


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione per Crack

NomeDefaultModificabileLog modifiche
crack.default_dictionaryNULLPHP_INI_SYSTEMDisponibile da PHP 4.0.5.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

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

<?php
// Apre il dizionario di CrackLib
$dizionario = crack_opendict('/usr/local/lib/pw_dict')
     or die('Incapace di aprire il dizionario di CrackLib');

// Esegue il controllo della password
$controllo = controllo_crack($dizionario, 'gx9A2s0x');

// Recupera i messaggi
$messaggio = crack_getlastmessage();
echo $messaggio; // 'password forte'

// Chiude il dizionario
crack_closedict($dizionario);
?>

Nota: Se crack_check() restituisce TRUE, crack_getlastmessage() restituirà 'password forte'.

Sommario
crack_check -- Effettua un controllo nascosto con la password data
crack_closedict -- Chiude un dizionario di CrackLib aperto
crack_getlastmessage -- Restituisce il messaggio dell'ultimo controllo nascosto
crack_opendict -- Apre un nuovo dizionario di CrackLib

crack_check

(PHP 4 >= 4.0.5, PECL)

crack_check -- Effettua un controllo nascosto con la password data

Descrizione

bool crack_check ( [resource dizionario, string password] )

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.

crack_closedict

(PHP 4 >= 4.0.5, PECL)

crack_closedict -- Chiude un dizionario di CrackLib aperto

Descrizione

bool crack_closedict ( [resource dizionario] )

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.

crack_getlastmessage

(PHP 4 >= 4.0.5, PECL)

crack_getlastmessage -- Restituisce il messaggio dell'ultimo controllo nascosto

Descrizione

string crack_getlastmessage ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

crack_opendict

(PHP 4 >= 4.0.5, PECL)

crack_opendict -- Apre un nuovo dizionario di CrackLib

Descrizione

resource crack_opendict ( string dizionario )

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

XVII. Funzioni di tipo dei caratteri

Introduzione

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.


Requisiti

Nessuno oltre alle funzioni della libreria standard del C che sono sempre disponibili.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
ctype_alnum -- Controlla i caratteri alfanumerici
ctype_alpha -- Controlla i caratteri alfabetici
ctype_cntrl -- Controlla i caratteri di controllo
ctype_digit -- Controlla i caratteri numerici
ctype_graph -- Controlla ogni carattere stampabile tranne lo spazio
ctype_lower -- Controlla i caratteri minuscoli
ctype_print -- Controlla i caratteri stampabili
ctype_punct --  Controlla ogni carattere stampabile che non è uno spazio o un carattere alfanumerico
ctype_space -- Controlla gli spazi
ctype_upper -- Controlla i caratteri maiuscoli
ctype_xdigit --  Controlla i caratteri che rappresentano una cifra esadecimale

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5)

ctype_alnum -- Controlla i caratteri alfanumerici

Descrizione

bool ctype_alnum ( string testo )

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)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

Questo esempio visualizzerà :

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consists of all letters or digits.

Vedere anche ctype_alpha(), ctype_digit() e setlocale().

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5)

ctype_alpha -- Controlla i caratteri alfabetici

Descrizione

bool ctype_alpha ( string testo )

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)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "The string $testcase consists of all letters.\n";
    } else {
        echo "The string $testcase does not consist of all letters.\n";
    }
}
?>

This example will output :

The string KjgWZC consists of all letters.
The string arf12 does not consists of all letters.

Vedere anche ctype_upper(), ctype_lower() e setlocale().

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5)

ctype_cntrl -- Controlla i caratteri di controllo

Descrizione

bool ctype_cntrl ( string testo )

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

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "The string '$name' consists of all control characters.\n";
    } else {
        echo "The string '$name' does not consist of all control characters.\n";
    }
}
?>

L'esempio visualizzerà :

The string 'string1' consists of all control characters.
The string 'string2' does not consists of all control characters.

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit -- Controlla i caratteri numerici

Descrizione

bool ctype_digit ( string testo )

Restituisce TRUE se ogni carattere di testo è una cifra decimale, FALSE in caso contrario.

Esempio 1. Esempio di uso di ctype_digit()

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

Questo esempio visualizzerà :

The string 1820.20 does not consists of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consists of all digits.

Vedere anche ctype_alnum() e ctype_xdigit().

ctype_graph

(PHP 4 >= 4.0.4, PHP 5)

ctype_graph -- Controlla ogni carattere stampabile tranne lo spazio

Descrizione

bool ctype_graph ( string testo )

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

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "The string '$name' consists of all (visibly) printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all (visibly) printable characters.\n";
    }
}
?>

Questo esempio visualizzerà :

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

Vedere anche ctype_alnum(), ctype_print() e ctype_punct().

ctype_lower

(PHP 4 >= 4.0.4, PHP 5)

ctype_lower -- Controlla i caratteri minuscoli

Descrizione

bool ctype_lower ( string testo )

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)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "The string $testcase consists of all lowercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all lowercase letters.\n";
    }
}
?>

Questo esempio visualizzerà :

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

Vedere anche ctype_alpha(), ctype_upper() e setlocale().

ctype_print

(PHP 4 >= 4.0.4, PHP 5)

ctype_print -- Controlla i caratteri stampabili

Descrizione

bool ctype_print ( string testo )

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

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "The string '$name' consists of all printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all printable characters.\n";
    }
}
?>

Questo esempio visualizzerà :

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().

ctype_punct

(PHP 4 >= 4.0.4, PHP 5)

ctype_punct --  Controlla ogni carattere stampabile che non è uno spazio o un carattere alfanumerico

Descrizione

bool ctype_punct ( string testo )

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

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "The string $testcase consists of all punctuation.\n";
    } else {
        echo "The string $testcase does not consist of all punctuation.\n";
    }
}
?>

Questo esempio visualizzerà :

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

Vedere anche ctype_cntrl() e ctype_graph().

ctype_space

(PHP 4 >= 4.0.4, PHP 5)

ctype_space -- Controlla gli spazi

Descrizione

bool ctype_space ( string testo )

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

<?php
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of all whitespace characters.\n";
    } else {
        echo "The string '$name' does not consist of all whitespace characters.\n";
    }
}
?>

Questo esempio visualizzerà :

The string 'string1' consists of all whitespace characters.
The string 'string2' does not consist of all whitespace characters.
The string 'string3' does not consist of all whitespace characters.

Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().

ctype_upper

(PHP 4 >= 4.0.4, PHP 5)

ctype_upper -- Controlla i caratteri maiuscoli

Descrizione

bool ctype_upper ( string testo )

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)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase consists of all uppercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all uppercase letters.\n";
    }
}
?>

Questo esempio visualizzerà :

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

Vedere anche ctype_alpha(), ctype_lower(), e setlocale().

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5)

ctype_xdigit --  Controlla i caratteri che rappresentano una cifra esadecimale

Descrizione

bool ctype_xdigit ( string testo )

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

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?>

Questo esempio visualizzerà :

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

Vedere anche ctype_digit().

XVIII. Funzioni CURL, Client URL Library

Introduzione

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.


Requisiti

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.


Installazione

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)


Costanti predefinite

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.

CURLOPT_DNS_USE_GLOBAL_CACHE (integer)

CURLOPT_DNS_CACHE_TIMEOUT (integer)

CURLOPT_FTPSSLAUTH (integer)

Disponibile da PHP 5.1.0

CURLOPT_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_FTP_USE_EPSV (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_CAPATH (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLOPT_NOSIGNAL (integer)

CURLOPT_PROXYTYPE (integer)

CURLOPT_BUFFERSIZE (integer)

CURLOPT_HTTPGET (integer)

CURLOPT_HTTP_VERSION (integer)

CURLOPT_SSLKEY (integer)

CURLOPT_SSLKEYTYPE (integer)

CURLOPT_SSLKEYPASSWD (integer)

CURLOPT_SSLENGINE (integer)

CURLOPT_SSLENGINE_DEFAULT (integer)

CURLOPT_SSLCERTTYPE (integer)

CURLOPT_CRLF (integer)

CURLOPT_ENCODING (integer)

CURLOPT_PROXYPORT (integer)

CURLOPT_UNRESTRICTED_AUTH (integer)

CURLOPT_FTP_USE_EPRT (integer)

CURLOPT_HTTP200ALIASES (integer)

CURLOPT_HTTPAUTH (integer)

CURLAUTH_BASIC (integer)

CURLAUTH_DIGEST (integer)

CURLAUTH_GSSNEGOTIATE (integer)

CURLAUTH_NTLM (integer)

CURLAUTH_ANY (integer)

CURLAUTH_ANYSAFE (integer)

CURLOPT_PROXYAUTH (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLINFO_STARTTRANSFER_TIME (integer)

CURLINFO_CONTENT_TYPE (integer)

CURLINFO_REDIRECT_TIME (integer)

CURLINFO_REDIRECT_COUNT (integer)

CURL_VERSION_IPV6 (integer)

CURL_VERSION_KERBEROS4 (integer)

CURL_VERSION_SSL (integer)

CURL_VERSION_LIBZ (integer)

CURLVERSION_NOW (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)

CURLE_GOT_NOTHING (integer)

CURLE_SSL_ENGINE_NOTFOUND (integer)

CURLE_SSL_ENGINE_SETFAILED (integer)

CURLE_SEND_ERROR (integer)

CURLE_RECV_ERROR (integer)

CURLE_SHARE_IN_USE (integer)

CURLE_SSL_CERTPROBLEM (integer)

CURLE_SSL_CIPHER (integer)

CURLE_SSL_CACERT (integer)

CURLE_BAD_CONTENT_ENCODING (integer)

CURLE_LDAP_INVALID_URL (integer)

CURLE_FILESIZE_EXCEEDED (integer)

CURLFTPAUTH_DEFAULT (integer)

Available since PHP 5.1.0

CURLFTPAUTH_SSL (integer)

Available since PHP 5.1.0

CURLFTPAUTH_TLS (integer)

Disponibile da PHP 5.1.0

CURLE_FTP_SSL_FAILED (integer)

CURLPROXY_HTTP (integer)

CURLPROXY_SOCKS5 (integer)

CURL_NETRC_OPTIONAL (integer)

CURL_NETRC_IGNORED (integer)

CURL_NETRC_REQUIRED (integer)

CURL_HTTP_VERSION_NONE (integer)

CURL_HTTP_VERSION_1_0 (integer)

CURL_HTTP_VERSION_1_1 (integer)

CURLM_CALL_MULTI_PERFORM (integer)

CURLM_OK (integer)

CURLM_BAD_HANDLE (integer)

CURLM_BAD_EASY_HANDLE (integer)

CURLM_OUT_OF_MEMORY (integer)

CURLM_INTERNAL_ERROR (integer)

CURLMSG_DONE (integer)


Esempi

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:

Esempio 1. Usare il modulo CURL di PHP per scaricare la homepage di example.com

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Sommario
curl_close -- Chiude una sessione CURL
curl_copy_handle --  Copy a cURL handle along with all of its preferences
curl_errno -- Restituisce il numero dell'ultimo errore
curl_error --  Restituisce una stringa contenente l'ultimo errore relativo alla sessione corrente
curl_exec -- Esegue una sessione CURL
curl_getinfo --  Ottiene informazioni relative a un determinato trasferimento
curl_init -- Inizializza una sessione CURL
curl_multi_add_handle --  Aggiunge un handle cURL ad un multi handle cURL
curl_multi_close --  Chiude un set di handle cURL
curl_multi_exec --  Esegue la sotto-connessione dell'handle cURL corrente
curl_multi_getcontent --  Restituisce il contenuto di un handle cURL se è impostato CURLOPT_RETURNTRANSFER
curl_multi_info_read --  Ottiene informazioni sui trasferimenti correnti
curl_multi_init --  Restituisce un nuovo multi handle cURL
curl_multi_remove_handle --  Rimuove un multi handle da un set di handle cURL
curl_multi_select --  Restituisce tutti i socket associati alla estensione cURL che possono essere "selected"
curl_setopt -- Imposta una opzione per un trasferimento CURL
curl_version -- Restituisce la versione di CURL in uso

curl_close

(PHP 4 >= 4.0.2, PHP 5)

curl_close -- Chiude una sessione CURL

Descrizione

void curl_close ( resource ch )

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

<?php
// crea una risorsa curl
$ch = curl_init();
 
// imposta l'URL e le opzioni appropriate
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
 
// scarica l'URL e lo passa al browser
curl_exec($ch);
 
// chiude la risorsa curl
curl_close($ch);
?>

Vedere anche: curl_init().

curl_copy_handle

(PHP 5)

curl_copy_handle --  Copy a cURL handle along with all of its preferences

Description

resource curl_copy_handle ( resource ch )

This function copies a cURL handle, returning a new cURL handle with the same preferences.

Esempio 1. Copying a cURL handle.

<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// copy the handle
$ch2 = curl_copy_handle($ch);

// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);

// close curl resources, and free up system resources
curl_close($ch2);
curl_close($ch);
?>

curl_errno

(PHP 4 >= 4.0.3, PHP 5)

curl_errno -- Restituisce il numero dell'ultimo errore

Descrizione

int curl_errno ( resource ch )

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.

curl_error

(PHP 4 >= 4.0.3, PHP 5)

curl_error --  Restituisce una stringa contenente l'ultimo errore relativo alla sessione corrente

Descrizione

string curl_error ( resource ch )

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

curl_exec

(PHP 4 >= 4.0.2, PHP 5)

curl_exec -- Esegue una sessione CURL

Descrizione

mixed curl_exec ( resource ch )

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.

<?php
// Crea la risorsa CURL
$ch = curl_init();
 
// Imposta l'URL e altre opzioni
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
 
// Scarica l'URL e lo passa al browser
curl_exec($ch);
 
// Chiude la risorsa curl
curl_close($ch);
?>

Nota: Se si desidera avere restituito il risultato anzichè averlo visualizzato direttamente sul browser, utilizzare l'opzione CURLOPT_RETURNTRANSFER di curl_setopt().

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5)

curl_getinfo --  Ottiene informazioni relative a un determinato trasferimento

Descrizione

string curl_getinfo ( resource ch [, int opt] )

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

(PHP 4 >= 4.0.2, PHP 5)

curl_init -- Inizializza una sessione CURL

Descrizione

resource curl_init ( [string url] )

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

<?php
// crea una nuova risorsa curl
$ch = curl_init();
// imposta l'URL ed altre opzioni
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// scarica l'URL e lo passa al browser
curl_exec($ch);
// chiude la risorsa curl e rilascia le risorse di sistema
curl_close($ch);
?>

Vedere anche: curl_close() e curl_setopt().

curl_multi_add_handle

(PHP 5)

curl_multi_add_handle --  Aggiunge un handle cURL ad un multi handle cURL

Descrizione

int curl_multi_add_handle ( resource mh, resource ch )

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

curl_multi_close

(PHP 5)

curl_multi_close --  Chiude un set di handle cURL

Descrizione

void curl_multi_close ( resource mh )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche curl_multi_init() e curl_close().

curl_multi_exec

(PHP 5)

curl_multi_exec --  Esegue la sotto-connessione dell'handle cURL corrente

Descrizione

int curl_multi_exec ( resource mh, int &still_running )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche curl_multi_init() e curl_exec().

curl_multi_getcontent

(PHP 5)

curl_multi_getcontent --  Restituisce il contenuto di un handle cURL se è impostato CURLOPT_RETURNTRANSFER

Descrizione

string curl_multi_getcontent ( resource ch )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche curl_multi_init().

curl_multi_info_read

(PHP 5)

curl_multi_info_read --  Ottiene informazioni sui trasferimenti correnti

Descrizione

array curl_multi_info_read ( resource mh )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche curl_multi_init().

curl_multi_init

(PHP 5)

curl_multi_init --  Restituisce un nuovo multi handle cURL

Descrizione

resource curl_multi_init ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche curl_init() e curl_multi_close().

curl_multi_remove_handle

(PHP 5)

curl_multi_remove_handle --  Rimuove un multi handle da un set di handle cURL

Descrizione

int curl_multi_remove_handle ( resource mh, resource ch )

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

curl_multi_select

(PHP 5)

curl_multi_select --  Restituisce tutti i socket associati alla estensione cURL che possono essere "selected"

Descrizione

int curl_multi_select ( resource mh [, float timeout] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche curl_multi_init().

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt -- Imposta una opzione per un trasferimento CURL

Descrizione

bool curl_setopt ( resource ch, int option, mixed valore )

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

OptionSet value toNotes
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.

Nota: PHP automaticamente imposta questa opzione a TRUE dovrebbe essere cambiata solo per operazioni di debug.

 
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 :

OptionSet value toNotes
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 :

OptionSet value toNotes
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.

Nota: Non fare ciò senza essere sicuri che innanzitutto il vostro server supporti il metodo di richiesta custom.

 
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.

Nota: Siccome questa opzione contiene una password di tipo sensitive, bisogna ricordarsi di mantenere lo script PHP, in cui è contenuto, sicuro.

 
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 :

OptionSet value toNotes
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 :

OptionSet value toNotes
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 :

OptionSet value toNotes
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

<?php
  	// crea una nuova risorsa CURL 
  	$ch = curl_init();
  	 
  	// imposta l'URL e altre opzioni spedifiche
  	curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
  	curl_setopt($ch, CURLOPT_HEADER, false);
  	 
  	// carica l' URL e la passa al browser
  	curl_exec($ch);
  	 
  	// chiude la risorsa CURL e rilascia le risorse di sistema
  	curl_close($ch);
  	?>

curl_version

(PHP 4 >= 4.0.2, PHP 5)

curl_version -- Restituisce la versione di CURL in uso

Descrizione

string curl_version ( [int version] )

La funzione curl_version() restituisce una stringa contenente la versione di CURL attualmente in uso.

XIX. Funzioni di pagamento Cybercash

Installazione

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.

Sommario
cybercash_base64_decode -- Decodifica dei dati in base64 per Cybercash
cybercash_base64_encode -- Codifica dei dati in base64 per Cybercash
cybercash_decr -- Decrifrazione Cybercash
cybercash_encr -- Criptazione Cybercash

cybercash_base64_decode

(PHP 4 <= 4.2.3, PECL)

cybercash_base64_decode -- Decodifica dei dati in base64 per Cybercash

Descrizione

string cybercash_base64_decode ( string inbuff )

cybercash_base64_encode

(PHP 4 <= 4.2.3, PECL)

cybercash_base64_encode -- Codifica dei dati in base64 per Cybercash

Descrizione

string cybercash_base64_encode ( string inbuff )

cybercash_decr

(PHP 4 <= 4.2.3, PECL)

cybercash_decr -- Decrifrazione Cybercash

Descrizione

array cybercash_decr ( string wmk, string sk, string inbuff )

La funzione restituisce un array associativo con gli elementi "errcode" e, se "errcode" è FALSE, "outbuff" (stringa), "outLth" (long) and "macbuff" (stringa).

cybercash_encr

(PHP 4 <= 4.2.3, PECL)

cybercash_encr -- Criptazione Cybercash

Descrizione

array cybercash_encr ( string wmk, string sk, string inbuff )

La funzione restituisce un array associativo con gli elementi "errcode" e, se "errcode" è FALSE, "outbuff" (stringa), "outLth" (long) and "macbuff" (stringa).

XX. Crédit Mutuel CyberMUT functions

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.

Sommario
cybermut_creerformulairecm -- Genera un form HTML per la richiesta di pagamento
cybermut_creerreponsecm --  Genera la conferma della consegna della conferma di pagamento
cybermut_testmac --  Assicura che non siano contenuti dati manipolati nel messaggio di conferma ricevuto

cybermut_creerformulairecm

(4.0.5 - 4.2.3 only, PECL)

cybermut_creerformulairecm -- Genera un form HTML per la richiesta di pagamento

Descrizione

string cybermut_creerformulairecm ( string url_CM, string version, string TPE, string montant, string ref_commande, string texte_libre, string url_retour, string url_retour_ok, string url_retour_err, string langue, string code_societe, string texte_bouton )

cybermut_creerformulairecm() è usato per generare il form HTML per la richiesta di pagamento.

Esempio 1. Primo passo di pagamento (equiv cgi1.c)

<?php
// Directory dove si trovano le chiavi
putenv("CMKEYDIR=/var/creditmut/cles");
 
// Numero Versione
$VERSION="1.2";

  $retour =  cybermut_creerformulairecm(
  "https://www.creditmutuel.fr/test/telepaiement/paiement.cgi",
  $VERSION,
  "1234567890",
  "300FRF",
  $REFERENCE,
  $TEXTE_LIBRE,
  $URL_RETOUR,
  $URL_RETOUR_OK,
  $URL_RETOUR_ERR,
  "francais",
  "company",
  "Paiement par carte bancaire");
 
  echo $retour;                                                               
?>

Vedere anche cybermut_testmac() e cybermut_creerreponsecm().

cybermut_creerreponsecm

(4.0.5 - 4.2.3 only, PECL)

cybermut_creerreponsecm --  Genera la conferma della consegna della conferma di pagamento

Descrizione

string cybermut_creerreponsecm ( string phrase )

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

cybermut_testmac

(4.0.5 - 4.2.3 only, PECL)

cybermut_testmac --  Assicura che non siano contenuti dati manipolati nel messaggio di conferma ricevuto

Descrizione

bool cybermut_testmac ( string code_MAC, string version, string TPE, string cdate, string montant, string ref_commande, string texte_libre, string code-retour )

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

<?php
// Make sure that Enable Track Vars is ON.
// Directory where are located the keys
putenv("CMKEYDIR=/var/creditmut/cles");
 
// Version number
$VERSION="1.2";

$texte_libre = $HTTP_GET_VARS["texte-libre"];
$code_retour = $HTTP_GET_VARS["code-retour"];                                     

$mac_ok = cybermut_testmac($MAC,$VERSION,$TPE,$date,$montant,$reference,$texte_libre,$code_retour);

if ($mac_ok) {

  //
  // insert data processing here
  //
  //

  $result=cybermut_creerreponsecm("OK");
} else {
  $result=cybermut_creerreponsecm("Document Falsifie");
}
 
?>

Vedere anche cybermut_creerformulairecm() e cybermut_creerreponsecm().

XXI. Funzioni di amministrazione Cyrus IMAP

Introduzione

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: Questo modulo non è disponibile su piattaforme Windows.


Installazione

Questo modulo è disponibile soltanto se PHP è stato configurato con l'opzione --with-cyrus .


Costanti predefinite

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.

CYRUS_CONN_NONSYNCLITERAL (integer)

CYRUS_CONN_INITIALRESPONSE (integer)

CYRUS_CALLBACK_NUMBERED (integer)

CYRUS_CALLBACK_NOLITERAL (integer)

Sommario
cyrus_authenticate -- Autentifica attraverso un server Cyrus IMAP
cyrus_bind -- Bind callbacks ad una connessione Cyrus IMAP
cyrus_close --  Chiude la connessione con un server Cyrus IMAP
cyrus_connect -- Apre una connessione con un server Cyrus IMAP
cyrus_query -- Invia una query ad un server Cyrus IMAP
cyrus_unbind -- Unbind ...

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL)

cyrus_authenticate -- Autentifica attraverso un server Cyrus IMAP

Descrizione

bool cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf]]]]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cyrus_bind

(PHP 4 >= 4.1.0, PECL)

cyrus_bind -- Bind callbacks ad una connessione Cyrus IMAP

Description

bool cyrus_bind ( resource connection, array callbacks )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cyrus_close

(PHP 4 >= 4.1.0, PECL)

cyrus_close --  Chiude la connessione con un server Cyrus IMAP

Descrizione

bool cyrus_close ( resource connection )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cyrus_connect

(PHP 4 >= 4.1.0, PECL)

cyrus_connect -- Apre una connessione con un server Cyrus IMAP

Descrizione

resource cyrus_connect ( [string host [, string port [, int flags]]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cyrus_query

(PHP 4 >= 4.1.0, PECL)

cyrus_query -- Invia una query ad un server Cyrus IMAP

Descrizione

bool cyrus_query ( resource connection, string query )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

cyrus_unbind

(PHP 4 >= 4.1.0, PECL)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

XXII. Funzioni di Data e Ora

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
checkdate -- Verifica una data/orario gragoriana/o
date_default_timezone_get --  Gets the default timezone used by all date/time functions in a script
date_default_timezone_set --  Sets the default timezone used by all date/time functions in a script
date_sunrise --  Returns time of sunrise for a given day and location
date_sunset --  Returns time of sunset for a given day and location
date -- Formatta una data o orario locale
getdate -- Riceve informazioni su data/orario
gettimeofday -- Riceve l'orario attuale
gmdate -- Formatta una data/ora GMT/UTC
gmmktime -- Riceve l'UNIX timestamp per una data GMT
gmstrftime --  Formatta una data/ora GMT/UTC secondo i parametri locali
idate -- Format a local time/date as integer
localtime -- Riceve l'orario locale
microtime --  Restituisce l'attuale UNIX timestamp con i microsecondi
mktime -- Restituisce la UNIX timestamp per una data
strftime --  Formatta una data/orario locale accordandola/o alle impostazioni locali according to locale settings
strptime --  Parse a time/date generated with strftime()
strtotime --  Analizza le descrizioni testuali di datetime in Inglese nell'UNIX timestamp
time -- Restituisce l'attuale UNIX timestamp

checkdate

(PHP 3, PHP 4, PHP 5)

checkdate -- Verifica una data/orario gragoriana/o

Descrizione

bool checkdate ( int mese, int giorno, int anno )

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

date_default_timezone_get

(PHP 5 >= 5.1.0RC1)

date_default_timezone_get --  Gets the default timezone used by all date/time functions in a script

Descrizione

string date_default_timezone_get ( void )

This 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

Valori restituiti

Returns a string.

date_default_timezone_set

(PHP 5 >= 5.1.0RC1)

date_default_timezone_set --  Sets the default timezone used by all date/time functions in a script

Descrizione

bool date_default_timezone_set ( string timezone_identifier )

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

Elenco dei parametri

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendice H.

Valori restituiti

This function always returns TRUE (even if the timezone_identifier isn't valid).

date_sunrise

(PHP 5)

date_sunrise --  Returns time of sunrise for a given day and location

Description

mixed date_sunrise ( int timestamp [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]] )

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

constantdescriptionexample
SUNFUNCS_RET_STRINGreturns the result as string16:46
SUNFUNCS_RET_DOUBLEreturns the result as float16.78243132
SUNFUNCS_RET_TIMESTAMPreturns the result as integer (timestamp)1095034606

Esempio 1. date_sunrise() example

<?php

/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

Il precedente esempio visualizzerà qualcosa simile a:

Mon Dec 20 2004, sunrise time : 08:54

See also date_sunset().

date_sunset

(PHP 5)

date_sunset --  Returns time of sunset for a given day and location

Description

mixed date_sunset ( int timestamp [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]] )

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

constantdescriptionexample
SUNFUNCS_RET_STRINGreturns the result as string16:46
SUNFUNCS_RET_DOUBLEreturns the result as float16.78243132
SUNFUNCS_RET_TIMESTAMPreturns the result as integer (timestamp)1095034606

Esempio 1. date_sunset() example

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

Il precedente esempio visualizzerà qualcosa simile a:

Mon Dec 20 2004, sunset time : 18:13

See also date_sunrise().

date

(PHP 3, PHP 4, PHP 5)

date -- Formatta una data o orario locale

Descrizione

string date ( string formato [, int timestamp] )

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.

Caratteri non utilizzati nella stringa del formato saranno scritti come sono. Il formato "Z" restituirà sempre "0" quando si usa gmdate().

Esempio 1. Esempio di date()

echo date ("l dS of F Y h:i:s A");
echo "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));

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.

Esempio 2. Caratteri di escape in date()

echo date("l \\t\h\e jS"); // scrive qualcosa tipo 'Saturday the 8th'

È possibile usare date() e mktime() assieme per cercare delle date nel futuro o nel passato.

Esempio 3. Esempio di date() e mktime()

$tomorrow  = mktime (0,0,0,date("m")  ,date("d")+1,date("Y"));
$lastmonth = mktime (0,0,0,date("m")-1,date("d"),  date("Y"));
$nextyear  = mktime (0,0,0,date("m"),  date("d"),  date("Y")+1);

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

/* Today is March 10th, 2001, 5:16:18 pm */
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17

Per formattare le date in lingue diverse dall'inglese, dovresti usare le funzioni setlocale() e strftime().

Guarda anche getlastmod(), gmdate(), mktime(), strftime() e time().

getdate

(PHP 3, PHP 4, PHP 5)

getdate -- Riceve informazioni su data/orario

Descrizione

array getdate ( [int timestamp] )

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"

Esempio 1. Esempio di getdate()

$today = getdate(); 
$month = $today['month']; 
$mday = $today['mday']; 
$year = $today['year']; 
echo "$month $mday, $year";

gettimeofday

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

gettimeofday -- Riceve l'orario attuale

Descrizione

array gettimeofday ( void )

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

gmdate

(PHP 3, PHP 4, PHP 5)

gmdate -- Formatta una data/ora GMT/UTC

Descrizione

string gmdate ( string formato [, int timestamp] )

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

Esempio 1. Esempio di gmdate()

echo date ("M d Y H:i:s", mktime (0,0,0,1,1,1998));
echo gmdate ("M d Y H:i:s", mktime (0,0,0,1,1,1998));

Guarda anche date(), mktime(), gmmktime() e strftime().

gmmktime

(PHP 3, PHP 4, PHP 5)

gmmktime -- Riceve l'UNIX timestamp per una data GMT

Descrizione

int gmmktime ( int ora, int minuto, int secondo, int mese, int giorno, int anno [, int is_dst] )

Identica alla funzione mktime() eccetto per il paramentro passato, che rappresenta una data GMT.

gmstrftime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

gmstrftime --  Formatta una data/ora GMT/UTC secondo i parametri locali

Descrizione

string gmstrftime ( string formato [, int timestamp] )

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

Esempio 1. Esempio di gmstrftime()

setlocale ('LC_TIME', 'en_US');
echo strftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
echo gmstrftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";

Guarda anche strftime().

idate

(PHP 5)

idate -- Format a local time/date as integer

Description

int idate ( string format [, int timestamp] )

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 characterDescription
BSwatch Beat/Internet Time
dDay of the month
hHour (12 hour format)
HHour (24 hour format)
iMinutes
Ireturns 1 if DST is activated, 0 otherwise
Lreturns 1 for leap year, 0 otherwise
mMonth number
sSeconds
tDays in current month
USeconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time()
wDay of the week (0 on Sunday)
WISO-8601 week number of year, weeks starting on Monday
yYear (1 or 2 digits - check note below)
YYear (4 digits)
zDay of the year
ZTimezone 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:

<?php
$timestamp = strtotime('1st January 2004'); //1072915200

// this prints the year in a two digit format
// however, as this would start with a "0", it
// only prints "4"
echo idate('y', $timestamp);
?>

See also date() and time().

localtime

(PHP 4, PHP 5)

localtime -- Riceve l'orario locale

Descrizione

array localtime ( [int timestamp [, bool is_associative]] )

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

microtime

(PHP 3, PHP 4, PHP 5)

microtime --  Restituisce l'attuale UNIX timestamp con i microsecondi

Descrizione

string microtime ( void )

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

function getmicrotime(){ 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec); 
    } 

$time_start = getmicrotime();
    
for ($i=0; $i < 1000; $i++){
    //do nothing, 1000 times
    }

$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds";

Vedere anche time().

mktime

(PHP 3, PHP 4, PHP 5)

mktime -- Restituisce la UNIX timestamp per una data

Descrizione

int mktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst] )

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

Esempio 1. Esempio di mktime()

echo date ("M-d-Y", mktime (0,0,0,12,32,1997));
echo date ("M-d-Y", mktime (0,0,0,13,1,1997));
echo date ("M-d-Y", mktime (0,0,0,1,1,1998));
echo date ("M-d-Y", mktime (0,0,0,1,1,98));
Year può avere sia 2 che 4 cifre, con valori compresi tra 0-69 e 2000-2069 oppure tra 70-99 e 1970-1999 (sui sistemi dove time_t è un intero segnato a 32bit, come sulla maggior parte dei PC di oggi, l'intervallo valido per year è tra 1902 e 2037).

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

Esempio 2. L'ultimo giorno del mese successivo

$lastday = mktime (0,0,0,3,0,2000);
echo strftime ("L'ultimo giorno di Feb 2000 è: %d", $lastday);
     
$lastday = mktime (0,0,0,4,-31,2000);
echo strftime ("L'ultimo giorno di Feb 2000 è: %d", $lastday);

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

Guarda anche date() e time().

strftime

(PHP 3, PHP 4, PHP 5)

strftime --  Formatta una data/orario locale accordandola/o alle impostazioni locali according to locale settings

Descrizione

string strftime ( string format [, int timestamp] )

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

Esempio 1. Esempio di strftime()

setlocale (LC_TIME, "C");
print (strftime ("%A in Finlandese è "));
setlocale (LC_TIME, "fi_FI");
print (strftime ("%A, in Francese "));
setlocale (LC_TIME, "fr_FR");
print (strftime ("%A e in Italiano "));
setlocale (LC_TIME, "it_IT");
print (strftime ("%A.\n"));
Questo esempio funziona se hai le ripettive impostazioni di lingua installate nel tuo sistema.

Guarda anche setlocale() e mktime() e le specifiche dell' Open Group per strftime().

strptime

(PHP 5 >= 5.1.0RC1)

strptime --  Parse a time/date generated with strftime()

Description

array strptime ( string date, string format )

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

Elenco dei parametri

date (string)

The string to parse (e.g. returned from strftime())

format (string)

The format used in date (e.g. the same as used in strftime()).

For more information about the format options, read the strftime() page.

Valori restituiti

Returns an array, or FALSE on failure.

Tabella 1. The following parameters are returned in the array

parametersDescription
tm_secSeconds after the minute (0-61)
tm_minMinutes after the hour (0-59)
tm_hourHour since midnight (0-23)
tm_mdayDay of the month (1-31)
tm_monMonths since January (0-11)
tm_yearYears since 1900
tm_wdayDays since Sunday (0-6)
tm_ydayDays since January 1 (0-365)
unparsedthe date part which was not recognized using the specified format

Esempi

Esempio 1. strptime() example

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

Il precedente esempio visualizzerà qualcosa simile a:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

Vedere anche:

strftime()

strtotime

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

strtotime --  Analizza le descrizioni testuali di datetime in Inglese nell'UNIX timestamp

Descrizione

int strtotime ( string time [, int now] )

La 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

echo strtotime ("now"), "\n";
echo strtotime ("10 September 2000"), "\n";
echo strtotime ("+1 day"), "\n";
echo strtotime ("+1 week"), "\n";
echo strtotime ("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime ("next Thursday"), "\n";
echo strtotime ("last Monday"), "\n";

Esempio 2. Controllo per il fallimento

$str = 'Not Good';
if (($timestamp = strtotime($str)) === -1) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == ". date('l dS of F Y h:i:s A',$timestamp);
}

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

time

(PHP 3, PHP 4, PHP 5)

time -- Restituisce l'attuale UNIX timestamp

Descrizione

int time ( void )

Restituisce l'attuale data e orario misurata in numero di secondi dalla Unix Epoch (January 1 1970 00:00:00 GMT).

Guarda anche date().

XXIII. DB++ 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.


Introduzione

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.


Requisiti

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


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.


Costanti predefinite

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.


db++ error codes

Tabella 1. DB++ Error Codes

PHP Constantdb++ constantmeaning
DBPLUS_ERR_NOERR (integer) ERR_NOERRNull error condition
DBPLUS_ERR_DUPLICATE (integer) ERR_DUPLICATETried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) ERR_EOSCANEnd of scan from rget()
DBPLUS_ERR_EMPTY (integer) ERR_EMPTYRelation is empty (server)
DBPLUS_ERR_CLOSE (integer) ERR_CLOSEThe server can't close
DBPLUS_ERR_WLOCKED (integer) ERR_WLOCKEDThe record is write locked
DBPLUS_ERR_LOCKED (integer) ERR_LOCKEDRelation was already locked
DBPLUS_ERR_NOLOCK (integer) ERR_NOLOCKRelation cannot be locked
DBPLUS_ERR_READ (integer) ERR_READRead error on relation
DBPLUS_ERR_WRITE (integer) ERR_WRITEWrite error on relation
DBPLUS_ERR_CREATE (integer) ERR_CREATECreate() system call failed
DBPLUS_ERR_LSEEK (integer) ERR_LSEEKLseek() system call failed
DBPLUS_ERR_LENGTH (integer) ERR_LENGTHTuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) ERR_OPENOpen() system call failed
DBPLUS_ERR_WOPEN (integer) ERR_WOPENRelation already opened for writing
DBPLUS_ERR_MAGIC (integer) ERR_MAGICFile is not a relation
DBPLUS_ERR_VERSION (integer) ERR_VERSIONFile is a very old relation
DBPLUS_ERR_PGSIZE (integer) ERR_PGSIZERelation uses a different page size
DBPLUS_ERR_CRC (integer) ERR_CRCInvalid crc in the superpage
DBPLUS_ERR_PIPE (integer) ERR_PIPEPiped relation requires lseek()
DBPLUS_ERR_NIDX (integer) ERR_NIDXToo many secondary indices
DBPLUS_ERR_MALLOC (integer) ERR_MALLOCMalloc() call failed
DBPLUS_ERR_NUSERS (integer) ERR_NUSERSError use of max users
DBPLUS_ERR_PREEXIT (integer) ERR_PREEXITCaused by invalid usage
DBPLUS_ERR_ONTRAP (integer) ERR_ONTRAPCaused by a signal
DBPLUS_ERR_PREPROC (integer) ERR_PREPROCError in the preprocessor
DBPLUS_ERR_DBPARSE (integer) ERR_DBPARSEError in the parser
DBPLUS_ERR_DBRUNERR (integer) ERR_DBRUNERRRun error in db
DBPLUS_ERR_DBPREEXIT (integer) ERR_DBPREEXITExit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) ERR_WAITWait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) ERR_CORRUPT_TUPLEA 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_FIFOCan't create a fifo
DBPLUS_ERR_PERM (integer) ERR_PERMPermission denied
DBPLUS_ERR_TCL (integer) ERR_TCLTCL_error
DBPLUS_ERR_RESTRICTED (integer) ERR_RESTRICTEDOnly 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 

Sommario
dbplus_add -- Add a tuple to a relation
dbplus_aql -- Perform AQL query
dbplus_chdir -- Get/Set database virtual current directory
dbplus_close -- Close a relation
dbplus_curr -- Get current tuple from relation
dbplus_errcode --  Get error string for given errorcode or last error
dbplus_errno -- Get error code for last operation
dbplus_find -- Set a constraint on a relation
dbplus_first -- Get first tuple from relation
dbplus_flush -- Flush all changes made on a relation
dbplus_freealllocks -- Free all locks held by this client
dbplus_freelock -- Release write lock on tuple
dbplus_freerlocks -- Free all tuple locks on given relation
dbplus_getlock -- Get a write lock on a tuple
dbplus_getunique -- Get an id number unique to a relation
dbplus_info -- Get information about a relation
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation
dbplus_next -- Get next tuple from relation
dbplus_open -- Open relation file
dbplus_prev -- Get previous tuple from relation
dbplus_rchperm -- Change relation permissions
dbplus_rcreate -- Creates a new DB++ relation
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_resolve -- Resolve host information for relation
dbplus_restorepos -- Restore position
dbplus_rkeys -- Specify new primary key for a relation
dbplus_ropen -- Open relation file local
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex --  Create a new secondary index for a relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation
dbplus_savepos -- Save position
dbplus_setindex -- Set index
dbplus_setindexbynumber -- Set index by number
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- Undo
dbplus_undoprepare -- Prepare undo
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation
dbplus_update -- Update specified tuple in relation
dbplus_xlockrel -- Request exclusive lock on relation
dbplus_xunlockrel -- Free exclusive lock on relation

dbplus_add

(4.1.0 - 4.2.3 only, PECL)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_aql

(4.1.0 - 4.2.3 only, PECL)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_chdir

(4.1.0 - 4.2.3 only, PECL)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_close

(4.1.0 - 4.2.3 only, PECL)

dbplus_close -- Close a relation

Description

mixed dbplus_close ( resource 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.

Calling dbplus_close() will close a relation previously opened by dbplus_open().

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

dbplus_curr

(4.1.0 - 4.2.3 only, PECL)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array &tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_errcode

(4.1.0 - 4.2.3 only, PECL)

dbplus_errcode --  Get error string for given errorcode or last error

Description

string dbplus_errcode ( [int 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_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

dbplus_errno

(4.1.0 - 4.2.3 only, PECL)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_find

(4.1.0 - 4.2.3 only, PECL)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_first

(4.1.0 - 4.2.3 only, PECL)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array &tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_flush

(4.1.0 - 4.2.3 only, PECL)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource 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_flush() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

dbplus_freealllocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_freelock

(4.1.0 - 4.2.3 only, PECL)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_freerlocks

(4.1.0 - 4.2.3 only, PECL)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource 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_freerlocks() will free all tuple locks held on the given relation.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().

dbplus_getlock

(4.1.0 - 4.2.3 only, PECL)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_getunique

(4.1.0 - 4.2.3 only, PECL)

dbplus_getunique -- Get an id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_info

(4.1.0 - 4.2.3 only, PECL)

dbplus_info -- Get information about a relation

Description

int dbplus_info ( resource relation, string key, array &result )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_last

(4.1.0 - 4.2.3 only, PECL)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array &tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource 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_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

dbplus_next

(4.1.0 - 4.2.3 only, PECL)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array &tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_open

(4.1.0 - 4.2.3 only, PECL)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string 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.

The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

dbplus_prev

(4.1.0 - 4.2.3 only, PECL)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array &tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_rchperm

(4.1.0 - 4.2.3 only, PECL)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_rcreate

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, bool overwrite] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_rcrtexact

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

mixed dbplus_rcrtexact ( string name, resource relation [, bool overwrite] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_rcrtlike

(4.1.0 - 4.2.3 only, PECL)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

mixed dbplus_rcrtlike ( string name, resource relation [, int overwrite] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_resolve

(4.1.0 - 4.2.3 only, PECL)

dbplus_resolve -- Resolve host information for relation

Description

array dbplus_resolve ( string relation_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_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

dbplus_restorepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_restorepos -- Restore position

Description

int dbplus_restorepos ( resource relation, array tuple )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_rkeys

(4.1.0 - 4.2.3 only, PECL)

dbplus_rkeys -- Specify new primary key for a relation

Description

mixed dbplus_rkeys ( resource relation, mixed domlist )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_ropen

(4.1.0 - 4.2.3 only, PECL)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string 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_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.

dbplus_rquery

(4.1.0 - 4.2.3 only, PECL)

dbplus_rquery -- Perform local (raw) AQL query

Description

resource dbplus_rquery ( string query [, string dbpath] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_rrename

(4.1.0 - 4.2.3 only, PECL)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string 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_rrename() will change the name of relation to name.

dbplus_rsecindex

(4.1.0 - 4.2.3 only, PECL)

dbplus_rsecindex --  Create a new secondary index for a relation

Description

mixed dbplus_rsecindex ( resource relation, mixed domlist, int type )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_runlink

(4.1.0 - 4.2.3 only, PECL)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource 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_unlink() will close and remove the relation.

dbplus_rzap

(4.1.0 - 4.2.3 only, PECL)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource 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.

dbplus_savepos

(4.1.0 - 4.2.3 only, PECL)

dbplus_savepos -- Save position

Description

int dbplus_savepos ( resource 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.

dbplus_setindex

(4.1.0 - 4.2.3 only, PECL)

dbplus_setindex -- Set index

Description

int dbplus_setindex ( resource relation, string idx_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

dbplus_setindexbynumber

(4.1.0 - 4.2.3 only, PECL)

dbplus_setindexbynumber -- Set index by number

Description

int dbplus_setindexbynumber ( resource relation, int idx_number )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_sql

(4.1.0 - 4.2.3 only, PECL)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query [, string server [, string dbpath]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_tcl

(4.1.0 - 4.2.3 only, PECL)

dbplus_tcl -- Execute TCL code on server side

Description

string dbplus_tcl ( int sid, string script )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_tremove

(4.1.0 - 4.2.3 only, PECL)

dbplus_tremove -- Remove tuple and return new current tuple

Description

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

dbplus_undo

(4.1.0 - 4.2.3 only, PECL)

dbplus_undo -- Undo

Description

int dbplus_undo ( resource 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.

dbplus_undoprepare

(4.1.0 - 4.2.3 only, PECL)

dbplus_undoprepare -- Prepare undo

Description

int dbplus_undoprepare ( resource 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.

dbplus_unlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource 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_unlockrel() will release a write lock previously obtained by dbplus_lockrel().

dbplus_unselect

(4.1.0 - 4.2.3 only, PECL)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource 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.

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

dbplus_update

(4.1.0 - 4.2.3 only, PECL)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_xlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource 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().

dbplus_xunlockrel

(4.1.0 - 4.2.3 only, PECL)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource 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_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

XXIV. Database (dbm-style) Abstraction Layer Functions

Introduzione

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


Requisiti

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

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


Installazione

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

HandlerConfigure Switch
dbm To enable support for dbm add --with-dbm[=DIR].

Nota: dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm To enable support for ndbm add --with-ndbm[=DIR].

Nota: ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm To enable support for gdbm add --with-gdbm[=DIR].
db2 To enable support for db2 add --with-db2[=DIR].

Nota: db2 conflicts with db3 and db4.

db3 To enable support for db3 add --with-db3[=DIR].

Nota: db3 conflicts with db2 and db4.

db4 To enable support for db4 add --with-db4[=DIR].

Nota: db4 conflicts with db2 and db3.

Nota: This was added in PHP 4.3.2. In earlier versions of PHP you need to use --with-db3=DIR with DIR being the path to db4 library. It is not possible to use db versions starting from 4.1 with PHP prior to version 4.3.0. Also, the db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version.

cdb To enable support for cdb add --with-cdb[=DIR].

Nota: Since PHP 4.3.0 you can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.

flatfile To enable support for flatfile add --with-flatfile.

Nota: This was added in PHP 4.3.0 to add compatibility with deprecated dbm extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.

inifile To enable support for inifile add --with-inifile.

Nota: This was added in PHP 5.0.0 and allows to read and set microsoft style .ini files (like the php.ini file).

qdbm To enable support for qdbm add --with-qdbm[=DIR].

Nota: qdbm conflicts with dbm and gdbm.

Nota: This was added in PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net.

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

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.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Esempio 1. DBA example

<?php

$id = dba_open("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
    echo dba_fetch("key", $id);
    dba_delete("key", $id);
}

dba_close($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Esempio 2. Traversing a database

<?php

// ...open database...

$key = dba_firstkey($id);

while ($key != false) {
    if (true) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey($id);
}

foreach ($handle_later as $val) {
    dba_delete($val, $id);
}

?>

Sommario
dba_close -- Close a DBA database
dba_delete -- Delete DBA entry specified by key
dba_exists -- Check whether key exists
dba_fetch -- Fetch data specified by key
dba_firstkey -- Fetch first key
dba_handlers -- List all the handlers available
dba_insert -- Insert entry
dba_key_split --  Splits a key in string representation into array representation
dba_list -- List all open database files
dba_nextkey -- Fetch next key
dba_open -- Open database
dba_optimize -- Optimize database
dba_popen -- Open database persistently
dba_replace -- Replace or insert entry
dba_sync -- Synchronize database

dba_close

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

dba_close -- Close a DBA database

Descrizione

void dba_close ( resource handle )

dba_close() closes the established database and frees all resources of the specified database handle.

Elenco dei parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

No value is returned.

Vedere anche:

dba_open()
dba_popen()

dba_delete

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

dba_delete -- Delete DBA entry specified by key

Descrizione

bool dba_delete ( string key, resource handle )

dba_delete() deletes the specified entry from the database.

Elenco dei parametri

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

dba_exists

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

dba_exists -- Check whether key exists

Descrizione

bool dba_exists ( string key, resource handle )

dba_exists() checks whether the specified key exists in the database.

Elenco dei parametri

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Returns TRUE if the key exists, FALSE otherwise.

dba_fetch

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

dba_fetch -- Fetch data specified by key

Descrizione

string dba_fetch ( string key, resource handle )

string dba_fetch ( string key, int skip, resource handle )

dba_fetch() fetches the data specified by key from the database specified with handle.

Elenco dei parametri

key

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

skip

The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Returns the associated string if the key/data pair is found, FALSE otherwise.

Log delle modifiche

VersioneDescrizione
4.3 The skip parameter is available to support cdb's capability of multiple keys having the same name.

dba_firstkey

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

dba_firstkey -- Fetch first key

Descrizione

string dba_firstkey ( resource handle )

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

Elenco dei parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Returns the key on success, or FALSE on failure.

Vedere anche:

dba_nextkey()
dba_key_split()
Example 2 in the DBA examples

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers -- List all the handlers available

Descrizione

array dba_handlers ( [bool full_info] )

dba_handlers() list all the handlers supported by this extension.

Elenco dei parametri

full_info

Turns on/off full information display in the result. The default is FALSE.

Valori restituiti

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.

Esempi

Esempio 1. dba_handlers() Example

<?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
  // clean the versions
  $handler_version = str_replace('$', '', $handler_version);
  echo " - $handler_name: $handler_version\n";
}

?>

Il precedente esempio visualizzerà qualcosa simile a:

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3 
 - cdb_make: 0.75, Revision: 1.2.2.4 
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3 
 - flatfile: 1.0, Revision: 1.5.2.4

dba_insert

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

dba_insert -- Insert entry

Descrizione

bool dba_insert ( string key, string value, resource handle )

dba_insert() inserts the entry described with key and value into the database.

Elenco dei parametri

key

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.

value

The value to be inserted.

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

dba_key_split

(PHP 5)

dba_key_split --  Splits a key in string representation into array representation

Descrizione

mixed dba_key_split ( mixed key )

dba_key_split() splits a key (string representation) into an array representation.

Elenco dei parametri

key

The key in string representation.

Valori restituiti

Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.

dba_list

(PHP 4 >= 4.3.0, PHP 5)

dba_list -- List all open database files

Descrizione

array dba_list ( void )

dba_list() list all open database files.

Valori restituiti

An associative array, in the form resourceid => filename.

dba_nextkey

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

dba_nextkey -- Fetch next key

Descrizione

string dba_nextkey ( resource handle )

dba_nextkey() returns the next key of the database and advances the internal key pointer.

Elenco dei parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Returns the key on success, or FALSE on failure.

Vedere anche:

dba_firstkey()
dba_key_split()
Example 2 in the DBA examples

dba_open

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

dba_open -- Open database

Descrizione

resource dba_open ( string path, string mode [, string handler [, mixed ...]] )

dba_open() establishes a database instance for path with mode using handler.

Elenco dei parametri

path

Commonly a regular path in your filesystem.

mode

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 openmode = "rl"mode = "rlt"mode = "wl"mode = "wlt"mode = "rd"mode = "rdt"mode = "wd"mode = "wdt"
not openokokokokokokokok
mode = "rl"okokwaitfalseillegalillegalillegalillegal
mode = "wl"waitfalsewaitfalseillegalillegalillegalillegal
mode = "rd"illegalillegalillegalillegalokokwaitfalse
mode = "wd"illegalillegalillegalillegalwaitfalsewaitfalse

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.

handler

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.

Valori restituiti

Returns a positive handle on success, or FALSE on failure.

Log delle modifiche

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

Vedere anche:

dba_popen()
dba_close()

dba_optimize

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

dba_optimize -- Optimize database

Descrizione

bool dba_optimize ( resource handle )

dba_optimize() optimizes the underlying database.

Elenco dei parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

dba_sync()

dba_popen

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

dba_popen -- Open database persistently

Descrizione

resource dba_popen ( string path, string mode [, string handler [, mixed ...]] )

dba_popen() establishes a persistent database instance for path with mode using handler.

Elenco dei parametri

path

Commonly a regular path in your filesystem.

mode

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.

handler

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.

Valori restituiti

Returns a positive handle on success, or FALSE on failure.

Vedere anche:

dba_open()
dba_close()

dba_replace

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

dba_replace -- Replace or insert entry

Descrizione

bool dba_replace ( string key, string value, resource handle )

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

Elenco dei parametri

key

The key of the entry to be replaced.

value

The value to be replaced.

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

dba_sync

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

dba_sync -- Synchronize database

Descrizione

bool dba_sync ( resource handle )

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

Elenco dei parametri

handle

The database handler, returned by dba_open() or dba_popen().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

dba_optimize()

XXV. Funzioni dBase

Introduzione

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.


Installazione

Allo scopo di abilitare le librerie dbase fornite e di usare queste funzioni, si deve compilare PHP con l'opzione --enable-dbase .


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
dbase_add_record -- Aggiunge un record ad un database dBase
dbase_close -- Chiude un database dBase
dbase_create -- Crea un database dBase
dbase_delete_record -- Cancella un record da un database dBase
dbase_get_header_info -- Ottenere le informazioni di intestazione di un database dBase
dbase_get_record_with_names --  Estrae un record da un database dBase come un array associativo
dbase_get_record -- Estrae un record da un database dBase
dbase_numfields --  Restituisce il numero di campi in un database dBase.
dbase_numrecords --  Restituisce il numero di records in un database dBase.
dbase_open -- Apre un database dBase
dbase_pack -- Stabilizza un database dBase
dbase_replace_record -- Sostituisce un record in un database dBase

dbase_add_record

(PHP 3, PHP 4, PHP 5)

dbase_add_record -- Aggiunge un record ad un database dBase

Descrizione

bool dbase_add_record ( int dbase_identifier, array record )

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.

dbase_close

(PHP 3, PHP 4, PHP 5)

dbase_close -- Chiude un database dBase

Descrizione

bool dbase_close ( int dbase_identifier )

Chiude il database associato con il dbase_identifier.

dbase_create

(PHP 3, PHP 4, PHP 5)

dbase_create -- Crea un database dBase

Descrizione

int dbase_create ( string filename, array fields )

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:

L

Boolean. Questi non hanno una lunghezza o una precisione.

M

Memo. (Nota che non sono supportati da PHP.) Questi non hanno una lunghezza o una precisione.

D

Date (memorizzate nel formato YYYYMMDD). Questi non hanno una lunghezza o una precisione.

N

Number. Questi hanno sia una lunghezza sia una precisione (il numero di decimali).

C

String.

Se il database è creato con successo, viene restituito un dbase_identifier, altrimenti viene restituito FALSE.

Esempio 1. Creare un file di database dBase

<?php

// "database" name
$dbname = "/tmp/test.dbf";

// database "definition"
$def =
    array(
        array("date",     "D"),
        array("name",     "C",  50),
        array("age",      "N",   3, 0),
        array("email",    "C", 128),
        array("ismember", "L")
    );

// creation
if (!dbase_create($dbname, $def))
    echo "<strong>Error!</strong>";
	
	?>

dbase_delete_record

(PHP 3, PHP 4, PHP 5)

dbase_delete_record -- Cancella un record da un database dBase

Descrizione

bool dbase_delete_record ( int dbase_identifier, int record )

Marca il record da cancellare dal database. Per rimuovere il record dal database, è necessario chiamare la funzione dbase_pack().

dbase_get_header_info

(PHP 5)

dbase_get_header_info -- Ottenere le informazioni di intestazione di un database dBase

Descrizione

array dbase_get_header_info ( int dbase_identifier )

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:

nome

Il nome della colonna

tipo

Il nome del tipo di colonna del dBase riconoscibile dall'utente (es. data, boolean, etc)

lunghezza

Il numero di bytes che la colonna può contenere

precisione

Il numero di cifre della precisione decimale della colonna

formato

Un formato di printf() suggerito, specifico per la colonna

offset (scostamento)

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
// Path to dbase file
$db_path = "/tmp/test.dbf";

// Open dbase file
$dbh = dbase_open($db_path)
    or die("Errore! Il file di database dBase non può essere aperto '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

// Display information
print_r($column_info);
?>

dbase_get_record_with_names

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

dbase_get_record_with_names --  Estrae un record da un database dBase come un array associativo

Descrizione

array dbase_get_record_with_names ( int dbase_identifier, int record )

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

dbase_get_record

(PHP 3, PHP 4, PHP 5)

dbase_get_record -- Estrae un record da un database dBase

Descrizione

array dbase_get_record ( int dbase_identifier, int record )

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.

dbase_numfields

(PHP 3, PHP 4, PHP 5)

dbase_numfields --  Restituisce il numero di campi in un database dBase.

Descrizione

int dbase_numfields ( int dbase_identifier )

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

Esempio 1. Usare dbase_numfields()

<?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i=0; $i < $nf; $i++) {
    echo $rec[$i]."<br>\n";
}
?>

dbase_numrecords

(PHP 3, PHP 4, PHP 5)

dbase_numrecords --  Restituisce il numero di records in un database dBase.

Descrizione

int dbase_numrecords ( int dbase_identifier )

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.

dbase_open

(PHP 3, PHP 4, PHP 5)

dbase_open -- Apre un database dBase

Descrizione

int dbase_open ( string filename, int flags )

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.

dbase_pack

(PHP 3, PHP 4, PHP 5)

dbase_pack -- Stabilizza un database dBase

Descrizione

bool dbase_pack ( int dbase_identifier )

Stabilizza il database specificato (cancellando permanentemente tutti i records marcati per la cancellazione usando dbase_delete_record()).

dbase_replace_record

(PHP 3 >= 3.0.11, PHP 4, PHP 5)

dbase_replace_record -- Sostituisce un record in un database dBase

Descrizione

bool dbase_replace_record ( int dbase_identifier, array record, int dbase_record_number )

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

XXVI. Funzioni DBM

Introduzione

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.


Requisiti

Per utilizzare queste funzioni occorre compilare il PHP con il supporto per un database sottostante. Vedere l'elenco dei database supoprtati.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

La funzione dbmopen() restituisce un identificatore di database che può essere utilizzato con le altre funzioni dbm.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Esempio 1. Esempio DBM

<?php

$dbm = dbmopen ("lastseen", "w");
if (dbmexists ($dbm, $userid)) {
    $last_seen = dbmfetch ($dbm, $userid);
} else {
    dbminsert ($dbm, $userid, time());
}
do_stuff();
dbmreplace($dbm, $userid, time());
dbmclose($dbm);

?>

Sommario
dblist --  Descrive la libreria DBM-compatibile in uso.
dbmclose -- Chiude un database dbm
dbmdelete --  Cancella il valore per una chiave da un database DBM
dbmexists --  Dice se esiste un valore per una chiave in un database DBM
dbmfetch --  Estrae un valore per una chiave da un database DBM
dbmfirstkey --  Recupera la prima chiave da un database DBM
dbminsert --  Inserisce un valore per una chiave in un database DBM
dbmnextkey --  Recupera la chiave successiva da un database DBM
dbmopen -- Apre un database DBM
dbmreplace --  Sostituisce il valore per una chiave in un database DBM

dblist

(PHP 3, PHP 4, PECL)

dblist --  Descrive la libreria DBM-compatibile in uso.

Descrizione

string dblist ( void )

Esempio 1. Ottenere informazioni da linea di comando

[marcus@zaphod marcus]$ php -r 'echo dblist();'
This is GDBM version 1.8.0, as of May 19, 1999.

dbmclose

(PHP 3, PHP 4, PECL)

dbmclose -- Chiude un database dbm

Descrizione

bool dbmclose ( resource dbm_identifier )

Sblocca e chiude il database specificato.

dbmdelete

(PHP 3, PHP 4, PECL)

dbmdelete --  Cancella il valore per una chiave da un database DBM

Descrizione

bool dbmdelete ( resource dbm_identifier, string key )

Cancella il valore per key nel database.

Restituisce FALSE se la chiave non esisteva nel database.

dbmexists

(PHP 3, PHP 4, PECL)

dbmexists --  Dice se esiste un valore per una chiave in un database DBM

Descrizione

bool dbmexists ( resource dbm_identifier, string key )

Restituisce TRUE se c'è un valore associato con la key.

dbmfetch

(PHP 3, PHP 4, PECL)

dbmfetch --  Estrae un valore per una chiave da un database DBM

Descrizione

string dbmfetch ( resource dbm_identifier, string key )

Restituisce il valore associato con key.

dbmfirstkey

(PHP 3, PHP 4, PECL)

dbmfirstkey --  Recupera la prima chiave da un database DBM

Descrizione

string dbmfirstkey ( resource dbm_identifier )

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.

dbminsert

(PHP 3, PHP 4, PECL)

dbminsert --  Inserisce un valore per una chiave in un database DBM

Descrizione

int dbminsert ( resource dbm_identifier, string key, string value )

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

dbmnextkey

(PHP 3, PHP 4, PECL)

dbmnextkey --  Recupera la chiave successiva da un database DBM

Descrizione

string dbmnextkey ( resource dbm_identifier, string key )

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:

Esempio 1. Esaminare ogni coppia key/value in un database DBM

<?php

$key = dbmfirstkey($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch($dbm_id, $key) . "\n";
    $key = dbmnextkey($dbm_id, $key);
}

?>

dbmopen

(PHP 3, PHP 4, PECL)

dbmopen -- Apre un database DBM

Descrizione

resource dbmopen ( string filename, string flags )

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.

dbmreplace

(PHP 3, PHP 4, PECL)

dbmreplace --  Sostituisce il valore per una chiave in un database DBM

Descrizione

int dbmreplace ( resource dbm_identifier, string key, string value )

Sostituisce il valore per la chiave specificata nel database.

Aggiungerà inoltre la chiave al database se la stessa non esisteva già.

XXVII. dbx Functions

Introduzione

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.


Requisiti

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:

Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. DBX Configuration Options

NameDefaultChangeableChangelog
dbx.colnames_case"unchanged"PHP_INI_SYSTEMAvailable since PHP 4.3.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

dbx.colnames_case string

Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().


Tipi di risorse

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.


Costanti predefinite

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.

DBX_MYSQL (integer)

DBX_ODBC (integer)

DBX_PGSQL (integer)

DBX_MSSQL (integer)

DBX_FBSQL (integer)

DBX_OCI8 (integer) (available from PHP 4.3.0)

DBX_SYBASECT (integer)

DBX_SQLITE (integer) (PHP 5)

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_RESULT_UNBUFFERED (integer) (PHP 5)

DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)

DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)

DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)

DBX_CMP_NATIVE (integer)

DBX_CMP_TEXT (integer)

DBX_CMP_NUMBER (integer)

DBX_CMP_ASC (integer)

DBX_CMP_DESC (integer)

Sommario
dbx_close -- Close an open connection/database
dbx_compare -- Compare two rows for sorting purposes
dbx_connect -- Open a connection/database
dbx_error --  Report the error message of the latest function call in the module (not just in the connection)
dbx_escape_string --  Escape a string so it can safely be used in an sql-statement
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
dbx_query -- Send a query and fetch all results (if any)
dbx_sort --  Sort a result from a dbx_query by a custom sort function

dbx_close

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_close -- Close an open connection/database

Description

bool dbx_close ( object link_identifier )

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Nota: Always refer to the module-specific documentation as well.

See also dbx_connect().

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

dbx_compare -- Compare two rows for sorting purposes

Description

int dbx_compare ( array row_a, array row_b, string column_key [, int flags] )

dbx_compare() returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC. dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order

  • DBX_CMP_DESC - descending order

and the preferred comparison type:

  • DBX_CMP_NATIVE - no type conversion

  • DBX_CMP_TEXT - compare items as strings

  • DBX_CMP_NUMBER - compare items numerically

One of the direction and one of the type constant can be combined with bitwise OR operator (|). The default value for the flags parameter is DBX_CMP_ASC | DBX_CMP_NATIVE.

Esempio 1. dbx_compare() example

<?php
function user_re_order($a, $b) 
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See also dbx_sort().

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_connect -- Open a connection/database

Description

object dbx_connect ( mixed module, string host, string database, string username, string password [, int persistent] )

dbx_connect() returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"

  • DBX_ODBC or "odbc"

  • DBX_PGSQL or "pgsql"

  • DBX_MSSQL or "mssql"

  • DBX_FBSQL or "fbsql" (available from PHP 4.1.0)

  • DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)

  • DBX_OCI8 or "oci8" (available from PHP 4.3.0)

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

database

It is the name of the currently selected database.

handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module

It is used internally by dbx only, and is actually the module number mentioned above.

Esempio 1. dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Nota: Always refer to the module-specific documentation as well.

See also dbx_close().

dbx_error

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_error --  Report the error message of the latest function call in the module (not just in the connection)

Description

string dbx_error ( object link_identifier )

dbx_error() returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Esempio 1. dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Nota: Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented (yet).

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

dbx_escape_string --  Escape a string so it can safely be used in an sql-statement

Description

string dbx_escape_string ( object link_identifier, string text )

dbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.

Esempio 1. dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

See also dbx_query().

dbx_fetch_row

(PHP 5 <= 5.0.4)

dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

mixed dbx_fetch_row ( object result_identifier )

dbx_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

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

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

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_query -- Send a query and fetch all results (if any)

Description

mixed dbx_query ( object link_identifier, string sql_statement [, int flags] )

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

Esempio 1. How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types 
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX

It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.

If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.

DBX_RESULT_INFO

It provides info about columns, such as field names and field types.

DBX_RESULT_ASSOC

It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.

Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.

DBX_RESULT_UNBUFFERED (PHP 5)

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.

DBX_COLNAMES_UNCHANGED (available from PHP 4.3.0)

The case of the returned column names will not be changed.

DBX_COLNAMES_UPPERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to uppercase.

DBX_COLNAMES_LOWERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to lowercase.

Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:

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

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields 
?>

info (optional)

It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Esempio 2. lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";  
}
?>
data

This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Esempio 3. outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Esempio 4. How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Nota: Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

See also dbx_escape_string(), dbx_fetch_row() and dbx_connect().

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

dbx_sort --  Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object result, string user_compare_function )

Restituisce 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

<?php
function user_re_order($a, $b) 
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See also dbx_compare().

XXVIII. Funzioni per l'IO diretto

Introduzione

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


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Per potere utilizzare queste funzioni, occorre configurare PHP con --enable-dio.


Costanti predefinite

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.

c (integer)

F_DUPFD (integer)

F_GETFD (integer)

F_GETFL (integer)

F_GETLK (integer)

F_GETOWN (integer)

F_RDLCK (integer)

F_SETFL (integer)

F_SETLK (integer)

F_SETLKW (integer)

F_SETOWN (integer)

F_UNLCK (integer)

F_WRLCK (integer)

O_APPEND (integer)

O_ASYNC (integer)

O_CREAT (integer)

O_EXCL (integer)

O_NDELAY (integer)

O_NOCTTY (integer)

O_NONBLOCK (integer)

O_RDONLY (integer)

O_RDWR (integer)

O_SYNC (integer)

O_TRUNC (integer)

O_WRONLY (integer)

S_IRGRP (integer)

S_IROTH (integer)

S_IRUSR (integer)

S_IRWXG (integer)

S_IRWXO (integer)

S_IRWXU (integer)

S_IWGRP (integer)

S_IWOTH (integer)

S_IWUSR (integer)

S_IXGRP (integer)

S_IXOTH (integer)

S_IXUSR (integer)


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione definisce un solo tipo di risorsa: un descrittore di file restituito dalla funzione dio_open().

Sommario
dio_close -- Chiude il descrittore di file passato
dio_fcntl -- Esegue la funzione C fcntl su un descrittore di file
dio_open --  Apre un nuovo file nella modalità specificata da flags e i permessi indicati in mode
dio_read -- Legge n bytes da un descrittore di file
dio_seek -- Si posiziona al byte pos del file indicato da fd
dio_stat --  Restituisce le informazioni relative al file indicato da fd
dio_tcsetattr --  Imposta gli attributi terminale e la velocità per una porta seriale
dio_truncate --  Tronca il file indicato da fd ad un numero di byte specificato
dio_write --  Scrive dati sul file indicato da fd con la possibilità di troncarne la lunghezza

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_close -- Chiude il descrittore di file passato

Descrizione

void dio_close ( resource fd )

La funzione dio_close() chiude il descrittore di file fd.

Elenco dei parametri

fd

Il descrittore di file restituito da dio_open().

Valori restituiti

No value is returned.

Esempi

Esempio 1. Chiudere un descrittore di file

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);
 
dio_close($fd);
?>

Vedere anche:

dio_open()

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_fcntl -- Esegue la funzione C fcntl su un descrittore di file

Descrizione

mixed dio_fcntl ( resource fd, int cmd [, mixed args] )

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

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

cmd

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.

args

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)

Valori restituiti

Restituisce il valore della chiamata C.

Esempi

Esempio 1. Impostare e cancellare un lock

<?php
 
$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock succesfully set/cleared";
}
 
dio_close($fd);
?>

dio_open

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

Descrizione

resource dio_open ( string filename, int flags [, int mode] )

La funzione dio_open() apre un file e restituisce un nuovo descrittore di file per questo.

Elenco dei parametri

filename

Il file aperto.

flags

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.

mode

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.

Valori restituiti

Restituisce un descrittore di file, oppure FALSE in caso di errore.

Esempi

Esempio 1. Apertura di un descrittore di file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

Vedere anche:

dio_close()

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_read -- Legge n bytes da un descrittore di file

Descrizione

string dio_read ( resource fd [, int len] )

La funzione dio_read() legge e restituisce len bytes dal file indicato dal descrittore fd.

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

len

Numero di byte da leggere. Se non indicato dio_read() legge blocchi da un 1k.

Valori restituiti

I byte letti da fd.

Vedere anche:

dio_write()

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_seek -- Si posiziona al byte pos del file indicato da fd

Descrizione

int dio_seek ( resource fd, int pos [, int whence] )

La funzione dio_seek() viene utilizzata per modificare la posizione nel file indicato dal descrittore fd.

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

pos

La nuova posizione.

whence

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.

Valori restituiti

Esempi

Esempio 1. Posizionamento in un file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// Si posiziona a 10 caratteri dall'inizio del file

dio_seek($fd, -2, SEEK_CUR);
// Si posiziona a 8 caratteri dall'inizio del file

dio_seek($fd, -5, SEEK_END);
// Si posiziona a 5 caratteri dalla fine del file

dio_seek($fd, 10, SEEK_END);
// Si posiziona a 10 caratteri dopo la fine del file
// i 10 caratteri tra la fine del file e la posizione corrente
// sono riempiti con zero.

dio_close($fd);
?>

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_stat --  Restituisce le informazioni relative al file indicato da fd

Descrizione

array dio_stat ( resource fd )

La funzione dio_stat() restituisce le informazioni sul dato descrittore di file.

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

Valori restituiti

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

Se si verifica un errore la funzione dio_stat() restituisce NULL.

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

dio_tcsetattr --  Imposta gli attributi terminale e la velocità per una porta seriale

Descrizione

void dio_tcsetattr ( resource fd, array options )

La funzione dio_tcsetattr() imposta gli attributi di terminale e la velocità della porta aperta fd.

Nota: Questa funzione non è implementata su piattaforme Windows

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

options

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.

Valori restituiti

No value is returned.

Esempi

Esempio 1. Esempio di impostazione della velocità di una porta seriale

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
)); 

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
} 

?>

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

dio_truncate --  Tronca il file indicato da fd ad un numero di byte specificato

Descrizione

bool dio_truncate ( resource fd, int offset )

La 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

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

offset

Posizione in byte.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

dio_write

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

Descrizione

int dio_write ( resource fd, string data [, int len] )

La funzione dio_write() scrive fino a len bytes da data nel file fd.

Elenco dei parametri

fd

Descrittore di file restituito da dio_open().

data

I dati scritti.

len

Lunghezza dei dati da scrivere in byte. Se non indicato, la funzione scrive tutti i dati nel file indicato.

Valori restituiti

La funzione restituisce il numero di byte scritti in fd.

Vedere anche:

dio_read()

XXIX. Funzioni per le directory


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

DIRECTORY_SEPARATOR (string)

PATH_SEPARATOR (string)

Nota: La costante PATH_SEPARATOR è stata inserita dalla versione 4.3.0-RC2.


Vedere anche:

Per funzioni correlate, quali dirname(), is_dir(), mkdir() e rmdir(), vedere la sezione Filesystem.

Sommario
chdir -- cambia directory
chroot -- Cambia la direcory di root
dir -- Classe directory
closedir -- Chiude l'handle della directory
getcwd -- Restituisce la directory di lavoro in uso
opendir -- Apre l'handle della directory
readdir -- Legge una voce dall'handle della directory
rewinddir -- Riavvolge l'handle della directory
scandir -- List files and directories inside the specified path

chdir

(PHP 3, PHP 4, PHP 5)

chdir -- cambia directory

Descrizione

bool chdir ( string directory )

Cambia la directory in uso da parte del PHP in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. Esempio di uso di chdir()

<?php

// directory corrente
echo getcwd() . "\n";

chdir('public_html');

// directory corrente
echo getcwd() . "\n";

?>

Il precedente esempio visualizzerà:

/home/vincent
/home/vincent/public_html

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

chroot

(PHP 4 >= 4.0.5, PHP 5)

chroot -- Cambia la direcory di root

Descrizione

bool chroot ( string directory )

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

dir

(PHP 3, PHP 4, PHP 5)

dir -- Classe directory

Descrizione

class dir {

dir ( string directory )

string path

resource handle

string read ( void )

void rewind ( void )

void close ( void )

}

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.

Esempio 1. esempio dir()

<?php
$d = dir("/etc");
echo "Handle: " . $d->handle . "<br />\n";
echo "Path: " . $d->path . "<br />\n";
while ($entry = $d->read()) {
    echo $entry."<br />\n";
}
$d->close();
?>

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.

closedir

(PHP 3, PHP 4, PHP 5)

closedir -- Chiude l'handle della directory

Descrizione

void closedir ( resource dir_handle )

Chiude il flusso directory indicato da dir_handle. Il flusso deve essere stato aperto in precedenza da opendir().

getcwd

(PHP 4, PHP 5)

getcwd -- Restituisce la directory di lavoro in uso

Descrizione

string getcwd ( void )

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.

Esempio 1. Esempio di uso di getcwd()

<?php
 
// current directory
echo getcwd() . "\n";
 
chdir('cvs');
 
// current directory
echo getcwd() . "\n";
 
?>

Il precedente esempio visualizzerà qualcosa simile a:

/home/didou
/home/didou/cvs

Vedere anche: chdir() e chmod().

opendir

(PHP 3, PHP 4, PHP 5)

opendir -- Apre l'handle della directory

Descrizione

resource opendir ( string percorso )

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.

Esempio 1. esempio opendir()

<?php
$dir = "/tmp/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
   if ($dh = opendir($dir)) {
      while (($file = readdir($dh)) !== false) {
             echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}

?>

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

Vedere anche: is_dir(), readdir() e Dir

readdir

(PHP 3, PHP 4, PHP 5)

readdir -- Legge una voce dall'handle della directory

Descrizione

string readdir ( resource dir_handle )

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

<?php
// Nota che l'operatore !== non è esistito fino alla versione 4.0.0-RC2
if ($handle = opendir('/percorso/ai/file')) {
    echo "Handle della directory: $handle\n";
    echo "File:\n";

   /* Questa è la maniera corretta di eseguire un loop all'interno di una directory. */
   while (false !== ($file = readdir($handle))) { 
       echo "$file\n";
   }

   /* Questa è la maniera SCORRETTA di eseguire un loop all'interno di una directory. */
   while ($file = readdir($handle)) { 
       echo "$file\n";
   }

   closedir($handle); 
}
?>

Nota che readdir() restituirà le voci . e ... Se non si vogliono ottenere queste, si possono semplicemente eliminare:

Esempio 2. Elenca tutti i file della directory in uso ed elimina . e ..

<?php 
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") { 
            echo "$file\n"; 
        } 
    }
    closedir($handle); 
}
?>

Vedere anche: is_dir() e glob().

rewinddir

(PHP 3, PHP 4, PHP 5)

rewinddir -- Riavvolge l'handle della directory

Descrizione

void rewinddir ( resource dir_handle )

Reimposta il flusso della directory indicato da dir_handle all'inizio della directory.

scandir

(PHP 5)

scandir -- List files and directories inside the specified path

Descrizione

array scandir ( string directory [, int sorting_order [, resource context]] )

Returns an array of files and directories from the directory.

Elenco dei parametri

directory

The directory that will be scanned.

sorting_order

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.

context

For a description of the context parameter, refer to the streams section of the manual.

Valori restituiti

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.

Esempi

Esempio 1. A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Esempio 2. PHP 4 alternatives to scandir()

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Note

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.

XXX. DOM Functions

Introduzione

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.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Classi predefinite

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.


DOMAttr

Estende DOMNode. L'interfaccia DOMAttr rappresenta un attributo dell'oggetto DOMElement.


Costruttori


Metodi


Proprietà

Tabella 1.

NomeTipoSola letturaDescrizione
namestringsiNome dell'attributo
ownerElementDOMElementElemento che contiene l'attributo
schemaTypeInfoboolNon ancora impementato, ritorna sempre NULL
specifiedboolNon ancora impementato, ritorna sempre NULL
valuestringnoValore dell'attributo

DOMCharacterData

Espande DOMNode.


Metodi


Proprietà

Tabella 2.

NomeTipoSola letturaDescrizione
datastringnoContenuto del nodo
lengthintLunghezza del contenuto

DOMComment

Espande DOMCharacterData.


Costruttori


DOMDocument

Espande DOMNode.


Costruttori


Metodi


Proprietà

Tabella 3.

NomeTipoSola letturaDescrizione
actualEncodingstring 
configDOMConfiguration 
doctypeDOMDocumentType Dichiarazione del tipo documento associato al docuemnto.
documentElementDOMElement Attributo di convenienza per accedere direttamente al nodo figlio, che è l'elemento del documento.
documentURIstringno Luogo del documento oppure NULL se indefinito.
encodingstringno 
formatOutputboolno 
implementationDOMImplementation L'oggetto DOMImplementation che gestisce questo documento.
preserveWhiteSpaceboolnoNon rimuovere gli spazi ridondanti. Default TRUE.
recoverboolno 
resolveExternalsboolno Impostare a TRUE per caricare le entità esterne dalla dichiarazione doctype. Questo è utile per includere entità di caratteri nel documento XML.
standaloneboolno 
strictErrorCheckingboolnoGenera un DOMException in caso di errore. Default TRUE.
substituteEntitiesboolno 
validateOnParseboolnoCarica e valida nei confronti della DTD. Default FALSE.
versionstringno 
xmlEncodingstring 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.
xmlStandaloneboolno Attributo che specifica, come parte della dichiarazione XML, se il documento è standalone. Vale FALSE se non specificato.
xmlVersionstringno 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".

DOMDocumentType

Espande DOMNode

Ciascun DOMDocument possiede un attributo doctype il cui valore può essere o NULL o un oggetto DOMDocumentType.


Proprietà

Tabella 4.

NomeTipoSola letturaDescrizione
publicIdstringIdentificatore pubblico del subset esterno.
systemIdstringIdentificatore di sistema del subset esterno. Può essere un URI assoluto o meno.
namestringIl nome della DTD; ad esempio il nome che segue immediatamente la parola chiave DOCTYPE.
entitiesDOMNamedNodeMap Un oggetto DOMNamedNodeMap che contiene le entità generali, sia interne che esterne, dichiarate nella DTD.
notationsDOMNamedNodeMap Un oggetto DOMNamedNodeMap contenente le notazioni dichiarate nella DTD.
internalSubsetstring SubSet interno definito come stringa, oppure null se non vi è nulla. Questo non contiene le parentesi quadre di delimitazione.

DOMElement

Espande DOMNode.


Costruttori


Metodi


Proprietà

Tabella 5.

NomeTipoSola letturaDescrizione
schemaTypeInfoboolNon ancora implementato, restituisce sempre NULL
tagNamestringNome dell'elemento

DOMEntity

Espande DOMNode

Questa interfaccia rappresenta una entità nota, sia interpretata che no, in un documento XML.


Proprietà

Tabella 6.

NomeTipoSola letturaDescrizione
publicIdstring Identificatore pubblico associato all'entità, se indicato, altrimenti NULL.
systemIdstring Identificatore di sistema associato all'entità, se indicato, altrimenti NULL. Può essere un URI assoluto.
notationNamestring Per le entità non interpretate, il nome della notazione dell'entità. Per le entità interpretate vale NULL.
actualEncodingstringno 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.
encodingstring Attributo che indica, come parte del testo di dichiarazione, la codifica dell'entità, in caso di entità esterna. Negli altri casi vale NULL.
versionstring Attributo che indica, come parte del testo di dichiarazione, il numero di versione di questa entità, in caso di entità esterna. Altrimenti NULL.

DOMEntityReference

Espande DOMNode.


Costruttori


DOMException

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.


Proprietà

Tabella 7.

NomeTipoSola letturaDescrizione
codeintIntero indicante il tipo di errore generato

DOMImplementation

L'interfaccia DOMImplementation fornisce diversi metodi per eseguire operazioni che sono indipendenti da qualsiasi istanza del modello ad oggetti del documento.


Costruttori


Metodi


DOMNode

Metodi


Proprietà

Tabella 8.

NomeTipoSola letturaDescrizione
nodeNamestringRestituisce un nome più accurato per il tipo di nodo.
nodeValuestringnoValore di questo nodo, dipende dal tipo.
nodeTypeintTipo di nodo. Una delle costanti XML_xxx_NODE predefinite.
parentNodeDOMNodeNodo genitore di questo nodo.
childNodesDOMNodeList Un oggetto DOMNodeList che contiene tutti i nodi figli di questo nodo. Se non vi sono nodi figli, questa è un DOMNodeList vuoto.
firstChildDOMNode Il primo figlio di questo nodo. Se tale nodo non esiste, restituisce NULL.
lastChildDOMNode L'ultimo figlio di questo nodo. Se tale nodo non esiste, restituisce NULL.
previousSiblingDOMNode Il nodo immediatamente precedente a questo. Se tale nodo non esiste, restituisce NULL.
nextSiblingDOMNode Il nodo immediatamente seguente a questo. Se tale nodo non esiste, restituisce NULL.
attributesDOMNamedNodeMap Un oggetto DOMNamedNodeMap contenente gli attributi di questo nodo (se si tratta di un DOMElement) oppure NULL.
ownerDocumentDOMDocument L'oggetto DOMDocument associato a questo nodo.
namespaceURIstring L'URI dello spazio dei nomi di questo nodo, oppure NULL se non specificato.
prefixstringno Prefisso dello spazio dei nomi del nodo, oppure NULL se non specificato.
localNamestring Restituisce la parte locale del nome qualificato del nodo.
baseURIstring L'URI assoluto del nodo oppure NULL se l'implementazione non è in grado di ottenere l'URI assoluto.
textContentstringno Questo attributo restituisce il testo contenuto nel nodo e nei suoi discendenti.

DOMNodeList


Metodi


Proprietà

Tabella 9.

NomeTipoSola letturaDescrizione
lengthint Numero di nodi nella lista. Il range valido per l'indice varia tra 0 e length - 1 compresi.

DOMNotation

Espande DOMNode


Proprietà

Tabella 10.

NomeTipoSola letturaDescrizione
publicIdstring 
systemIdstring 

DOMProcessingInstruction

Espande DOMNode.


Costruttori


Proprietà

Tabella 11.

NomeTipoSola letturaDescrizione
targetstring 
datastringno 

DOMText

Espande DOMCharacterData.


Costruttori


Metodi


Proprietà

Tabella 12.

NomeTipoSola letturaDescrizione
wholeTextstring 

DOMXPath


Costruttori


Metodi


Proprietà

Tabella 13.

NomeTipoSola letturaDescrizione
documentDOMDocument  

Esempi

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Esempio 1. chapter.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>


Costanti predefinite

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

CostanteValoreDescrizione
XML_ELEMENT_NODE (integer) 1Il nodo è un DOMElement
XML_ATTRIBUTE_NODE (integer) 2Il nodo è un DOMAttr
XML_TEXT_NODE (integer) 3Il nodo è un DOMText
XML_CDATA_SECTION_NODE (integer) 4Il nodo è un oggetto DOMCharacterData
XML_ENTITY_REF_NODE (integer) 5Il nodo è un oggetto DOMEntityReference
XML_ENTITY_NODE (integer) 6Il nodo è un DOMEntity
XML_PI_NODE (integer) 7Il nodo è un DOMProcessingInstruction
XML_COMMENT_NODE (integer) 8Il nodo è un DOMComment
XML_DOCUMENT_NODE (integer) 9Il nodo è un DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) 10Il nodo è un oggetto DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) 11Il nodo è un oggetto DOMDocumentFragment
XML_NOTATION_NODE (integer) 12Il 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

CostanteValoreDescrizione
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) 3Se 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) 12Stringa non valida o illegale.
DOM_INVALID_MODIFICATION_ERR (integer) 13Tentativo 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) 15Parametro 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.
Sommario
DOMAttr->__construct() --  Crea un nuovo oggetto DOMAttr
DOMAttr->isId() --  Verifica se l'attributo è un ID definito
DOMCharacterData->appendData() --  Aggiunge una stringa alla fine del testo di un nodo
DOMCharacterData->deleteData() --  Rimuove un range di caratteri da un nodo
DOMCharacterData->insertData() --  Inserisce una stringa all'offset di 16 bit indicato
DOMCharacterData->replaceData() --  Sostituisce una stringa all'interno di un nodo DOMCharacterData
DOMCharacterData->substringData() --  Estrae un tange di dati da un nodo
DOMComment->__construct() --  Crea un nuovo oggetto DOMComment
DOMDocument->__construct() --  Crea un nuovo oggetto DOMDocument
DOMDocument->createAttribute() -- Crea un nuovo attributo
DOMDocument->createAttributeNS() --  Crea un nuovo nodo attributo con associato lo spazio dei nomi
DOMDocument->createCDATASection() -- Crea un nuovo nodo cdata
DOMDocument->createComment() -- Crea un nuovo nodo di commento
DOMDocument->createDocumentFragment() -- Crea un nuovo frammento di documento
DOMDocument->createElement() -- Crea un nuovo nodo elemento
DOMDocument->createElementNS() --  Crea un nuovo nodo elemento con associato lo spazio dei nomi
DOMDocument->createEntityReference() -- Crea un nuovo nodo riferimento ad entità
DOMDocument->createProcessingInstruction() -- Crea un nuovo nodo PI
DOMDocument->createTextNode() -- Crea un nuovo nodo di testo
DOMDocument->getElementById() -- Cerca un elemento con un certo id
DOMDocument->getElementsByTagName() -- Cerca tutti gli eleemnti per un dato nome di tag
DOMDocument->getElementsByTagNameNS() --  Ricerca tutti gli elementi per un dato nome tag nello spazio dei nomi indicato.
DOMDocument->importNode() -- Importa un nodo nel documento corrente
DOMDocument->load() --  Carica un documento XML da un file
DOMDocument->loadHTML() --  Carica una pagina 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() --  Scarica l'albero XML interno in un file
DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting
DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting
DOMDocument->saveXML() --  Dumps the internal XML tree back into a string
DOMDocument->schemaValidate() --  Validates a document based on a schema
DOMDocument->schemaValidateSource() --  Validates a document based on a schema
DOMDocument->validate() --  Valida il documento in base alla sua DTD
DOMDocument->xinclude() --  Sostituisce gli XIncludes in un oggetto DOMDocument
DOMElement->__construct() --  Crea un nuovo oggetto DOMElement
DOMElement->getAttribute() -- Restituisce il valore di un attributo
DOMElement->getAttributeNode() -- Restituisce il nodo attributo
DOMElement->getAttributeNodeNS() --  Restituisce un nodo attributo
DOMElement->getAttributeNS() -- Restituisce il valore di un attributo
DOMElement->getElementsByTagName() -- Restituisce gli elementi in base al nome del tag
DOMElement->getElementsByTagNameNS() -- Restituisce gli elementi per spazio dei nomi e nome locale
DOMElement->hasAttribute() -- Verifica se l'attributo esiste
DOMElement->hasAttributeNS() --  Verifica se esiste l'attributo
DOMElement->removeAttribute() -- Rimuove l'attributo
DOMElement->removeAttributeNode() -- Rimuove gli attributi
DOMElement->removeAttributeNS() -- Rimuove gli attributi
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
DOMAttr->__construct() --  Crea un nuovo oggetto DOMEntityReference
DOMImplementation->__construct() --  Crea un nuovo oggetto DOMImplementation
DOMImplementation->createDocument() --  Crea un oggetto DOMDocument del tipo indicato con il suo elemento documento
DOMImplementation->createDocumentType() --  Crea un oggetto DOMDocumentType vuoto
DOMImplementation->hasFeature() --  Verifica se l'implementazione DOM ha una specifica caratteristica
DOMNamedNodeMap->getNamedItem() --  Recupera un nodo indicandone il nome
DOMNamedNodeMap->getNamedItemNS() --  Recupera un nodo indicando il nome locale e l'URI dello spazio dei nomi
DOMNamedNodeMap->item() -- Recupera un nodo tramite il suo indice
DOMNode->appendChild() --  Aggiunge un nuovo nodo figlio alla fine dei nodi figli
DOMNode->cloneNode() --  Clona un nodo
DOMNode->hasAttributes() --  Verifica se un nodo ha degli attributi
DOMNode->hasChildNodes() --  Verifica se un nodo ha nodi figli
DOMNode->insertBefore() --  Aggiunge un nuovo nodo figlio prima del riferimento
DOMNode->isSameNode() --  Indica se due nodi sono il medesimo nodo
DOMNode->isSupported() --  Verifica se una caratteristica è supportata dalla versione indicata
DOMNode->lookupNamespaceURI() --  Restituisce l'URI dello spazio dei nomi in base al prefisso
DOMNode->lookupPrefix() --  Resituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomi
DOMNode->normalize() --  Normalizza un nodo
DOMNode->removeChild() --  Rimuove un nodo figlio dalla lista dei nodi figli
DOMNode->replaceChild() --  Sostituisce un nodo figlio
DOMNodelist->item() --  Recupera il nodo indicato dall'indice
DOMProcessingInstruction->__construct() --  Crea un nuovo oggetto DOMProcessingInstruction
DOMText->__construct() --  Crea un nuovo oggetto DOMText
DOMText->isWhitespaceInElementContent() --  Indica se questo nodo di testo contiene spazi
DOMText->splitText() --  Spezza il nodo in due all'offset specificato
DOMXPath->__construct() --  Crea un nuovo oggetto DOMXPath
DOMXPath->evaluate() --  Valuta l'espressione XPath data e restituisce un risultato se possibile
DOMXPath->query() --  Valuta l'espressione XPath
DOMXPath->registerNamespace() --  Registra lo spazio dei nomi nell'oggetto DOMXpath
dom_import_simplexml --  Ottiene un'oggetto DOMElement da un'oggetto SimpleXMLElement

DOMAttr->__construct()

(no version information, might be only in CVS)

DOMAttr->__construct() --  Crea un nuovo oggetto DOMAttr

Descrizione

class DOMAttr {

__construct ( string name [, string value] )

}

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

Elenco dei parametri

name

Nome tag dell'attributo- The tag name of the attribute.

value

Valore dell'attributo.

Esempi

Esempio 1. Esempio di creazione di un nuovo DOMAttr

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root attr="attrvalue" /> */

?>

DOMAttr->isId()

(no version information, might be only in CVS)

DOMAttr->isId() --  Verifica se l'attributo è un ID definito

Descrizione

class DOMAttr {

bool isId ( void )

}

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

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. DOMAttr->isId() Example

<?php

$doc = new DomDocument;

// Occorre validare il documento prima di puntare all'id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// Recuperiamo l'attributo chianat id del capitolo documento
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

DOMCharacterData->appendData()

(no version information, might be only in CVS)

DOMCharacterData->appendData() --  Aggiunge una stringa alla fine del testo di un nodo

Descrizione

class DOMCharacterData {

void appendData ( string data )

}

Aggiunge la stringa data alla fine dei dati del nodo.

Elenco dei parametri

data

La stringa da aggiungere.

Valori restituiti

No value is returned.

DOMCharacterData->deleteData()

(no version information, might be only in CVS)

DOMCharacterData->deleteData() --  Rimuove un range di caratteri da un nodo

Descrizione

class DOMCharacterData {

void deleteData ( int offset, int count )

}

Rimuove un numero di caratteri pari a count a partire dalla posizione offset.

Elenco dei parametri

offset

Offset da cui partire a rimuovere.

count

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.

Valori restituiti

No value is returned.

Eccezioni

DOM_INDEX_SIZE_ERR

Eccezione generata se offset è negativo oppure più grande di un numero di 16 bit, oppure se count è negativo.

DOMCharacterData->insertData()

(no version information, might be only in CVS)

DOMCharacterData->insertData() --  Inserisce una stringa all'offset di 16 bit indicato

Descrizione

class DOMCharacterData {

void insertData ( int offset, string data )

}

Inserisce la stringa data alla posizione offset.

Elenco dei parametri

offset

L'offset del carattere da cui cominciare ad inserire.

data

La stringa da inserire.

Valori restituiti

No value is returned.

Eccezioni

DOM_INDEX_SIZE_ERR

Generato se offset è negativo o se è maggiore di un numero di 16 bit.

DOMCharacterData->replaceData()

(no version information, might be only in CVS)

DOMCharacterData->replaceData() --  Sostituisce una stringa all'interno di un nodo DOMCharacterData

Descrizione

class DOMCharacterData {

void replaceData ( int offset, int count, string data )

}

Sostituisce count caratteri a partire dalla posizione offset con data.

Elenco dei parametri

offset

Offset da cui iniziare la sostituzione.

count

Numero di caratteri da sostituire. Se la somma di offset e count eccede la lunghezza, allora saranno sostituiti tutti i caratteri fino alla fine.

data

La stringa con cui sostituire i caratteri del range indicato.

Valori restituiti

No value is returned.

Eccezioni

DOM_INDEX_SIZE_ERR

Generato se offset è negativo o maggiore di un numero di 16 bit, oppure se count è negativo.

DOMCharacterData->substringData()

(no version information, might be only in CVS)

DOMCharacterData->substringData() --  Estrae un tange di dati da un nodo

Descrizione

class DOMCharacterData {

string substringData ( int offset, int count )

}

Restituisce la stringa richiesta.

Elenco dei parametri

offset

Offset di partenza della stringa richiesta.

count

Numero di caratteri da estrarre.

Valori restituiti

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.

Eccezioni

DOM_INDEX_SIZE_ERR

Generato se offset è negativo o maggiore di un numero di 16 bit, oppure se count è negativo.

DOMComment->__construct()

(no version information, might be only in CVS)

DOMComment->__construct() --  Crea un nuovo oggetto DOMComment

Descrizione

class DOMComment {

__construct ( [string value] )

}

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

Elenco dei parametri

value

Il testo del commento.

Esempi

Esempio 1. Esempio di creazione di un nuovo DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

DOMDocument->__construct()

(no version information, might be only in CVS)

DOMDocument->__construct() --  Crea un nuovo oggetto DOMDocument

Descrizione

class DOMDocument {

__construct ( [string version [, string encoding]] )

}

Crea un nuovo oggetto DOMDocument.

Elenco dei parametri

version

Numero di versione del documento come parte della dichiarazione XML.

encoding

Codifica del docuemnto utilizzata nella dichisrazione XML.

Esempi

Esempio 1. Esempio di creazione di un nuovo DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

DOMDocument->createAttribute()

(no version information, might be only in CVS)

DOMDocument->createAttribute() -- Crea un nuovo attributo

Descrizione

class DOMDocument {

DOMAttr createAttribute ( string name )

}

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

Elenco dei parametri

name

Nome dell'attributo.

Valori restituiti

La nuova istanza di DOMAttr oppure FALSE se si verifica un errore.

Eccezioni

DOM_INVALID_CHARACTER_ERR

Generato se name contiene caratteri non validi.

DOMDocument->createAttributeNS()

(no version information, might be only in CVS)

DOMDocument->createAttributeNS() --  Crea un nuovo nodo attributo con associato lo spazio dei nomi

Descrizione

class DOMDocument {

DOMAttr createAttributeNS ( string namespaceURI, string qualifiedName )

}

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

Elenco dei parametri

namespaceURI

L' URI dello spazio dei nomi.

qualifiedName

Il nome del tag e prefisso dell'attributo nella struttura prefix:tagname.

Valori restituiti

La nuova istanza di DOMAttr oppure FALSE se si verifica un errore.

Eccezioni

DOM_INVALID_CHARACTER_ERR

Generato se qualifiedName contiene carattei non validi.

DOM_NAMESPACE_ERR

Generato se qualifiedName se è un nome malformato, oppure se qualifiedName ha un prefisso e namespaceURI vale NULL.

DOMDocument->createCDATASection()

(no version information, might be only in CVS)

DOMDocument->createCDATASection() -- Crea un nuovo nodo cdata

Descrizione

class DOMDocument {

DOMCDATASection createCDATASection ( string data )

}

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

Elenco dei parametri

data

Contenuto del nodo cdata.

Valori restituiti

Una nuova istanza di DOMCDATASection oppure FALSE in caso di errore.

DOMDocument->createComment()

(no version information, might be only in CVS)

DOMDocument->createComment() -- Crea un nuovo nodo di commento

Descrizione

class DOMDocument {

DOMComment createComment ( string data )

}

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

Elenco dei parametri

data

Il contenuto del commento.

Valori restituiti

Una istanza di DOMComment oppure FALSE in caso di errore.

DOMDocument->createDocumentFragment()

(no version information, might be only in CVS)

DOMDocument->createDocumentFragment() -- Crea un nuovo frammento di documento

Descrizione

class DOMDocument {

DOMDocumentFragment createDocumentFragment ( void )

}

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

Valori restituiti

L'istanza DOMDocumentFragment oppure FALSE in caso di errore.

DOMDocument->createElement()

(no version information, might be only in CVS)

DOMDocument->createElement() -- Crea un nuovo nodo elemento

Descrizione

class DOMDocument {

DOMElement createElement ( string name [, string value] )

}

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

Elenco dei parametri

name

Il nome del tag dell'elemento.

value

Il valore dell'elemento. Per default si crea un elemento vuoto. Il valore può essere impostato in un secondo momento tramite DOMElement->nodeValue.

Valori restituiti

Restituisce una nuova istanza della classe DOMElement oppure FALSE in caso di errore.

Eccezioni

DOM_INVALID_CHARACTER_ERR

Generato se name contiene caratteri invalidi.

Esempi

Esempio 1. Esempio di creazione di un nuovo elemento ed inserimento nel documento come root

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom->createElement('test', 'This is the root element!');

// inserimento dell'elemento come root (figlio del nodo documento)
$dom->appendChild($element);

echo $dom->saveXML();
?>

Il precedente esempio visualizzerà:

<?xml version="1.0" encoding="iso-8859-1"?>
<test>This is the root element!</test>

DOMDocument->createElementNS()

(no version information, might be only in CVS)

DOMDocument->createElementNS() --  Crea un nuovo nodo elemento con associato lo spazio dei nomi

Descrizione

class DOMDocument {

DOMElement createElementNS ( string namespaceURI, string qualifiedName [, string value] )

}

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

Elenco dei parametri

namespaceURI

L' URI dello spazio dei nomi.

qualifiedName

Un nuome qualificato pe l'elemento del tipo prefix:tagname.

value

Il valore dell'elemento. Per default si crea un elemento vuoto. Il valore può essere impostato in un secondo momento tramite DOMElement->nodeValue.

Valori restituiti

L'istanza DOMElement oppure FALSE in caso di errore.

Eccezioni

DOM_INVALID_CHARACTER_ERR

Generato se qualifiedName contiene caratteri non validi.

DOM_NAMESPACE_ERR

Generato se qualifiedName se è un nome qualificato invalido.

Esempi

Esempio 1. Esempio di creazione di un nuovo elemento ed inserimento nel documento come root

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// inserimento dell'elemento come root (figlio del nodo documento)
$dom->appendChild($element);

echo $dom->saveXML();
?>

Il precedente esempio visualizzerà:

<?xml version="1.0" encoding="iso-8859-1"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

DOMDocument->createEntityReference()

(no version information, might be only in CVS)

DOMDocument->createEntityReference() -- Crea un nuovo nodo riferimento ad entità

Descrizione

class DOMDocument {

DOMEntityReference createEntityReference ( string name )

}

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

Elenco dei parametri

name

Il contenuto del riferimento all'entità, ad esempio il riferimento all'entità meno & iniziale e ; finale.

Valori restituiti

Il nuovo DOMEntityReference oppure FALSE in caso di errore.

Eccezioni

DOM_INVALID_CHARACTER_ERR

Generato se name contiene caratteri non validi.

DOMDocument->createProcessingInstruction()

(no version information, might be only in CVS)

DOMDocument->createProcessingInstruction() -- Crea un nuovo nodo PI

Descrizione

class DOMDocument {

DOMProcessingInstruction createProcessingInstruction ( string target [, string data] )

}

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

Elenco dei parametri

target

Il target delle itrsuzioni di processamento.

data

Il contenuto della PI.

Valori restituiti

La nuova istanza di DOMProcessingInstruction oppure FALSE in caso di errore.

Eccezioni

DOM_INVALID_CHARACTER_ERR

Generato se target contiene caratteri non validi.

DOMDocument->createTextNode()

(no version information, might be only in CVS)

DOMDocument->createTextNode() -- Crea un nuovo nodo di testo

Descrizione

class DOMDocument {

DOMText createTextNode ( string content )

}

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

Elenco dei parametri

content

Il contenuto del testo.

Valori restituiti

La nuova istanza di DOMText oppure FALSE in caso di errore.

DOMDocument->getElementById()

(no version information, might be only in CVS)

DOMDocument->getElementById() -- Cerca un elemento con un certo id

Descrizione

class DOMDocument {

DOMElement getElementById ( string elementId )

}

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

Elenco dei parametri

elementId

Il valore dell'id univoco per le'elemento.

Valori restituiti

Restituisce DOMElement oppure NULL se l'elemento non è trovato.

Esempi

Esempio 1. Esempio di uso di DOMDocument->getElementById()

<?php

$doc = new DomDocument;

// Occorre validare il documento prima di puntare all'id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is books is: " . $doc->getElementById('books')->tagName . "\n";

?>

Il precedente esempio visualizzerà:

The element whose id is books is: chapter

DOMDocument->getElementsByTagName()

(no version information, might be only in CVS)

DOMDocument->getElementsByTagName() -- Cerca tutti gli eleemnti per un dato nome di tag

Descrizione

class DOMDocument {

DOMNodeList getElementsByTagName ( string name )

}

Questa funzione crea una nuova istanza della classe DOMNodeList contenente gli elementi con il nome tag cercato.

Elenco dei parametri

name

Il nome del tag da cercare. Il valore spaciale * indica tutti i tag.

Valori restituiti

Una nuova istanza dell'oggetto DOMNodeList contenente tutti gli elementi trovati.

DOMDocument->getElementsByTagNameNS()

(no version information, might be only in CVS)

DOMDocument->getElementsByTagNameNS() --  Ricerca tutti gli elementi per un dato nome tag nello spazio dei nomi indicato.

Descrizione

class DOMDocument {

DOMNodeList getElementsByTagNameNS ( string namespaceURI, string localName )

}

Restituicse un DOMNodeList contenente tutti gli elementi con il nome e lo spazio dei nomi indicati.

Elenco dei parametri

namespaceURI

L' URI dello spazio dei nomi degli elementi da cercare. Il valore speciale * indica tutti.

localName

Il nome locale degli elementi da cercare. Il valore speciale * indica tutti.

Valori restituiti

Un nuovo oggetto DOMNodeList contenente tutti gli elementi trovati.

Esempi

Esempio 1. Ottienet tutti gli elementi XInclude

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
 <xi:include href="book.xml">
  <xi:fallback>
   <error>xinclude: book.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// Carica la stringa definita in precedenza
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

Il precedente esempio visualizzerà:

local name: include, prefix: xi
local name: fallback, prefix: xi

DOMDocument->importNode()

(no version information, might be only in CVS)

DOMDocument->importNode() -- Importa un nodo nel documento corrente

Descrizione

class DOMDocument {

DOMNode importNode ( DOMNode importedNode [, bool deep] )

}

Questa funzione restituisce una copia del nodo da importare e lo associa al documento corrente.

Elenco dei parametri

importedNode

Il nodo da importare.

deep

Se impostato a TRUE, questo metodo importerà in modo ricorsivo il sotto-albero di importedNode.

Valori restituiti

Il nodo copiato.

Eccezioni

DOMException è generato se il nodo non può essere importato.

DOMDocument->load()

(no version information, might be only in CVS)

DOMDocument->load() --  Carica un documento XML da un file

Descrizione

class DOMDocument {

bool load ( string filename )

}

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

Elenco dei parametri

filename

Il percorso al documento XML.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Creazione di un documento

<?php
$doc = DOMDocument::load('book.xml');
echo $doc->saveXML();

$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

DOMDocument->loadHTML()

(no version information, might be only in CVS)

DOMDocument->loadHTML() --  Carica una pagina HTML da una stringa

Descrizione

class DOMDocument {

bool loadHTML ( string source )

}

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

Elenco dei parametri

source

La stringa HTML.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Creazione di un documento

<?php
$doc = DOMDocument::loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();

$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

DOMDocument->loadHTMLFile()

(no version information, might be only in CVS)

DOMDocument->loadHTMLFile() --  Carica un file HTML

Descrizione

class DOMDocument {

bool loadHTMLFile ( string filename )

}

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.

Elenco dei parametri

filename

Il nome del file HTML.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Creazione di un documento

<?php
$doc = DOMDocument::loadHTMLFile("filename.html");
print $doc->saveHTML();

$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
print $doc->saveHTML();
?>

DOMDocument->loadXML()

(no version information, might be only in CVS)

DOMDocument->loadXML() --  Carica un documento XML da una stringa

Descrizione

class DOMDocument {

bool loadXML ( string source )

}

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

Elenco dei parametri

source

Stringa contenente codice XML.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Creazione di un documento

<?php
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();

$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

DOMDocument->normalize()

(no version information, might be only in CVS)

DOMDocument->normalize() --  Normalizza il documento

Descrizione

class DOMDocument {

void normalize ( void )

}

Normalizza il documento.

Valori restituiti

No value is returned.

Vedere anche:

DOMNode->normalize()

DOMDocument->relaxNGValidate()

(no version information, might be only in CVS)

DOMDocument->relaxNGValidate() --  Esegue una validazione relaxNG sul documento

Descrizione

class DOMDocument {

bool relaxNGValidate ( string filename )

}

Esegue una validazione relaxNG sul documento in base allo schema RNG dato.

Elenco dei parametri

filename

File RNG.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMDocument->relaxNGValidateSource()

(no version information, might be only in CVS)

DOMDocument->relaxNGValidateSource() --  Esegue una validazione relaxNG sul documento

Descrizione

class DOMDocument {

bool relaxNGValidateSource ( string source )

}

Esegue una validazione relaxNG sul documento in base alla sorgente RNG data.

Elenco dei parametri

source

Stringa contenente lo schema RNG.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMDocument->save()

(no version information, might be only in CVS)

DOMDocument->save() --  Scarica l'albero XML interno in un file

Descrizione

class DOMDocument {

mixed save ( string filename )

}

Crea un docuemnto XML dalla rappresentazione DOM. Usualmente questa funzione è chiamata dopo la creazione da zero di un nuovo documento DOM come nell'esempio seguente.

Elenco dei parametri

filename

Percorso del file in cui scrivere il documento XML.

Valori restituiti

La funzione restituisce il numero di byte scritti, oppure FALSE in caso di errore.

Esempi

Esempio 1. Salvataggio di un albero DOM in un file

<?php

$doc = new DOMDocument('1.0');
// output formattato
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

DOMDocument->saveHTML()

(no version information, might be only in CVS)

DOMDocument->saveHTML() --  Dumps the internal document into a string using HTML formatting

Descrizione

class DOMDocument {

string saveHTML ( void )

}

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

Valori restituiti

Returns the HTML, or FALSE if an error occurred.

Esempi

Esempio 1. Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

DOMDocument->saveHTMLFile()

(no version information, might be only in CVS)

DOMDocument->saveHTMLFile() --  Dumps the internal document into a file using HTML formatting

Descrizione

class DOMDocument {

int saveHTMLFile ( string filename )

}

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

Elenco dei parametri

filename

The path to the saved HTML document.

Valori restituiti

Returns the number of bytes written or FALSE if an error occurred.

Esempi

Esempio 1. Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

DOMDocument->saveXML()

(no version information, might be only in CVS)

DOMDocument->saveXML() --  Dumps the internal XML tree back into a string

Descrizione

class DOMDocument {

string saveXML ( [DOMNode node [, integer options]] )

}

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

Elenco dei parametri

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Valori restituiti

Returns the XML, or FALSE if an error occurred.

Eccezioni

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

Log delle modifiche

VersioneDescrizione
5.1.0 Added the options parameter

Esempi

Esempio 1. Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Retrieving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Retrieving only the title part:\n";
echo $doc->saveXML($title);

?>

Il precedente esempio visualizzerà:

Retrieving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Retrieving only the title part:
<title>This is the title</title>

DOMDocument->schemaValidate()

(no version information, might be only in CVS)

DOMDocument->schemaValidate() --  Validates a document based on a schema

Descrizione

class DOMDocument {

bool schemaValidate ( string filename )

}

Validates a document based on the given schema file.

Elenco dei parametri

filename

The path to the schema.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMDocument->schemaValidateSource()

(no version information, might be only in CVS)

DOMDocument->schemaValidateSource() --  Validates a document based on a schema

Descrizione

class DOMDocument {

bool schemaValidateSource ( string source )

}

Validates a document based on a schema defined in the given string.

Elenco dei parametri

source

A string containing the schema.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMDocument->validate()

(no version information, might be only in CVS)

DOMDocument->validate() --  Valida il documento in base alla sua DTD

Descrizione

class DOMDocument {

bool validate ( void )

}

Valida il documento in base alla sua DTD.

Si può anche utilizzare la proprietà validateOnParse di DOMDocument per ottenere una validazione DTD.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Se il documenti non ha una DTD collegata, questo metodo restituisce FALSE.

Esempi

Esempio 1. Esempio di validazione con DTD

<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
    echo "Questo documento è valido!\n";
}
?>

Si può anche validare il documento mentre lo si carica:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->Load('book.xml');
?>

DOMDocument->xinclude()

(no version information, might be only in CVS)

DOMDocument->xinclude() --  Sostituisce gli XIncludes in un oggetto DOMDocument

Descrizione

class DOMDocument {

int xinclude ( [int options] )

}

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

Elenco dei parametri

options

parametri libxml. Disponibile da PHP 5.1.0 e Libxml 2.6.7.

Valori restituiti

Restituisce il numero di XIncludes nel documento.

Esempi

Esempio 1. Esempio di uso di DOMDocument->xinclude()

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
 <title>Books of the other guy..</title>
 <para>
  <xi:include href="book.xml">
   <xi:fallback>
    <error>xinclude: book.xml not found</error>
   </xi:fallback>
  </xi:include>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// output formattato
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// carica la stringa XML definita in precedenza
$dom->loadXML($xml);

// sostituisce gli xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

Il precedente esempio visualizzerà qualcosa simile a:

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

DOMElement->__construct()

(no version information, might be only in CVS)

DOMElement->__construct() --  Crea un nuovo oggetto DOMElement

Descrizione

class DOMElement {

__construct ( string name [, string value [, string namespaceURI]] )

}

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

Elenco dei parametri

name

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.

value

Valore dell'elemento.

namespaceURI

URI dello spazio dei nomi, usato per creare l'elemento nello spazio dei nomi indicato.

Esempi

Esempio 1. Creazione di un nuovo DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

DOMElement->getAttribute()

(no version information, might be only in CVS)

DOMElement->getAttribute() -- Restituisce il valore di un attributo

Descrizione

class DOMElement {

string getAttribute ( string name )

}

Restituisce il valore dell'attributo con nome name per il nodo corrente.

Elenco dei parametri

name

Nome dell'attributo.

Valori restituiti

La funzione restituisce il valore dell'attributo oppure una stringa vuota se non si trova alcun attributo con nome name.

DOMElement->getAttributeNode()

(no version information, might be only in CVS)

DOMElement->getAttributeNode() -- Restituisce il nodo attributo

Descrizione

class DOMElement {

DOMAttr getAttributeNode ( string name )

}

Restituisce il nodo attributo con nome name per l'elemento corrente.

Elenco dei parametri

name

Nome dell'attributo.

Valori restituiti

Il nodo attributo.

DOMElement->getAttributeNodeNS()

(no version information, might be only in CVS)

DOMElement->getAttributeNodeNS() --  Restituisce un nodo attributo

Descrizione

class DOMElement {

DOMAttr getAttributeNodeNS ( string namespaceURI, string localName )

}

Restituisce il nodo attributo cone nome localName nello spazio dei nomi namespaceURI per il nodo corrente.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

localName

Nome locale.

Valori restituiti

The attribute node.

DOMElement->getAttributeNS()

(no version information, might be only in CVS)

DOMElement->getAttributeNS() -- Restituisce il valore di un attributo

Descrizione

class DOMElement {

string getAttributeNS ( string namespaceURI, string localName )

}

Restituisce il valore dell'attributo con nome localName nello spazio dei nomi namespaceURI per il nodo corrente.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

localName

Nome locale.

Valori restituiti

Il valore dell'attributo, oppure una stringa vuota nel caso in cui non si trovi un attributo con i dati localName e namespaceURI.

DOMElement->getElementsByTagName()

(no version information, might be only in CVS)

DOMElement->getElementsByTagName() -- Restituisce gli elementi in base al nome del tag

Descrizione

class DOMElement {

DOMNodeList getElementsByTagName ( string name )

}

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

Elenco dei parametri

name

Il nome del tag. Utilizzare "*" per indicare di restituire tutti gli elementi del documento.

Valori restituiti

Questa funzione crea una nuova istanza della classe DOMNodeList contenente tutti gli elementi trovati.

DOMElement->getElementsByTagNameNS()

(no version information, might be only in CVS)

DOMElement->getElementsByTagNameNS() -- Restituisce gli elementi per spazio dei nomi e nome locale

Descrizione

class DOMElement {

DOMNodeList getElementsByTagNameNS ( string namespaceURI, string localName )

}

Questa funzione scarica tutti gli elementi con un dato localName e namespaceURI.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

localName

Nome locale. Utilizzare come nome "*" per restituire tutti gli elementi presenti nell'albero degli elementi.

Valori restituiti

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.

DOMElement->hasAttribute()

(no version information, might be only in CVS)

DOMElement->hasAttribute() -- Verifica se l'attributo esiste

Descrizione

class DOMElement {

bool hasAttribute ( string name )

}

Indica se l'attributo name esiste come menbro dell'elemento.

Elenco dei parametri

name

Nome dell'attributo.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMElement->hasAttributeNS()

(no version information, might be only in CVS)

DOMElement->hasAttributeNS() --  Verifica se esiste l'attributo

Descrizione

class DOMElement {

bool hasAttributeNS ( string namespaceURI, string localName )

}

Indica se l'attributo nello spazio dei nomi namespaceURI con nome localName esiste come membro dell'elemento.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

localName

Nome locale.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMElement->removeAttribute()

(no version information, might be only in CVS)

DOMElement->removeAttribute() -- Rimuove l'attributo

Descrizione

class DOMElement {

bool removeAttribute ( string name )

}

Rimuove l'attributo name dall'elemento.

Elenco dei parametri

name

Nome dell'attributo.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo non può essere modificato (in sola lettura).

DOMElement->removeAttributeNode()

(no version information, might be only in CVS)

DOMElement->removeAttributeNode() -- Rimuove gli attributi

Descrizione

class DOMElement {

bool removeAttributeNode ( DOMAttr oldnode )

}

Rimuove l'attributo oldnode dall'elemento.

Elenco dei parametri

oldnode

Nodo attributo.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

DOM_NOT_FOUND_ERROR

Generato se oldnode non è un attributo dell'elemento.

DOMElement->removeAttributeNS()

(no version information, might be only in CVS)

DOMElement->removeAttributeNS() -- Rimuove gli attributi

Descrizione

class DOMElement {

bool removeAttributeNS ( string namespaceURI, string localName )

}

Rimuove l'attributo localName nello spazio dei nomi namespaceURI dall'elemento.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

localName

Nome locale.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

DOMElement->setAttribute()

(no version information, might be only in CVS)

DOMElement->setAttribute() -- Aggiunge un nuovo attributo

Descrizione

class DOMElement {

bool setAttribute ( string name, string value )

}

Imposta l'attributo con nome name al dato valore. Se l'attributo non esiste lo crea.

Elenco dei parametri

name

Nome dell'attributo.

value

Valore dell'attributo.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

Esempi

Esempio 1. Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

DOMElement->setAttributeNode()

(no version information, might be only in CVS)

DOMElement->setAttributeNode() -- Aggiunge un nuovo nodo attributo all'elemento

Descrizione

class DOMElement {

DOMAttr setAttributeNode ( DOMAttr attr )

}

Aggiunge un nuovo nodo attributo attr all'elemento.

Elenco dei parametri

attr

Nodo attributo.

Valori restituiti

Restituisce il vecchio nodo se questo viene sostituito oppure NULL.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

DOMElement->setAttributeNodeNS()

(no version information, might be only in CVS)

DOMElement->setAttributeNodeNS() -- Aggiunge un nuovo nodo attributo all'elemento

Descrizione

class DOMElement {

DOMAttr setAttributeNodeNS ( DOMAttr attr )

}

Aggiunge un nuovo nodo attr all'elemento.

Elenco dei parametri

name

Nodo attributo.

Valori restituiti

Restituisce il vecchio nodo se l'attributo viene sostituito.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

DOMElement->setAttributeNS()

(no version information, might be only in CVS)

DOMElement->setAttributeNS() -- Aggiunge un nuovo attributo

Descrizione

class DOMElement {

void setAttributeNS ( string namespaceURI, string qualifiedName, string value )

}

Imposta un attributo di nome name nello spazio dei nomi namespaceURI al valore dato. Se l'attributo non esiste viene creato.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

qualifiedName

Nome qualificato dell'attributo, nella forma prefisso:nometag.

value

Valore dell'attributo.

Valori restituiti

No value is returned.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

DOM_NAMESPACE_ERR

Generato se qualifiedName è un nome qualificato malformato, oppure se qualifiedName ha un prefisso, ma namespaceURI è NULL.

DOMAttr->__construct()

(no version information, might be only in CVS)

DOMAttr->__construct() --  Crea un nuovo oggetto DOMEntityReference

Descrizione

class DOMEntityReference {

__construct ( string name )

}

Crea un nuovo oggetto DOMEntityReference.

Elenco dei parametri

name

Nome dell'entità

Esempi

Esempio 1. Creazione di un nuovo DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

DOMImplementation->__construct()

(no version information, might be only in CVS)

DOMImplementation->__construct() --  Crea un nuovo oggetto DOMImplementation

Descrizione

class DOMImplementation {

__construct ( (void); )

}

Crea un nuovo oggetto DOMImplementation.

DOMImplementation->createDocument()

(no version information, might be only in CVS)

DOMImplementation->createDocument() --  Crea un oggetto DOMDocument del tipo indicato con il suo elemento documento

Descrizione

class DOMImplementation {

DOMDocument createDocument ( [string namespaceURI [, string qualifiedName [, DOMDocumentType doctype]]] )

}

Crea un oggetto DOMDocument del tipo specificato, con l'elemento documento.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi dell'elemento documento da creare.

qualifiedName

Nome qualificato dell'elemento documento da creare.

doctype

Tipo del documento da creare oppure NULL.

Valori restituiti

Restituisce un nuovo oggetto DOMDocument. Se namespaceURI, qualifiedName, e doctype sono a null, l'oggetto DOMDocument restituito è vuoto, cioè privo dell'elemento documento.

Eccezioni

DOM_WRONG_DOCUMENT_ERR

Generato se doctype è già utilizzato in un documento differente oppure è stato creato con una differente implementazione.

DOM_NAMESPACE_ERR

Generato se esiste un errore nello spazio dei nomi indicato da namespaceURI e qualifiedName.

DOMImplementation->createDocumentType()

(no version information, might be only in CVS)

DOMImplementation->createDocumentType() --  Crea un oggetto DOMDocumentType vuoto

Descrizione

class DOMImplementation {

DOMDocumentType createDocumentType ( [string qualifiedName [, string publicId [, string systemId]]] )

}

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

Elenco dei parametri

qualifiedName

Nome qualificato del tipo documento da creare.

publicId

Identificatore pubblico esterno.

systemId

Identificatore di sistema esterno.

Valori restituiti

Un nuovo nodo DOMDocumentType con il suo ownerDocument impostato a NULL.

Esempi

Esempio 1. Creazione di un documento con una DTD collegata

<?php

// Istanza della classe DOMImplementation
$imp = new DOMImplementation;

// Crea un'istanza di DOMDocumentType
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Crea un'istanza di DOMDocument
$dom = $imp->createDocument("", "", $dtd);

// Imposta altre opzioni
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Crea un elemento vuoto
$element = $dom->createElement('graph');

// Aggiunge l'elemento
$dom->appendChild($element);

// Recupera e scrive il documento
echo $dom->saveXML();

?>

Il precedente esempio visualizzerà:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Eccezioni

DOM_NAMESPACE_ERR

Generato se vi è un errore nello spazio dei nomi indicato da qualifiedName.

DOMImplementation->hasFeature()

(no version information, might be only in CVS)

DOMImplementation->hasFeature() --  Verifica se l'implementazione DOM ha una specifica caratteristica

Descrizione

class DOMImplementation {

bool hasFeature ( string feature, string version )

}

Verifica se l'implementazione DOM ha una specifica feature.

Si può avere l'eleneco di tutte le caratteristiche alla sezione Conformance delle specifiche DOM.

Elenco dei parametri

feature

Caratteristica da verificare.

version

Numero di versione della feature da verificare. Nel livello 2 questo parametro può valere 2.0 o 1.0.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Verifica dell'implementazione DOM

<?php

$features = array(
  'Core'           => 'Core module',
  'XML'            => 'XML module',
  'HTML'           => 'HTML module',
  'Views'          => 'Views module',
  'Stylesheets'    => 'Style Sheets module',
  'CSS'            => 'CSS module',
  'CSS2'           => 'CSS2 module',
  'Events'         => 'Events module',
  'UIEvents'       => 'User interface Events module',
  'MouseEvents'    => 'Mouse Events module',
  'MutationEvents' => 'Mutation Events module',
  'HTMLEvents'     => 'HTML Events module',
  'Range'          => 'Range module',
  'Traversal'      => 'Traversal module'
);
               
foreach ($features as $key => $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Has feature $name\n";
  } else {
    echo "Missing feature $name\n";
  }
}

?>

Vedere anche:

DOMNode->isSupported()

DOMNamedNodeMap->getNamedItem()

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItem() --  Recupera un nodo indicandone il nome

Descrizione

class DOMNamedNodeMap {

DOMNode getNamedItem ( string name )

}

Recupera il nodo indicato da nodeName.

Elenco dei parametri

name

Il nome del nodo da cercare.

Valori restituiti

Il nodo (di qualsiasi tipo) con il nome richiesto, oppure NULL se non viene trovato.

DOMNamedNodeMap->getNamedItemNS()

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItemNS() --  Recupera un nodo indicando il nome locale e l'URI dello spazio dei nomi

Descrizione

class DOMNamedNodeMap {

DOMNode getNamedItemNS ( string namespaceURI, string localName )

}

Recupera il nodo indicato da localName e namespaceURI.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi del nodo da cercare

localName

Nome locale del nodo da cercare.

Valori restituiti

Un nodo (di qualsiasi tipo) con il nome locale ed l'URI dello spazio dei nomi richiesti, oppure NULL se non viene trovato nulla.

DOMNamedNodeMap->item()

(no version information, might be only in CVS)

DOMNamedNodeMap->item() -- Recupera un nodo tramite il suo indice

Descrizione

class DOMNamedNodeMap {

DOMNode item ( int index )

}

Recupera un nodo tramite l'indice index all'interno dell'oggetto DOMNamedNodeMap.

Elenco dei parametri

index

Indice all'interno della tabella.

Valori restituiti

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

DOMNode->appendChild()

(no version information, might be only in CVS)

DOMNode->appendChild() --  Aggiunge un nuovo nodo figlio alla fine dei nodi figli

Descrizione

class DOMNode {

DOMNode appendChild ( DOMNode newnode )

}

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

Elenco dei parametri

newnode

Il nodo figlio da aggiungere.

Valori restituiti

Il nodo aggiunto.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se questo nodo è in sola lettura, oppure se il nodo genitore del nodo da inserire è in sola lettura.

DOM_HIERARCHY_REQUEST_ERR

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.

DOM_WRONG_DOCUMENT_ERR

Generato se newnode è stato creato in un documento differente rispetto al nodo che crea questo.

Esempi

Nel seguente esempio si aggiunge un nuovo nodo elemento ad un documento.

Esempio 1. Aggiunta di un nodo figlio

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

DOMNode->cloneNode()

(no version information, might be only in CVS)

DOMNode->cloneNode() --  Clona un nodo

Descrizione

class DOMNode {

DOMNode cloneNode ( [bool deep] )

}

Crea una copia di un nodo.

Elenco dei parametri

deep

Indica se occorre copiare tutti i nodi sottostanti. Questo parametro, opzionale, ha come default FALSE.

Valori restituiti

Il nodo clonato.

DOMNode->hasAttributes()

(no version information, might be only in CVS)

DOMNode->hasAttributes() --  Verifica se un nodo ha degli attributi

Descrizione

class DOMNode {

bool hasAttributes ( void )

}

Questa funzione verifica se un nodo ha degli attributi. Il nodo verificato deve essere di tipo XML_ELEMENT_NODE.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMNode->hasChildNodes()

(no version information, might be only in CVS)

DOMNode->hasChildNodes() --  Verifica se un nodo ha nodi figli

Descrizione

class DOMNode {

bool hasChildNodes ( void )

}

Questa funzione verifica se un nodo ha nodi figli.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMNode->insertBefore()

(no version information, might be only in CVS)

DOMNode->insertBefore() --  Aggiunge un nuovo nodo figlio prima del riferimento

Descrizione

class DOMNode {

DOMNode insertBefore ( DOMNode newnode [, DOMNode refnode] )

}

Questa funzione inserisce un nuovo nodo prima del nodo di riferimento. Se si prevede di fare ulteriori aggiunte al nodo aggiunto, utilizzare il nodo restituito.

Elenco dei parametri

newnode

Il nuovo nodo.

refnode

Nodo di riferimento. Se non viene fornito, newnode viene accodato ai nodi figli.

Valori restituiti

Il nodo inserito.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura o se il precedente nodo padre del nodo da aggiungere è in sola lettura.

DOM_HIERARCHY_REQUEST_ERR

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.

DOM_WRONG_DOCUMENT_ERR

Generato se newnode è stato creato in un docuemnto differente rispetto al documento in cui è sttao creato questo nodo.

DOM_NOT_FOUND

Generato se refnode non è un nodo figlio di questo nodo.

DOMNode->isSameNode()

(no version information, might be only in CVS)

DOMNode->isSameNode() --  Indica se due nodi sono il medesimo nodo

Descrizione

class DOMNode {

bool isSameNode ( DOMNode node )

}

Questa funzione indica se due nodi sono il medesimo nodo. Il confronto NON è basato sul contenuto.

Elenco dei parametri

node

Il nodo confrontato.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMNode->isSupported()

(no version information, might be only in CVS)

DOMNode->isSupported() --  Verifica se una caratteristica è supportata dalla versione indicata

Descrizione

class DOMNode {

bool isSupported ( string feature, string version )

}

Verifica se una feature è supportata dalla version indicata.

Elenco dei parametri

feature

Caratteristica da verificare. Vedere l'esempio di DOMImplementation->hasFeature() per avere l'elenco delle caratteristiche.

version

Numero di versione della feature da verificare.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMNode->lookupNamespaceURI()

(no version information, might be only in CVS)

DOMNode->lookupNamespaceURI() --  Restituisce l'URI dello spazio dei nomi in base al prefisso

Descrizione

class DOMNode {

string lookupNamespaceURI ( string prefix )

}

Restituisce l'URI dello spazio dei nomi del nodo in base al prefisso prefix.

Elenco dei parametri

prefix

Prefisso dello spazio dei nomi

Valori restituiti

URI dello spazio dei nomi del nodo.

DOMNode->lookupPrefix()

(no version information, might be only in CVS)

DOMNode->lookupPrefix() --  Resituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomi

Descrizione

class DOMNode {

string lookupPrefix ( string namespaceURI )

}

Resituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomi.

Elenco dei parametri

namespaceURI

URI dello spazio dei nomi.

Valori restituiti

Il prefisso dello spazio dei nomi.

DOMNode->normalize()

(no version information, might be only in CVS)

DOMNode->normalize() --  Normalizza un nodo

Descrizione

class DOMNode {

void normalize ( void )

}

Normalizza il nodo.

Valori restituiti

No value is returned.

DOMNode->removeChild()

(no version information, might be only in CVS)

DOMNode->removeChild() --  Rimuove un nodo figlio dalla lista dei nodi figli

Descrizione

class DOMNode {

DOMNode removeChild ( DOMNode oldnode )

}

Questa funzione rimuove un nodo figlio dalla lista dei nodi figli.

Elenco dei parametri

oldnode

Il nodo rimosso.

Valori restituiti

Se si riesce a rimuovere il nodo figlio, la funzione restituisce il vecchio nodo figlio.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se il nodo è in sola lettura.

DOM_NOT_FOUND

Generato se oldnode non è un figlio di questo nodo.

Esempi

Nel seguente esempio si rimuoverà il nodo 'chapter' dal nostro documento XML.

Esempio 1. Rimozione di un nodo figlio

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// Cerchiamo il nodo e lo rimuoviamo
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

Il precedente esempio visualizzerà:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" 
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>
 
</book>

DOMNode->replaceChild()

(no version information, might be only in CVS)

DOMNode->replaceChild() --  Sostituisce un nodo figlio

Descrizione

class DOMNode {

DOMNode replaceChild ( DOMNode newnode, DOMNode oldnode )

}

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.

Elenco dei parametri

newnode

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

oldnode

Il vecchio nodo.

Valori restituiti

Il vecchio nodo oppure FALSE in caso di errore.

Eccezioni

DOM_NO_MODIFICATION_ALLOWED_ERR

Generato se questo nodo è in sola lettura oppure se il precdente padre del nodo da inserire è in sola lettura.

DOM_HIERARCHY_REQUEST_ERR

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.

DOM_WRONG_DOCUMENT_ERR

Generato se newnode è stato creato in un docuemnto differente rispetto al documento in cui è stato creato il nodo.

DOM_NOT_FOUND

Generato se oldnode non è figlio del nodo.

DOMNodelist->item()

(no version information, might be only in CVS)

DOMNodelist->item() --  Recupera il nodo indicato dall'indice

Descrizione

class DOMNodeList {

DOMNode item ( int index )

}

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

Elenco dei parametri

index

Indice del nodo nella collezione.

Valori restituiti

Il nodo alla posizione index in DOMNodeList, oppure NULL se non è un indice valido.

Esempi

Esempio 1. Attraversamento di tutti gli elementi di una tabella

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}

?>

Oppure si può utilizzare foreach, che è molto pratico:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

Il precedente esempio visualizzerà:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

DOMProcessingInstruction->__construct()

(no version information, might be only in CVS)

DOMProcessingInstruction->__construct() --  Crea un nuovo oggetto DOMProcessingInstruction

Descrizione

class DOMProcessingInstruction {

__construct ( string name [, string value] )

}

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

Elenco dei parametri

name

Nome del tag dell'istruzione di processamento.

value

Valore dell'istruzione di processamento.

Esempi

Esempio 1. Creazione di un nuovo DOMProcessingInstruction

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?>
<html><body><?php echo "Hello World"; ?></body></html> */

?>

DOMText->__construct()

(no version information, might be only in CVS)

DOMText->__construct() --  Crea un nuovo oggetto DOMText

Descrizione

class DOMText {

__construct ( [string value] )

}

Crea un nuovo oggetto DOMText.

Elenco dei parametri

value

Valore del nodo di testo. Se non fornito, sarà creato un nodo con il testo vuoto.

Esempi

Esempio 1. Creazione di un nuovo DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

DOMText->isWhitespaceInElementContent()

(no version information, might be only in CVS)

DOMText->isWhitespaceInElementContent() --  Indica se questo nodo di testo contiene spazi

Descrizione

class DOMText {

bool isWhitespaceInElementContent ( void )

}

Indica se questo nodo di testo contiene spazi. Si determina se un nodo di testo contiene spazi durante la fase di caricamento del documento.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

DOMText->splitText()

(no version information, might be only in CVS)

DOMText->splitText() --  Spezza il nodo in due all'offset specificato

Descrizione

class DOMText {

DOMText splitText ( int offset )

}

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

Elenco dei parametri

offset

Offset al quale dividere, a partire da 0.

Valori restituiti

Il nuovo nodo, del medesimo tipo, avrà tutto il contenuto a partire da offset.

DOMXPath->__construct()

(no version information, might be only in CVS)

DOMXPath->__construct() --  Crea un nuovo oggetto DOMXPath

Descrizione

class DOMXPath {

__construct ( DOMDocument doc )

}

Crea un nuovo oggetto DOMXPath.

Elenco dei parametri

doc

L'oggetto DOMDocument associato a DOMXPath.

DOMXPath->evaluate()

(no version information, might be only in CVS)

DOMXPath->evaluate() --  Valuta l'espressione XPath data e restituisce un risultato se possibile

Descrizione

class DOMXPath {

mixed evaluate ( string expression [, DOMNode contextnode] )

}

Esegue l'espressione XPath data e restituisce un risultato se possibile

Elenco dei parametri

expression

L'espressione XPath da eseguire.

contextnode

Il parametro opzinale contextnode serve per indicare di eseguire query XPath relative. Per default le query sono relative all'elemento radice.

Valori restituiti

Restituisce un risultato oppure un oggetto DOMNodeList contenente tutti i nodi che soddisfano la query XPath .

Esempi

Esempio 1. Ottenere il numero dei libri inglesi

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// query relativa ai nodi tbody
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

Il precedente esempio visualizzerà:

There are 2 english books

Vedere anche:

DOMXPath->query()

DOMXPath->query()

(no version information, might be only in CVS)

DOMXPath->query() --  Valuta l'espressione XPath

Descrizione

class DOMXPath {

DOMNodeList query ( string expression [, DOMNode contextnode] )

}

Esegue la query XPath data.

Elenco dei parametri

expression

La query XPath da eseguire.

contextnode

Il parametro opzinale contextnode serve per indicare di eseguire query XPath relative. Per default le query sono relative all'elemento radice.

Valori restituiti

Restituisce un oggetto DOMNodeList contenente tutti i nodi che soddisfano la condizione expression. Qualsiasi espressione che non restituisce nodi creerà un DOMNodeList vuoto.

Esempi

Esempio 1. Ottenere il numero dei libri inglesi

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->Load('book.xml');

$xpath = new DOMXPath($doc);

// Partiamo dell'elemento radice
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

Il precedente esempio visualizzerà:

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

Possiamo utilizzare il parametro contextnode per ridurre l'espressione:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// query relativa ai nodi tbody
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

Vedere anche:

DOMXPath->evaluate()

DOMXPath->registerNamespace()

(no version information, might be only in CVS)

DOMXPath->registerNamespace() --  Registra lo spazio dei nomi nell'oggetto DOMXpath

Descrizione

class DOMXPath {

bool registerNamespace ( string prefix, string namespaceURI )

}

Registra lo spazio dei nomi namespaceURI e prefix nell'oggetto DOMXpath.

Elenco dei parametri

prefix

Il prefisso.

namespaceURI

URI dello spazio dei nomi.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

dom_import_simplexml

(PHP 5)

dom_import_simplexml --  Ottiene un'oggetto DOMElement da un'oggetto SimpleXMLElement

Descrizione

DOMElement dom_import_simplexml ( SimpleXMLElement node )

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.

Elenco dei parametri

node

Il nodo SimpleXMLElement.

Valori restituiti

Il nodo DOMElement aggiunto oppure FALSE in caso di errore.

Esempi

Esempio 1. Importare SimpleXML nel DOM con dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
    echo 'Error while parsing the document';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error while converting XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

Vedere anche:

simplexml_import_dom()

XXXI. Funzioni DOM XML

Introduzione

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.

Nota: Questo modulo non è più considerato sperimentale. Tuttavia non sarà rilasciato con PHP 5, e sarà solo distribuito con PHP 4. Se si ha bisogno del supporto DOM XML in PHP 5, si può utilizzare il modulo DOM. Questa estensione domxml non è compatibile con DOM.


Requisiti

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.


Installazione

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.


Funzioni deprecate

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 funzioneNuova funzione
xmldocdomxml_open_mem()
xmldocfiledomxml_open_file()
domxml_new_xmldocdomxml_new_doc()
domxml_dump_memDomDocument_dump_mem()
domxml_dump_mem_fileDomDocument_dump_file()
DomDocument_dump_mem_fileDomDocument_dump_file()
DomDocument_add_rootDomDocument_create_element() seguita da DomNode_append_child()
DomDocument_dtdDomDocument_doctype()
DomDocument_rootDomDocument_document_element()
DomDocument_childrenDomNode_child_nodes()
DomDocument_imported_nodeNessun sostituto.
DomNode_add_childCreare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child().
DomNode_childrenDomNode_child_nodes()
DomNode_parentDomNode_parent_node()
DomNode_new_childCreare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child().
DomNode_get_contentIl contenuto è semplicemente un nodo di testo ed è accessibile tramite DomNode_child_nodes().
DomNode_set_contentIl contenuto è semplicemente un nodo di testo e può essere aggiunto con DomNode_append_child().


Costanti predefinite

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

CostanteValoreDescrizione
XML_ELEMENT_NODE (integer) 1Il nodo è un elemento
XML_ATTRIBUTE_NODE (integer) 2Il nodo è un attributo
XML_TEXT_NODE (integer) 3Il nodo è un segmento di testo
XML_CDATA_SECTION_NODE (integer) 4 
XML_ENTITY_REF_NODE (integer) 5 
XML_ENTITY_NODE (integer) 6Il nodo è un'entità come, ad esempio, &nbsp;
XML_PI_NODE (integer) 7Il nodo è una istruzione di processamento
XML_COMMENT_NODE (integer) 8Il nodo è un commento
XML_DOCUMENT_NODE (integer) 9Il 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)   

Classi

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 classeClasse genitrice
DomAttributeDomNode
DomCDataDomNode
DomCommentDomCData : DomNode
DomDocumentDomNode
DomDocumentTypeDomNode
DomElementDomNode
DomEntityDomNode
DomEntityReferenceDomNode
DomProcessingInstructionDomNode
DomTextDomCData : DomNode
ParserAttualmente chiamata DomParser
XPathContext 

Tabella 4. Classe DomDocument (DomDocument : DomNode)

MetodiFunzioniNote
doctypeDomDocument_doctype() 
document_elementDomDocument_document_element() 
create_elementDomDocument_create_element() 
create_text_nodeDomDocument_create_text_node() 
create_commentDomDocument_create_comment() 
create_cdata_sectionDomDocument_create_cdata_section() 
create_processing_instructionDomDocument_create_processing_instruction() 
create_attributeDomDocument_create_attribute() 
create_entity_referenceDomDocument_create_entity_reference() 
get_elements_by_tagnameDomDocument_get_elements_by_tagname() 
get_element_by_idDomDocument_get_element_by_id() 
dump_memDomDocument_dump_mem()non standard DOM
dump_fileDomDocument_dump_file()non standard DOM
html_dump_memDomDocument_html_dump_mem()non standard DOM
xpath_initxpath_initnon standard DOM
xpath_new_contextxpath_new_contextnon standard DOM
xptr_new_contextxptr_new_contextnon standard DOM

Tabella 5. Classe DomElement (DomElement : DomNode)

MetodoFunzioniNote
tagnameDomElement_tagname() 
get_attributeDomElement_get_attribute() 
set_attributeDomElement_set_attribute() 
remove_attributeDomElement_remove_attribute() 
get_attribute_nodeDomElement_get_attribute_node() 
get_elements_by_tagnameDomElement_get_elements_by_tagname() 
has_attributeDomElement_has_attribute() 

Tabella 7. Classe DomAttribute (DomAttribute : DomNode)

Metodo Note
nameDomAttribute_name() 
valueDomAttribute_value() 
specifiedDomAttribute_specified() 

Tabella 8. Classe DomProcessingInstruction (DomProcessingInstruction : DomNode)

MetodoFunzioneNote
targetDomProcessingInstruction_target() 
dataDomProcessingInstruction_data() 

Tabella 9. Classe Parser class

MetodoFunzioneNote
add_chunkParser_add_chunk() 
endParser_end() 

Tabella 10. Classe XPathContext

MetodoFunzioneNote
evalXPathContext_eval() 
eval_expressionXPathContext_eval_expression() 
register_nsXPathContext_register_ns() 

Tabella 11. Classe DomDocumentType (DomDocumentType : DomNode)

MetodoFunzioneNote
nameDomDocumentType_name() 
entitiesDomDocumentType_entities() 
notationsDomDocumentType_notations() 
public_idDomDocumentType_public_id() 
system_idDomDocumentType_system_id() 
internal_subsetDomDocumentType_internal_subset() 

La classe DomDtd è derivata da DomNode. Mentre DomComment è derivata da DomCData


Esempi

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

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  sp;
  <!-- comment -->
  <informaltable ID='findme' language='&sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

Sommario
DomAttribute->name --  Restituisce il nome di un attributo
DomAttribute->set_value --  Sets the value of an attribute
DomAttribute->specified --  Verifica se l'attributo è presente
DomAttribute->value --  Restituisce il valore di un attributo
DomDocument->add_root --  Aggiunge un nodo radice [deprecated]
DomDocument->create_attribute --  Crea un nuovo attributo
DomDocument->create_cdata_section -- Crea un nuovo nodo cdata
DomDocument->create_comment -- Crea un nodo commento
DomDocument->create_element_ns --  Crea un nodo elemento con il relativo spazio dei nomi
DomDocument->create_element -- Crea un nodo elemento
DomDocument->create_entity_reference -- 
DomDocument->create_processing_instruction -- Crea un nuovo nodo PI
DomDocument->create_text_node -- Crea un nodo di testo
DomDocument->doctype --  Restituisce il tipo di documento
DomDocument->document_element --  Restituisce il nodo radice
DomDocument->dump_file --  Scarica in un file l'albero XML interno
DomDocument->dump_mem --  Scarica in una stringa la struttura XML interna
DomDocument->get_element_by_id --  Ricerca di un elemento per id
DomDocument->get_elements_by_tagname --  Restituisce un elemento dato il tag
DomDocument->html_dump_mem --  Scarica la struttura XML interna in una stringa come HTML
DomDocument->xinclude --  Sostituisce gli XIncludes in un oggetto DomDocument
DomDocumentType->entities --  Restituisce l'elenco delle entità
DomDocumentType->internal_subset --  Restituisce un subset interno
DomDocumentType->name --  Restituisce il nome del tipo documento
DomDocumentType->notations --  Restituisce la lista delle notazioni
DomDocumentType->public_id --  Restituisce l'identificatore pubblico del tipo documento
DomDocumentType->system_id --  Restituisce l'identificativo di sistema del tipo documento
DomElement->get_attribute_node --  Restituisce il nodo dell'attributo dato
DomElement->get_attribute --  Restituisce il valore di un attributo
DomElement->get_elements_by_tagname --  Restituisce l'elemento con il tag dato
DomElement->has_attribute --  Verifica l'esistenza dell'attributo
DomElement->remove_attribute --  Rimuove un attributo
DomElement->set_attribute --  Valorizza un attributo
DomElement->tagname --  Restituisce il nome dell'elemento corrente
DomNode->add_namespace --  Aggiunge la dichiarazione dello spazio dei nomi ad un nodo
DomNode->append_child --  Accoda un nuovo figlio
DomNode->append_sibling --  Aggiunge un nodo fratello
DomNode->attributes --  Restituisce la lista degli attributi
DomNode->child_nodes --  Restituisce i figli di un nodo
DomNode->clone_node --  Clona un nodo
DomNode->dump_node --  Scarica un singolo nodo
DomNode->first_child --  Restituisce il primo nodo figlio
DomNode->get_content --  Restituisce il contenuto del nodo
DomNode->has_attributes --  Verifica se il nodo ha attributi
DomNode->has_child_nodes --  Verifica se esistono nodi figlio
DomNode->insert_before --  Inserisce un nuovo nodo come figlio
DomNode->is_blank_node --  Verifica se il nodo è vuoto
DomNode->last_child --  Restituisce l'ultimo nodo figlio del nodo
DomNode->next_sibling --  Restituisce il successivo fratello del nodo
DomNode->node_name --  Restituisce il nome del nodo
DomNode->node_type --  Restituisce il tipo di nodo
DomNode->node_value --  Restituisce il valore di un nodo
DomNode->owner_document --  Restituisce il documento a cui appartiene questo nodo
DomNode->parent_node --  Restituisce il genitore del nodo
DomNode->prefix --  Restituisce lo spazio dei nomi prefisso al nodo
DomNode->previous_sibling --  Restituisce il nodo fratello precedente
DomNode->remove_child --  Rimuove un nodo figlio dalla lista dei figli
DomNode->replace_child --  Sostituisce un nodo figlio
DomNode->replace_node --  Sostituisce il nodo
DomNode->set_content --  Imposta il contenuto del nodo
DomNode->set_name --  Imposta il nome del nodo
DomNode->set_namespace --  Imposta lo spazio dei nomi del nodo
DomNode->unlink_node --  Rimuove il nodo
DomProcessingInstruction->data --  Restituisce i dati di un nodo PI
DomProcessingInstruction->target --  Restituisce il target di un nodo PI
DomXsltStylesheet->process --  Applica una trasformazione XSLT ad un oggetto DomDocument
DomXsltStylesheet->result_dump_file --  Scarica il risultato di una trasformazione XSLT in un file
DomXsltStylesheet->result_dump_mem --  Scarica il risultato di una trasformazione XSLT in una stringa
domxml_new_doc --  Crea un nuovo documento XML vuoto
domxml_open_file -- Crea un oggetto DOM da un file XML
domxml_open_mem -- Crea un oggetto DOM da un documento XML
domxml_version --  restituisce la versione della libreria XML
domxml_xmltree --  Crea un albero di oggetti PHP da un documento XML
domxml_xslt_stylesheet_doc --  Crea un oggetto DomXsltStylesheet da un oggetto DomDocument.
domxml_xslt_stylesheet_file --  Crea un oggetto DomXsltStylesheet da un file con un documento XSL
domxml_xslt_stylesheet --  Crea un oggetto DomXsltStylesheet da un documento XML contenuto in una stringa
domxml_xslt_version --  Gets the XSLT library version
xpath_eval_expression --  Valuta il percorso XPath nella stringa data
xpath_eval --  Valuta il percorso XPath nella stringa data
xpath_new_context --  Crea un nuovo contesto xpath
xpath_register_ns_auto --  Register the given namespace in the passed XPath context
xpath_register_ns --  Register the given namespace in the passed XPath context
xptr_eval --  Valuta il percorso della locazione XPtr nella stringa data
xptr_new_context --  Crea un nuovo contesto XPath

DomAttribute->name

(no version information, might be only in CVS)

DomAttribute->name --  Restituisce il nome di un attributo

Descrizione

string DomAttribute->name ( void )

La funzione restituisce il nome di un attributo.

Vedere anche domattribute_value() per un esempio.

DomAttribute->set_value

(no version information, might be only in CVS)

DomAttribute->set_value --  Sets the value of an attribute

Descrizione

class DomAttribute {

bool set_value ( string content )

}

This function sets the value of an attribute.

Elenco dei parametri

content

The new value.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Migrating to PHP 5

Set the value property of DOMAttr.

Vedere anche:

DomAttribute->value

DomAttribute->specified

(no version information, might be only in CVS)

DomAttribute->specified --  Verifica se l'attributo è presente

Descrizione

bool DomAttribute->specified ( void )

Rifarsi allo standard DOM per una descrizione dettagliata.

DomAttribute->value

(no version information, might be only in CVS)

DomAttribute->value --  Restituisce il valore di un attributo

Descrizione

mixed DomAttribute->value ( void )

Questa funzione restituisce il valore di un attributo.

Esempio 1. Ottenere tutti gli attributi di un nodo

<?php
 
include("example.inc");
 
if (!$dom = domxml_open_mem($xmlstr)) {
     echo "Error while parsing the document\n";
     exit;
}
 
$root = $dom->document_element();
$attrs = $root->attributes();
 
echo 'Attributes of ' . $root->node_name() . "\n";
foreach ($attrs as $attribute) {
     echo ' - ' . $attribute->name . ' : ' . $attribute->value . "\n";
}
 
?>

Il precedente esempio visualizzerà:

Attributes of chapter
 - language : en

Vedere anche domattribute_name().

DomDocument->add_root

(no version information, might be only in CVS)

DomDocument->add_root --  Aggiunge un nodo radice [deprecated]

Descrizione

domelement DomDocument->add_root ( string nome )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. Creazione dell'intestazione di un semplice documento HTML

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("html");
$head = $root->new_child("head", "");
$head->new_child("title", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

DomDocument->create_attribute

(no version information, might be only in CVS)

DomDocument->create_attribute --  Crea un nuovo attributo

Descrizione

domattribute DomDocument->create_attribute ( string nome, string valore )

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

DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Crea un nuovo nodo cdata

Descrizione

domcdata DomDocument->create_cdata_section ( string contenuto )

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

DomDocument->create_comment

(no version information, might be only in CVS)

DomDocument->create_comment -- Crea un nodo commento

Descrizione

domcomment DomDocument->create_comment ( string contenuto )

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

DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns --  Crea un nodo elemento con il relativo spazio dei nomi

Descrizione

domelement DomDocument->create_element_ns ( string uri, string nome [, string prefisso] )

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

DomDocument->create_element

(no version information, might be only in CVS)

DomDocument->create_element -- Crea un nodo elemento

Descrizione

domelement DomDocument->create_element ( string nome )

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

DomDocument->create_entity_reference

(no version information, might be only in CVS)

DomDocument->create_entity_reference -- 

Descrizione

domentityreference DomDocument->create_entity_reference ( string contenuto )

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

DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Crea un nuovo nodo PI

Descrizione

domprocessinginstruction DomDocument->create_processing_instruction ( string contenuto )

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

DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Crea un nodo di testo

Descrizione

domtext DomDocument->create_text_node ( string contenuto )

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

DomDocument->doctype

(no version information, might be only in CVS)

DomDocument->doctype --  Restituisce il tipo di documento

Descrizione

domdocumenttype DomDocument->doctype ( void )

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

DomDocument->document_element

(no version information, might be only in CVS)

DomDocument->document_element --  Restituisce il nodo radice

Descrizione

domelement DomDocument->document_element ( void )

Questa 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

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Errore nel parsing del documento\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

Il precedente esempio visualizzerà:

domelement Object
(
    [type] => 1
    [tagname] => chapter
    [0] => 6
    [1] => 137960648
)

DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file --  Scarica in un file l'albero XML interno

Descrizione

string DomDocument->dump_file ( string nomefile [, bool compressione [, bool formato]] )

La 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

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

Vedere anche domdocument_dump_mem() e domdocument_html_dump_mem().

DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem --  Scarica in una stringa la struttura XML interna

Descrizione

string DomDocument->dump_mem ( [bool formato [, string codifica]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

Nota: Il primo parametro è stato inserito nella versione 4.3.0 di PHP.

Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().

DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id --  Ricerca di un elemento per id

Descrizione

domelement DomDocument->get_element_by_id ( string id )

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

DomDocument->get_elements_by_tagname

(no version information, might be only in CVS)

DomDocument->get_elements_by_tagname --  Restituisce un elemento dato il tag

Descrizione

array DomDocument->get_elements_by_tagname ( string nome )

Vedere anche domdocument_add_root()

DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem --  Scarica la struttura XML interna in una stringa come HTML

Descrizione

string DomDocument->html_dump_mem ( void )

La 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

<?php

// Crea il documento
$doc = domxml_new_doc("1.0");

$root = $doc->create_element("html");
$root = $doc->append_child($root);
$head = $doc->create_element("head");
$head = $root->append_child($head);
$title = $doc->create_element("title");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo $doc->html_dump_mem();
?>

Il precedente esempio visualizzerà:

<html><head><title>This is the title</title></head></html>

Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().

DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude --  Sostituisce gli XIncludes in un oggetto DomDocument

Descrizione

int DomDocument->xinclude ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

// include.xml contains :
// <child>test</child>
	 
$xml = '<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="include.xml">
    <xi:fallback>
      <error>xinclude: include.xml not found</error>
    </xi:fallback>
  </xi:include>
</root>';
 
$domxml = domxml_open_mem($xml);
$domxml->xinclude();
	 
echo $domxml->dump_mem();
	 
?>

Il precedente esempio visualizzerà:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <child>test</child>
</root>

Se include.xml non esiste si avrà::

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <error>xinclude:dom.xml not found</error>
</root>

DomDocumentType->entities

(no version information, might be only in CVS)

DomDocumentType->entities --  Restituisce l'elenco delle entità

Descrizione

array DomDocumentType->entities ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomDocumentType->internal_subset

(no version information, might be only in CVS)

DomDocumentType->internal_subset --  Restituisce un subset interno

Descrizione

bool DomDocumentType->internal_subset ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomDocumentType->name

(no version information, might be only in CVS)

DomDocumentType->name --  Restituisce il nome del tipo documento

Descrizione

string DomDocumentType->name ( void )

Questa funzione restituisce il nome del tipo documento.

Esempio 1. Ottenere il nome del tipo documento

<?php
 
include("example.inc");
 
if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}
 
$doctype = $dom->doctype();
echo $doctype->name(); // chapter
 
?>

DomDocumentType->notations

(no version information, might be only in CVS)

DomDocumentType->notations --  Restituisce la lista delle notazioni

Descrizione

array DomDocumentType->notations ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomDocumentType->public_id

(no version information, might be only in CVS)

DomDocumentType->public_id --  Restituisce l'identificatore pubblico del tipo documento

Descrizione

string DomDocumentType->public_id ( void )

Questa funzione restituisce l'identificatore pubblico del tipo documento.

Il seguente esempio non visualizza niente.

Esempio 1. Recupera l'identificativo pubblico

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

DomDocumentType->system_id

(no version information, might be only in CVS)

DomDocumentType->system_id --  Restituisce l'identificativo di sistema del tipo documento

Descrizione

string DomDocumentType->system_id ( void )

Restituisce l'identificativo di sistema del tipo documento.

Esempio 1. Recupero dell'identificativo di sistema

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

Il precedente esempio visualizzerà:

/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd

DomElement->get_attribute_node

(no version information, might be only in CVS)

DomElement->get_attribute_node --  Restituisce il nodo dell'attributo dato

Descrizione

domattribute DomElement->get_attribute_node ( string name )

Restituisce 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

<?php
 
include("example.inc");
 
if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}
 
$root = $dom->document_element();
if ($attribute = $root->get_attribute_node('language')) {
    echo 'Language is: ' . $attribute->value() . "\n";
}
 
?>

DomElement->get_attribute

(no version information, might be only in CVS)

DomElement->get_attribute --  Restituisce il valore di un attributo

Descrizione

object DomElement->get_attribute ( string nome )

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

DomElement->get_elements_by_tagname

(no version information, might be only in CVS)

DomElement->get_elements_by_tagname --  Restituisce l'elemento con il tag dato

Descrizione

array DomElement->get_elements_by_tagname ( string nome )

Questa 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

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
	$node = $node_array[$i];
	echo ("The element[$i] is: ".$node->get_content());
}

?>

DomElement->has_attribute

(no version information, might be only in CVS)

DomElement->has_attribute --  Verifica l'esistenza dell'attributo

Descrizione

bool DomElement->has_attribute ( string nome )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomElement->remove_attribute

(no version information, might be only in CVS)

DomElement->remove_attribute --  Rimuove un attributo

Descrizione

bool DomElement->remove_attribute ( string name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomElement->set_attribute

(no version information, might be only in CVS)

DomElement->set_attribute --  Valorizza un attributo

Descrizione

domattribute DomElement->set_attribute ( string nome, string valore )

Imposta l'attributo chiamato nome al valore fornito. Se l'attributo non esiste lo crea.

Esempio 1. Valorizzazione di un attributo

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

Vedere anche domelement_get_attribute()

DomElement->tagname

(no version information, might be only in CVS)

DomElement->tagname --  Restituisce il nome dell'elemento corrente

Descrizione

string DomElement->tagname ( void )

Returns the name of the current node. Chiamare questa funzione è come accedere alla proprietà tagname del nodo corrente, o chiamare DomElement->node_name().

Esempio 1. Ottenere il nome del nodo

<?php
 
include("example.inc");
 
if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}
 
$root = $dom->document_element();
echo $root->tagname();   // chapter
echo $root->tagname;     // chapter
echo $root->node_name(); // chapter
 
 
?>

DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace --  Aggiunge la dichiarazione dello spazio dei nomi ad un nodo

Descrizione

bool DomNode->add_namespace ( string uri, string prefix )

Vedere anche domdocument_create_element_ns() e domnode_set_namespace()

DomNode->append_child

(no version information, might be only in CVS)

DomNode->append_child --  Accoda un nuovo figlio

Descrizione

domelement DomNode->append_child ( domelement newnode )

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 1. Aggiunta di un nodo figlio

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>
L'esempio precedente può anche essere scritto:

Esempio 2. Aggiunta di un nodo figlio

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>
Il seguente è un esempio più complesso. Prima cerca un dato elemento, quindi lo si duplica, compresi i suoi figli, lo si aggiunge come un fratello. Infine si aggiunge un attributo ad uno dei figli del nuovo nodo e quindi si scarica il documento.

Esempio 3. Aggiunta di un nodo figlio

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>
L'esempio precedente può anche essere svolto con domnode_insert_before() invece di domnode_append_child().

Vedere anche domnode_insert_before() e domnode_clone_node().

DomNode->append_sibling

(no version information, might be only in CVS)

DomNode->append_sibling --  Aggiunge un nodo fratello

Descrizione

object DomNode->append_sibling ( object nuovo_nodo )

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

DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes --  Restituisce la lista degli attributi

Descrizione

array DomNode->attributes ( void )

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

DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes --  Restituisce i figli di un nodo

Descrizione

array DomNode->child_nodes ( void )

Restituisce tutti i nodi figlio del nodo.

Vedere anche domnode_next_sibling() e domnode_previous_sibling().

DomNode->clone_node

(no version information, might be only in CVS)

DomNode->clone_node --  Clona un nodo

Descrizione

object DomNode->clone_node ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node --  Scarica un singolo nodo

Descrizione

string DomNode->dump_node ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche domdocument_dump_mem().

DomNode->first_child

(no version information, might be only in CVS)

DomNode->first_child --  Restituisce il primo nodo figlio

Descrizione

object DomNode->first_child ( void )

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

DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content --  Restituisce il contenuto del nodo

Descrizione

string DomNode->get_content ( void )

Questa funzione restituisce il contenuto del nodo

Esempio 1. Ottenere il contenuto di un nodo

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
    $node = $node_array[$i];
    echo ("The element[$i] is: ".$node->get_content());
}

?>

DomNode->has_attributes

(no version information, might be only in CVS)

DomNode->has_attributes --  Verifica se il nodo ha attributi

Descrizione

bool DomNode->has_attributes ( void )

Questa funzione verifica se il nodo ha attributi.

Vedere anche domnode_has_child_nodes().

DomNode->has_child_nodes

(no version information, might be only in CVS)

DomNode->has_child_nodes --  Verifica se esistono nodi figlio

Descrizione

bool DomNode->has_child_nodes ( void )

Questa funzione verifica se il nodo ha nodi figlio.

Vedere anche domnode_child_nodes().

DomNode->insert_before

(no version information, might be only in CVS)

DomNode->insert_before --  Inserisce un nuovo nodo come figlio

Descrizione

object DomNode->insert_before ( object nuovo_nodo, object nodo_riferimento )

Questa 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

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>

Vedere anche domnode_append_child().

DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node --  Verifica se il nodo è vuoto

Descrizione

bool DomNode->is_blank_node ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomNode->last_child

(no version information, might be only in CVS)

DomNode->last_child --  Restituisce l'ultimo nodo figlio del nodo

Descrizione

object DomNode->last_child ( void )

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

DomNode->next_sibling

(no version information, might be only in CVS)

DomNode->next_sibling --  Restituisce il successivo fratello del nodo

Descrizione

object DomNode->next_sibling ( void )

Restituisce 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

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while ($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

Vedere anche domnode_previous_sibling().

DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name --  Restituisce il nome del nodo

Descrizione

string DomNode->node_name ( void )

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

TipoSignificato
DomAttributevalori di attributo
DomAttribute 
DomCDataSection#cdata-section
DomComment#comment
DomDocument#document
DomDocumentTypenome del tipo documento
DomElementnome tag
DomEntitynome di entittà
DomEntityReferencenome di entità di riferimento
DomNotationnome della notazione
DomProcessingInstructiontarget
DomText#text

DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type --  Restituisce il tipo di nodo

Descrizione

int DomNode->node_type ( void )

La funzione restituisce il tipo di nodo. L'elenco di tutti i tipi possibili sono elencati in una tabella nell'introduzione.

Esempio 1.

<?php
 
include 'example.inc';
 
$dom = domxml_open_mem($xmlstr);
 
$chapter = $dom->document_element();
 
// Let's see the elements contained in chapter
foreach($chapter->child_nodes() as $node) {
  if ($node->node_type() == XML_ELEMENT_NODE) {
    echo $node->node_name() . "\n";
  }
}
 
?>

Il precedente esempio visualizzerà:

title
para

DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value --  Restituisce il valore di un nodo

Descrizione

string DomNode->node_value ( void )

La 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

TipoSignificato
DomAttributevalori di un attributo
DomAttribute 
DomCDataSectioncontenuto
DomCommentcontenuto del commento
DomDocumentnull
DomDocumentTypenull
DomElementnull
DomEntitynull
DomEntityReferencenull
DomNotationnull
DomProcessingInstructionl'intero contenuto senza destinatario
DomTextcontenuto del testo

DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document --  Restituisce il documento a cui appartiene questo nodo

Descrizione

object DomNode->owner_document ( void )

Questa funzione restituisce il documento a cui appartiene questo nodo.

L'esempio seguente produce due liste uguali di nodi figli.

Esempio 1. Ricerca del documento di un nodo

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

Vedere anche domnode_insert_before().

DomNode->parent_node

(no version information, might be only in CVS)

DomNode->parent_node --  Restituisce il genitore del nodo

Descrizione

object DomNode->parent_node ( void )

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

Esempio 1. Ricerca del documento di un nodo

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix --  Restituisce lo spazio dei nomi prefisso al nodo

Descrizione

string DomNode->prefix ( void )

Restituisce lo spazio dei nomi prefisso al nodo.

DomNode->previous_sibling

(no version information, might be only in CVS)

DomNode->previous_sibling --  Restituisce il nodo fratello precedente

Descrizione

object DomNode->previous_sibling ( void )

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

DomNode->remove_child

(no version information, might be only in CVS)

DomNode->remove_child --  Rimuove un nodo figlio dalla lista dei figli

Descrizione

object DomNode->remove_child ( object VecchioFiglio )

Questa 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

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

Vedere anche domnode_append_child().

DomNode->replace_child

(no version information, might be only in CVS)

DomNode->replace_child --  Sostituisce un nodo figlio

Descrizione

object DomNode->replace_child ( object vecchio_nodo, object nuovo_nodo )

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

DomNode->replace_node

(no version information, might be only in CVS)

DomNode->replace_node --  Sostituisce il nodo

Descrizione

object DomNode->replace_node ( object nuovo_nodo )

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

DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content --  Imposta il contenuto del nodo

Descrizione

bool DomNode->set_content ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name --  Imposta il nome del nodo

Descrizione

bool DomNode->set_name ( void )

Imposta il nome del nodo.

Vedere anche domnode_node_name().

DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace --  Imposta lo spazio dei nomi del nodo

Descrizione

void DomNode->set_namespace ( string uri [, string prefix] )

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

DomNode->unlink_node

(no version information, might be only in CVS)

DomNode->unlink_node --  Rimuove il nodo

Descrizione

object DomNode->unlink_node ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomProcessingInstruction->data

(no version information, might be only in CVS)

DomProcessingInstruction->data --  Restituisce i dati di un nodo PI

Descrizione

string DomProcessingInstruction->data ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomProcessingInstruction->target

(no version information, might be only in CVS)

DomProcessingInstruction->target --  Restituisce il target di un nodo PI

Descrizione

string DomProcessingInstruction->target ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DomXsltStylesheet->process

(no version information, might be only in CVS)

DomXsltStylesheet->process --  Applica una trasformazione XSLT ad un oggetto DomDocument

Descrizione

object DomXsltStylesheet->process ( object DomDocument [, array xslt_parameters [, bool param_is_xpath]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

DomXsltStylesheet->result_dump_file

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_file --  Scarica il risultato di una trasformazione XSLT in un file

Descrizione

string DomXsltStylesheet->result_dump_file ( object DomDocument, string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. Salvataggio del risultato di una trasformazione XSLT in un file.

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_file($result, "filename");     
?>

Vedere anche domxml_xslt_result_dump_mem() e domxml_xslt_process()

DomXsltStylesheet->result_dump_mem

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_mem --  Scarica il risultato di una trasformazione XSLT in una stringa

Descrizione

string DomXsltStylesheet->result_dump_mem ( object 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.

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.

Esempio 1. Visualizzazione del risultato di una trasformazione XSLT.

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_mem($result);     
?>

Vedere anche domxml_xslt_result_dump_file() e domxml_xslt_process()

domxml_new_doc

(PHP 4 >= 4.2.1, PECL)

domxml_new_doc --  Crea un nuovo documento XML vuoto

Descrizione

object domxml_new_doc ( string versione )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

domxml_open_file

(PHP 4 >= 4.2.1, PECL)

domxml_open_file -- Crea un oggetto DOM da un file XML

Descrizione

object domxml_open_file ( string nome_file [, int mode [, array &error]] )

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.

Esempio 1. Apertura di un documento XML da un file

<?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

Vedere anche domxml_open_mem() e domxml_new_doc().

domxml_open_mem

(PHP 4 >= 4.2.1, PECL)

domxml_open_mem -- Crea un oggetto DOM da un documento XML

Descrizione

object domxml_open_mem ( string str [, int mode [, array &error]] )

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.

Esempio 1. Apertura di un documento XML da una stringa

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

Vedere anche domxml_open_file() e domxml_new_doc().

domxml_version

(PHP 4 >= 4.1.0, PECL)

domxml_version --  restituisce la versione della libreria XML

Descrizione

string domxml_version ( void )

Questa funzione restituisce la versione della libreria XML attualmente utilizzata.

domxml_xmltree

(PHP 4 >= 4.2.1, PECL)

domxml_xmltree --  Crea un albero di oggetti PHP da un documento XML

Descrizione

object domxml_xmltree ( string str )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet_doc --  Crea un oggetto DomXsltStylesheet da un oggetto DomDocument.

Descrizione

object domxml_xslt_stylesheet_doc ( object DocDocument 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.

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

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet_file --  Crea un oggetto DomXsltStylesheet da un file con un documento XSL

Descrizione

object domxml_xslt_stylesheet_file ( string xsl 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.

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

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_stylesheet --  Crea un oggetto DomXsltStylesheet da un documento XML contenuto in una stringa

Descrizione

object domxml_xslt_stylesheet ( string xsl document )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

domxml_xslt_version

(PHP 4 >= 4.2.0, PECL)

domxml_xslt_version --  Gets the XSLT library version

Descrizione

int domxml_xslt_version ( void )

Gets the XSLT library version.

Valori restituiti

Returns the version number of the XSLT library, as an integer.

Esempi

Esempio 1. domxml_xslt_version() Example

<?php

echo domxml_xslt_version();

?>

Il precedente esempio visualizzerà qualcosa simile a:

10112

Vedere anche:

domxml_version()

xpath_eval_expression

(PHP 4 >= 4.0.4, PECL)

xpath_eval_expression --  Valuta il percorso XPath nella stringa data

Descrizione

array xpath_eval_expression ( object xpath_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().

xpath_eval

(PHP 4 >= 4.0.4, PECL)

xpath_eval --  Valuta il percorso XPath nella stringa data

Descrizione

array xpath_eval ( object xpath context, string xpath expression [, object contextnode] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

xpath_new_context

(PHP 4 >= 4.0.4, PECL)

xpath_new_context --  Crea un nuovo contesto xpath

Descrizione

object xpath_new_context ( object dom document )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

xpath_register_ns_auto

(PECL)

xpath_register_ns_auto --  Register the given namespace in the passed XPath context

Descrizione

bool xpath_register_ns_auto ( XPathContext xpath_context [, object context_node] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

xpath_register_ns()

xpath_register_ns

(PHP 4 >= 4.2.0, PECL)

xpath_register_ns --  Register the given namespace in the passed XPath context

Descrizione

bool xpath_register_ns ( XPathContext xpath_context, string prefix, string uri )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

xptr_eval

(PHP 4 >= 4.0.4, PECL)

xptr_eval --  Valuta il percorso della locazione XPtr nella stringa data

Descrizione

int xptr_eval ( [object xpath_context, string eval_str] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xptr_new_context

(PHP 4 >= 4.0.4, PECL)

xptr_new_context --  Crea un nuovo contesto XPath

Descrizione

string xptr_new_context ( [object doc_handle] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

XXXII. Funzioni di gestione degli errori e di logging

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione per la gestione degli errori e dei log

NomeDefaultModificabile
error_reportingE_ALL & ~E_NOTICEPHP_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_stringNULLPHP_INI_ALL
error_append_stringNULLPHP_INI_ALL
error_logNULLPHP_INI_ALL
warn_plus_overloadingNULLPHP_INI??
Per maggiori dettaglii e per le definizioni delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

error_reporting integer

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.

display_errors boolean

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

display_startup_errors boolean

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.

log_errors boolean

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.

log_errors_max_len integer

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.

ignore_repeated_errors boolean

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.

ignore_repeated_source boolean

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.

report_memleaks boolean

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.

track_errors boolean

Se abilitato, l'ultimo messaggio di errore sarà sempre presente nella variabile $php_errormsg.

html_errors boolean

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.

docref_root string

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

docref_ext string

Vedere docref_root.

Nota: Il valore di docref_ext deve cominciare con un punto '.'.

error_prepend_string string

Testo da visualizzare prima del messaggio di errore.

error_append_string string

Testo da visualizzare dopo il messaggio di errore.

error_log string

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

warn_plus_overloading boolean

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


Costanti predefinite

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

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


Esempi

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

<?php
// attiveremo la nostra gestione degli errori
error_reporting(0);

// funzione personalizzata di gestione dell'errore
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) 
{
    // orario per la registrazione
    $dt = date("Y-m-d H:i:s (T)");

    // definisce una matrice associativa con i messaggi di errore
    // in realtà i soli campi che saranno considerati sono
    // E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE
    $errortype = array (
                E_ERROR           => "Error",
                E_WARNING         => "Warning",
                E_PARSE           => "Parsing Error",
                E_NOTICE          => "Notice",
                E_CORE_ERROR      => "Core Error",
                E_CORE_WARNING    => "Core Warning",
                E_COMPILE_ERROR   => "Compile Error",
                E_COMPILE_WARNING => "Compile Warning",
                E_USER_ERROR      => "User Error",
                E_USER_WARNING    => "User Warning",
                E_USER_NOTICE     => "User Notice",
                E_STRICT          => "Runtime Notice"
                );
    // indica gli errori per i quali fare salvare la trace delle variabili
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
    
    $err = "<errorentry>\n";
    $err .= "\t<datetime>" . $dt . "</datetime>\n";
    $err .= "\t<errornum>" . $errno . "</errornum>\n";
    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";
    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
    }
    $err .= "</errorentry>\n\n";
    
    // for testing
    // echo $err;

    // salva nell'errorlog e invia un e-mail se vi sono errori critici
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR) {
        mail("phpdev@example.com", "Critical User Error", $err);
    }
}


function distance($vect1, $vect2) 
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero", 
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero", 
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// variabile non definita, genera un warning
$t = I_AM_NOT_DEFINED;

// definisce dei vettori
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// genera un errore utente
$t1 = distance($c, $b) . "\n";

// un'altro errore utente
$t2 = distance($b, "i am not an array") . "\n";

// genera un warning
$t3 = distance($a, $b) . "\n";

?>


Vedere anche:

Vedere anche syslog().

Sommario
debug_backtrace --  Genera una backtrace
debug_print_backtrace --  Stampa una backtrace
error_log -- invia un messaggio di errore
error_reporting -- definisce quali errori di PHP vengono restituiti
restore_error_handler --  Ripristina la precedente funzione di gestione dell'errore
restore_exception_handler --  Ripristina la funzione di gestione delle eccezioni definita in precedenza
set_error_handler --  Configura una funzione di gestione dell'errore definita dall'utente.
set_exception_handler --  Imposta una funzione di gestione delle eccezioni definita dall'utente
trigger_error --  Genera un messaggio a livello utente di errore/avviso/avvertimento message
user_error --  Genera un messaggio di errore/avviso/avvertimento a livello utente

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtrace --  Genera una backtrace

Descrizione

array debug_backtrace ( void )

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

NomeTipoDescrizione
funzionestring Il nome della funzione corrente. Vedere anche __FUNCTION__.
rigainteger Il numero della linea corrente. Vedere anche __LINE__.
filestring Il nome del file corrente. Vedere anche __FILE__.
classestring Il nome della class corrente. Vedere anche __CLASS__
tipostring 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.
argsarray 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

<?php
// filename: a.php

function a_test($str) 
{
    echo "\nHi: $str";
    var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: b.php
include_once '/tmp/a.php';
?>

Risultati durante l'esecuzione di /tmp/b.php:

Hi: friend
array(2) {
  [0]=>
  array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
  }
  [1]=>
  array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] => 
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

Vedere anche trigger_error() and debug_print_backtrace().

debug_print_backtrace

(PHP 5)

debug_print_backtrace --  Stampa una backtrace

Descrizione

void debug_print_backtrace ( void )

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

Elenco dei parametri

Questa funzione non ha parametri.

Valori restituiti

No value is returned.

Esempi

Esempio 1. Esempio di funzione debug_print_backtrace()

<?php
// include.php file

function a() {
    b();
}

function b() {
    c();
}

function c(){
    debug_print_backtrace();
}

a();

?>


<?php
// test.php file
// questo e' il file che dovrebbe essere eseguito

include 'include.php';
?>

Il precedente esempio visualizzerà qualcosa simile a:

#0  eval() called at [/tmp/include.php:5]
#1  a() called at [/tmp/include.php:17]
#2  include(/tmp/include.php) called at [/tmp/test.php:3]

#0  c() called at [/tmp/include.php:10]
#1  b() called at [/tmp/include.php:6]
#2  a() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

Vedere anche:

debug_backtrace()

error_log

(PHP 3, PHP 4, PHP 5)

error_log -- invia un messaggio di errore

Descrizione

int error_log ( string messaggio [, int tipo_messaggio [, string destinazione [, string header_extra]]] )

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

// Invia notifica via log del server se non è possibile 
// connettersi al database.
if (!Ora_Logon ($username, $password)) {
    error_log ("Database Oracle non disponibile!", 0);
}

// Notifica via posta elettronica all'amministratore se esauriscono i FOO
if (!($foo = allocate_new_foo()) {
    error_log ("Problemi seri, FOO esauriti!", 1,
               "operator@mydomain.com");
}

// altri modi per chiamare error_log():
error_log ("Problema!", 2, "127.0.0.1:7000");
error_log ("Problema!", 2, "loghost");
error_log ("Problema!", 3, "/var/tmp/my-errors.log");

error_reporting

(PHP 3, PHP 4, PHP 5)

error_reporting -- definisce quali errori di PHP vengono restituiti

Description

int error_reporting ( [int livello] )

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

error_reporting (55);   // Equivalente a E_ALL ^ E_NOTICE in PHP 3

/* ...in PHP 4, '55' indica (E_ERROR | E_WARNING | E_PARSE |
E_CORE_ERROR | E_CORE_WARNING) */

error_reporting (2039); // Equivalente a E_ALL ^ E_NOTICE in PHP 4

error_reporting (E_ALL ^ E_NOTICE); // Il medesimo in PHP 3 e 4
Seguite i collegamenti delle costanti per conoscerne il significato:

Tabella 1. error_reporting() valori dei bit

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

// Turn off all error reporting
error_reporting (0);

// Report simple running errors
error_reporting  (E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized 
// variables or catch variable name misspellings)
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all PHP errors (use bitwise  63  in PHP 3)
error_reporting (E_ALL);

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler --  Ripristina la precedente funzione di gestione dell'errore

Descrizione

void restore_error_handler ( void )

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

restore_exception_handler

(PHP 5)

restore_exception_handler --  Ripristina la funzione di gestione delle eccezioni definita in precedenza

Descrizione

bool restore_exception_handler ( void )

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

set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handler --  Configura una funzione di gestione dell'errore definita dall'utente.

Descrizione

string set_error_handler ( string error_handler )

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

<?php

// ridefinisce la costante dell'errore utente - solo PHP 4
define (FATAL,E_USER_ERROR);
define (ERROR,E_USER_WARNING);
define (WARNING,E_USER_NOTICE);

// configura il livello di restituzione errore per questo script
error_reporting (FATAL | ERROR | WARNING);

// funzione di gestione dell'errore
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
  switch ($errno) {
  case FATAL:
    echo "<b>FATAL</b> [$errno] $errstr<br>\n";
    echo "  Fatal error in line ".$errline." of file ".$errfile;
    echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
    echo "Aborting...<br>\n";
    exit 1;
    break;
  case ERROR:
    echo "<b>ERROR</b> [$errno] $errstr<br>\n";
    break;
  case WARNING:
    echo "<b>WARNING</b> [$errno] $errstr<br>\n";
    break;
    default:
    echo "Unkown error type: [$errno] $errstr<br>\n";
    break;
  }
}

// funzione di prova del gestore di errore
function scale_by_log ($vect, $scale) {
  if ( !is_numeric($scale) || $scale <= 0 )
    trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale",
      FATAL);
  if (!is_array($vect)) {
    trigger_error("Incorrect input vector, array of values expected", ERROR);
    return null;
  }
  for ($i=0; $i<count($vect); $i++) {
    if (!is_numeric($vect[$i]))
      trigger_error("Value at position $i is not a number, using 0 (zero)", 
        WARNING);
    $temp[$i] = log($scale) * $vect[$i];
  }
  return $temp;
}

// configura il gestore dell'errore definito dall'utente
$old_error_handler = set_error_handler("myErrorHandler");

// attiva alcuni errori, definendo prima un array misto con elementi non numerici
echo "vector a\n";
$a = array(2,3,"foo",5.5,43.3,21.11);
print_r($a);

// genera il secondo array, generando un avviso
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// questo è il problema, passiamo una stringa al posto di un array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array",2.3);
var_dump($c);

// errore critico, il log di zero o di un numero negativo non è definito
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>
E l'esecuzione di questo script, darà

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

set_exception_handler

(PHP 5)

set_exception_handler --  Imposta una funzione di gestione delle eccezioni definita dall'utente

Descrizione

string set_exception_handler ( callback exception_handler )

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

exception

Nome della funzione da invocare in caso di eccezione non individuata.

Elenco dei parametri

exception_handler

Nome della funzione da invocare in caso di eccezione non individuata.

Valori restituiti

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.

Esempi

Esempio 1. Esempio di funzione set_exception_handler()

<?php
function exception_handler($exception) {
  echo "Eccezione non individuata: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Non eseguita\n";
?>

trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_error --  Genera un messaggio a livello utente di errore/avviso/avvertimento message

Descrizione

void trigger_error ( string error_msg [, int error_type] )

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

if (assert ($divisor == 0))
   trigger_error ("Cannot divide by zero", E_USER_ERROR);

Nota: Vedere set_error_handler() per un esempio più esplicativo.

Vedere anche error_reporting(), set_error_handler(), restore_error_handler(), user_error()

user_error

(PHP 4, PHP 5)

user_error --  Genera un messaggio di errore/avviso/avvertimento a livello utente

Descrizione

void user_error ( string error_msg [, int error_type] )

Questo è un alias per la funzione trigger_error().

Vedere anche error_reporting(), set_error_handler(), restore_error_handler() e trigger_error()

XXXIII. Exif Functions

Introduzione

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.


Requisiti

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.


Installazione

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.


Configurazione di Runtime

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

NameDefaultChangeableChangelog
exif.encode_unicode"ISO-8859-15"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.encode_jis""PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_jis_motorola"JIS"PHP_INI_ALLAvailable since PHP 4.3.0.
exif.decode_jis_intel"JIS"PHP_INI_ALLAvailable since PHP 4.3.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

EXIF_USE_MBSTRING (integer)

The exif_imagetype() lists several related built-in constants.

Sommario
exif_imagetype -- Determine the type of an image
exif_read_data -- Reads the EXIF headers from JPEG or TIFF
exif_tagname -- Get the header name for an index
exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image
read_exif_data -- Alias di exif_read_data()

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype -- Determine the type of an image

Descrizione

int exif_imagetype ( string filename )

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.

Elenco dei parametri

filename

The image being checked.

Valori restituiti

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.

Log delle modifiche

VersioneDescrizione
4.3.2 Support for JPC, JP2, JPX, JB2, XBM, and WBMP
4.3.0Support for SWC

Costanti predefinite

The following constants are defined, and represent possible exif_imagetype() return values:

Tabella 1. Imagetype Constants

ValueConstant
1IMAGETYPE_GIF
2IMAGETYPE_JPEG
3IMAGETYPE_PNG
4IMAGETYPE_SWF
5IMAGETYPE_PSD
6IMAGETYPE_BMP
7IMAGETYPE_TIFF_II (intel byte order)
8 IMAGETYPE_TIFF_MM (motorola byte order)
9IMAGETYPE_JPC
10IMAGETYPE_JP2
11IMAGETYPE_JPX
12IMAGETYPE_JB2
13IMAGETYPE_SWC
14IMAGETYPE_IFF
15IMAGETYPE_WBMP
16IMAGETYPE_XBM

Esempi

Esempio 1. exif_imagetype() example

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

Vedere anche:

getimagesize()

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data -- Reads the EXIF headers from JPEG or TIFF

Descrizione

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]] )

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.

Elenco dei parametri

filename

The name of the image file being read. This cannot be an URL.

sections

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.

FILEFileName, 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_TAGAny 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.
COMMENTComment headers of JPEG images.
EXIF The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays

Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.

thumbnail

When set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.

Valori restituiti

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.

Log delle modifiche

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

Esempi

Esempio 1. exif_read_data() example

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

The first call fails because the image has no header information.

Il precedente esempio visualizzerà qualcosa simile a:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

exif_tagname

(PHP 4 >= 4.2.0, PHP 5)

exif_tagname -- Get the header name for an index

Descrizione

string exif_tagname ( string index )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

index

The image index

Valori restituiti

Returns the header name, or FALSE if index is undefined.

Vedere anche:

exif_imagetype()

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image

Descrizione

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]] )

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.

Elenco dei parametri

filename

The name of the image file being read. This image contains an embedded thumbnail.

width

The return width of the returned thumbnail.

height

The returned height of the returned thumbnail.

imagetype

The returned image type of the returned thumbnail. This is either TIFF or JPEG.

Valori restituiti

Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.

Log delle modifiche

VersioneDescrizione
4.3.0 The optional parameters width, height, and imagetype all became available.
4.3.0 May return thumbnails in the TIFF format.

Esempi

Esempio 1. exif_thumbnail() example

<?php
if (array_key_exists('file', $_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header('Content-type: ' .image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo 'No thumbnail available';
}
?>

read_exif_data

(PHP 4 >= 4.0.1, PHP 5)

read_exif_data -- Alias di exif_read_data()

Descrizione

This function is an alias of: exif_read_data().

XXXIV. Expect Functions

Introduzione

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.


Requisiti

This module uses the functions of the expect library. You need libexpect version >= 5.43.0.


Installazione

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


Configurazione di Runtime

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

NomeDefaultModificabileChangelog
expect.timeout"10"PHP_INI_ALL 
expect.loguser"On"PHP_INI_ALL 
expect.logfile""PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

expect.timeout integer

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.

expect.loguser boolean

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.

expect.logfile string

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.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

EXP_GLOB (integer)

Indicates that the pattern is a glob-style string pattern.

EXP_EXACT (integer)

Indicates that the pattern is an exact string.

EXP_REGEXP (integer)

Indicates that the pattern is a regexp-style string pattern.

EXP_EOF (integer)

Value, returned by expect_expectl(), when EOF is reached.

EXP_TIMEOUT (integer)

Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout

EXP_FULLBUFFER (integer)

Value, returned by expect_expectl() if no pattern have been matched.


Esempi

This example connects to the remote host via SSH, and prints the remote uptime.

Esempio 1. Expect Usage Example

<?php
ini_set ("expect.loguser", "Off");

$stream = popen ("expect://ssh root@remotehost uptime", "r");

$cases = array (
  array (0 => "password:", 1 => PASSWORD)
);

switch (expect_expectl ($stream, $cases))
{
 case PASSWORD:
  fwrite ($stream, "password\n");
  break;
 
 default:
  die ("Error was occurred while connecting to the remote host!\n");
}

while ($line = fgets ($stream)) {
  print $line;
}
fclose ($stream);
?>
Sommario
expect_expectl -- Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
expect_popen -- Exectute command via Bourne shell, and open the PTY stream to the process

expect_expectl

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

Descrizione

mixed expect_expectl ( resource expect, array cases )

Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

Elenco dei parametri

expect

An Expect stream, previously opened with expect_popen().

cases

An array of expect cases. Each expect case is an indexed array, as described in the following table:

Tabella 1. Expect Case Array

Index KeyValue TypeDescriptionIs MandatoryDefault Value
0stringpattern, that will be matched against the output from the streamyes 
1mixedvalue, that will be returned by this function, if the pattern matchesyes 
2integer pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP noEXP_GLOB

Valori restituiti

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

Esempi

Esempio 1. expect_expectl() example

<?php
// Copies file from remote host:
ini_set ("expect.timeout", 30);

$stream = popen ("expect://scp user@remotehost:/var/log/messages /home/user/messages.txt", "r");

$cases = array (
  array (0 => "password:", 1 => PASSWORD),
  array (0 => "yes/no)?", 1 => YESNO)
);

while (true) {
 switch (expect_expectl ($stream, $cases))
 {
  case PASSWORD:
   fwrite ($stream, "password\n");
   break;

  case YESNO:
   fwrite ($stream, "yes\n");
   break;

  case EXP_TIMEOUT:
  case EXP_EOF:
   break 2;
  
  default:
   die ("Error has occurred!\n");
 }
}

fclose ($stream);
?>

Vedere anche:

expect_popen()

expect_popen

(no version information, might be only in CVS)

expect_popen -- Exectute command via Bourne shell, and open the PTY stream to the process

Descrizione

resource expect_popen ( string command )

Execute command via Bourne shell, and open the PTY stream to the process.

Elenco dei parametri

command

Command to execute.

Valori restituiti

Returns an open PTY stream to the process'es stdio, stdout and stderr.

On failure this function returns FALSE.

Esempi

Esempio 1. expect_popen() example

<?php
// Login to the PHP.net CVS repository:
$stream = expect_popen ("cvs -d :pserver:anonymous@cvs.php.net:/repository login");
sleep (3);
fwrite ($stream, "phpfi\n");
fclose ($stream);
?>

Vedere anche:

popen()

XXXV. File Alteration Monitor Functions

Introduzione

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.


Requisiti

This extension uses the functions of the FAM library, developed by SGI. Therefore you have to download and install the FAM library.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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

ConstantDescription
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.
Sommario
fam_cancel_monitor -- Terminate monitoring
fam_close -- Close FAM connection
fam_monitor_collection -- Monitor a collection of files in a directory for changes
fam_monitor_directory -- Monitor a directory for changes
fam_monitor_file -- Monitor a regular file for changes
fam_next_event -- Get next pending FAM event
fam_open -- Open connection to FAM daemon
fam_pending -- Check for pending FAM events
fam_resume_monitor -- Resume suspended monitoring
fam_suspend_monitor -- Temporarily suspend monitoring

fam_cancel_monitor

(PHP 5 <= 5.0.4)

fam_cancel_monitor -- Terminate monitoring

Descrizione

bool fam_cancel_monitor ( resource fam, resource fam_monitor )

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

(PHP 5 <= 5.0.4)

fam_close -- Close FAM connection

Descrizione

void fam_close ( resource fam )

fam_close() closes a connection to the FAM service previously opened using fam_open().

fam_monitor_collection

(PHP 5 <= 5.0.4)

fam_monitor_collection -- Monitor a collection of files in a directory for changes

Descrizione

resource fam_monitor_collection ( resource fam, string dirname, int depth, string mask )

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

(PHP 5 <= 5.0.4)

fam_monitor_directory -- Monitor a directory for changes

Descrizione

resource fam_monitor_directory ( resource fam, string dirname )

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

(PHP 5 <= 5.0.4)

fam_monitor_file -- Monitor a regular file for changes

Descrizione

resource fam_monitor_file ( resource fam, string filename )

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

(PHP 5 <= 5.0.4)

fam_next_event -- Get next pending FAM event

Descrizione

array fam_next_event ( resource fam )

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

(PHP 5 <= 5.0.4)

fam_open -- Open connection to FAM daemon

Descrizione

resource fam_open ( [string appname] )

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

(PHP 5 <= 5.0.4)

fam_pending -- Check for pending FAM events

Descrizione

int fam_pending ( resource fam )

fam_pending() returns non-zero if events are available to be fetched using fam_next_event().

See also fam_next_event().

fam_resume_monitor

(PHP 5 <= 5.0.4)

fam_resume_monitor -- Resume suspended monitoring

Descrizione

bool fam_resume_monitor ( resource fam, resource fam_monitor )

fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().

See also fam_suspend_monitor().

fam_suspend_monitor

(PHP 5 <= 5.0.4)

fam_suspend_monitor -- Temporarily suspend monitoring

Descrizione

bool fam_suspend_monitor ( resource fam, resource fam_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().

XXXVI. Funzioni Forms Data Format

Introduzione

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


Requisiti

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.


Installazione

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


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

fdf

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


Costanti predefinite

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.

FDFValue (integer)

FDFStatus (integer)

FDFFile (integer)

FDFID (integer)

FDFFf (integer)

FDFSetFf (integer)

FDFClearFf (integer)

FDFFlags (integer)

FDFSetF (integer)

FDFClrF (integer)

FDFAP (integer)

FDFAS (integer)

FDFAction (integer)

FDFAA (integer)

FDFAPRef (integer)

FDFIF (integer)

FDFEnter (integer)

FDFExit (integer)

FDFDown (integer)

FDFUp (integer)

FDFFormat (integer)

FDFValidate (integer)

FDFKeystroke (integer)

FDFCalculate (integer)

FDFNormalAP (integer)

FDFRolloverAP (integer)

FDFDownAP (integer)


Esempi

Il seguente esempio illustra l'elaborazione dei dati di un form.

Esempio 1. Elaborazione di un documento FDF

<?php
// Apre fdf dalla stringa di input fornita dalla estensione
// Il form pdf contiene diversi campi con nome
// volume, date, comment, publisher, preparer, e due checkboxes
// show_publisher e show_preparer.
$fdf = fdf_open_string($HTTP_FDF_DATA);
$volume = fdf_get_value($fdf, "volume");
echo "TIl campo volume ha valore '<b>$volume</b>'<br />";

$date = fdf_get_value($fdf, "date");
echo "Il campo date ha valore '<b>$date</b>'<br />";

$comment = fdf_get_value($fdf, "comment");
echo "Il campo commento ha valore '<b>$comment</b>'<br />";

if (fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "Il campo publisher ha valore '<b>$publisher</b>'<br />";
} else
  echo "Publisher non deve essere visualizzato.<br />";

if (fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "Il campo preparer ha valore '<b>$preparer</b>'<br />";
} else
  echo "Preparer non deve essere visualizzato.<br />";
fdf_close($fdf);
?>

Sommario
fdf_add_doc_javascript -- Aggiunge codice Javascript ad un documento FDF
fdf_add_template -- aggiunge un templat in un documento FDF
fdf_close -- Chiude un documento FDF
fdf_create -- Crea un nuovo documento FDF
fdf_enum_values -- Richiama una funzione definita dall'utente per ciascun valore del documento
fdf_errno -- Restituisce il codice di errore per l'ultima operazione FDF
fdf_error -- Restituisce la descrizione di un codice di errore fdf
fdf_get_ap -- Ottiene il formato di un campo
fdf_get_attachment -- Estrae file racchiusi nel FDF
fdf_get_encoding -- Restituisce il valore della chiave /Encoding
fdf_get_file -- Ottiene il valore della chiave /F
fdf_get_flags -- Ottiene i flag di un campo
fdf_get_opt -- Ottiene un valore dalla matrice delle opzioni di un campo
fdf_get_status -- Restituisce il valore per la chiave /STATUS
fdf_get_value -- Ottiene il valore di un campo
fdf_get_version -- Restituisce il numero di versione per le API FDF o un file
fdf_header -- Imposta gli header specifici per FDF
fdf_next_field_name -- Restituisce il nome del campo successivo
fdf_open_string -- Legge un documento FDF da una stringa
fdf_open -- Apre un documento FDF
fdf_remove_item -- Imposta il frame di destinazione per un form
fdf_save_string -- Restituisce un documento FDF come una stringa
fdf_save -- Salva un documento FDF
fdf_set_ap -- Imposta l'apparire di un campo
fdf_set_encoding -- Imposta la codifica dei caratteri per FDF
fdf_set_file -- Imposta un documento PDF per visualizzare i dati FDF presenti
fdf_set_flags -- Imposta i flag di un campo
fdf_set_javascript_action -- Imposta un'azione javascript per un campo
fdf_set_on_import_javascript -- Adds javascript code to be executed when Acrobat opens the FDF
fdf_set_opt -- Imposta le opzioni per un campo
fdf_set_status -- Imposta il valore per la chiave /STATUS
fdf_set_submit_form_action -- Imposta un'azione per un campo nell'invio di un form
fdf_set_target_frame -- Imposta il frame in cui visualizzare il form
fdf_set_value -- Imposta il valore di un campo
fdf_set_version -- Imposta il numero di versione per un file FDF

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_add_doc_javascript -- Aggiunge codice Javascript ad un documento FDF

Descrizione

bool fdf_add_doc_javascript ( resource fdfdoc, string script_name, string script_code )

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

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?>

Sarà creato un documento come il seguente:

%FDF-1.2
%âãÏÓ
1 0 obj
<< 
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >> 
>> 
endobj
trailer
<<
/Root 1 0 R 

>>
%%EOF

fdf_add_template

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

fdf_add_template -- aggiunge un templat in un documento FDF

Descrizione

bool fdf_add_template ( resource fdfdoc, int newpage, string filename, string template, int rename )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fdf_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_close -- Chiude un documento FDF

Descrizione

bool fdf_close ( resource fdf_document )

La funzione fdf_close() chiude un documento FDF.

Vedere anche fdf_open().

fdf_create

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_create -- Crea un nuovo documento FDF

Descrizione

resource fdf_create ( void )

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

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

Vedere anche fdf_close(), fdf_save() e fdf_open().

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5)

fdf_enum_values -- Richiama una funzione definita dall'utente per ciascun valore del documento

Descrizione

bool fdf_enum_values ( resource fdfdoc, callback function [, mixed userdata] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fdf_errno

(PHP 4 >= 4.3.0, PHP 5)

fdf_errno -- Restituisce il codice di errore per l'ultima operazione FDF

Descrizione

int fdf_errno ( void )

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

(PHP 4 >= 4.3.0, PHP 5)

fdf_error -- Restituisce la descrizione di un codice di errore fdf

Descrizione

string fdf_error ( [int error_code] )

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

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_ap -- Ottiene il formato di un campo

Descrizione

bool fdf_get_ap ( resource fdf_document, string field, int face, string filename )

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.

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_attachment -- Estrae file racchiusi nel FDF

Descrizione

array fdf_get_attachment ( resource fdf_document, string fieldname, string savepath )

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

Esempio 1. Scaricare un file inserito

<?php 
  $fdf = fdf_open_string($HTTP_FDF_DATA);
  $data = fdf_get_attachment($fdf, "filename", "/tmpdir");
  echo "Il file è stato scaricato in $data[path]";
?>

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_encoding -- Restituisce il valore della chiave /Encoding

Descrizione

string fdf_get_encoding ( resource fdf_document )

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

fdf_get_file

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_get_file -- Ottiene il valore della chiave /F

Descrizione

string fdf_get_file ( resource fdf_document )

La funzione fdf_set_file() restituisce il valore della chiave /F.

Vedere anche fdf_set_file().

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_flags -- Ottiene i flag di un campo

Descrizione

int fdf_get_flags ( resource fdfdoc, string fieldname, int whichflags )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_opt -- Ottiene un valore dalla matrice delle opzioni di un campo

Descrizione

mixed fdf_get_opt ( resource fdfdof, string fieldname [, int element] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fdf_get_status

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_get_status -- Restituisce il valore per la chiave /STATUS

Descrizione

string fdf_get_status ( resource fdf_document )

La funzione fdf_get_status() restituisce il valore per la chiave /STATUS.

Vedere anche fdf_set_status().

fdf_get_value

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_get_value -- Ottiene il valore di un campo

Descrizione

string fdf_get_value ( resource fdf_document, string fieldname [, int which] )

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

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_version -- Restituisce il numero di versione per le API FDF o un file

Descrizione

string fdf_get_version ( [resource fdf_document] )

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

fdf_header

(PHP 4 >= 4.3.0, PHP 5)

fdf_header -- Imposta gli header specifici per FDF

Descrizione

bool fdf_header ( void )

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.

fdf_next_field_name

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_next_field_name -- Restituisce il nome del campo successivo

Descrizione

string fdf_next_field_name ( resource fdf_document [, string fieldname] )

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.

Esempio 1. Rilevazione di tutti i campi in un FDF

<?php
$fdf = fdf_open($HTTP_FDF_DATA);
for ($field = fdf_next_field_name($fdf); 
    $field != ""; 
    $field = fdf_next_field_name($fdf, $field)) {
  echo "field: $field\n";
} 
?>

Vedere anche fdf_enum_fields() e fdf_get_value().

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_open_string -- Legge un documento FDF da una stringa

Descrizione

resource fdf_open_string ( string fdf_data )

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.

Esempio 1. Accesso ai dati di un form

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

Vedere anche fdf_open(), fdf_close(), fdf_create() e fdf_save_string().

fdf_open

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_open -- Apre un documento FDF

Descrizione

resource fdf_open ( string filename )

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

Esempio 1. Accesso ai dati di un form

<?php
// Salva i dati FDF in un file temporaneo
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Apre il file temporaneo e analizza i dati
$fdf = fdf_open("test.fdf");
/* ... */
fdf_close($fdf);
?>

Vedere anche fdf_open_string(), fdf_close(), fdf_create() e fdf_save().

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5)

fdf_remove_item -- Imposta il frame di destinazione per un form

Descrizione

bool fdf_remove_item ( resource fdfdoc, string fieldname, int item )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_save_string -- Restituisce un documento FDF come una stringa

Descrizione

string fdf_save_string ( resource fdf_document )

La funzione fdf_save_string() restituisce il documento FDF come una stringa.

Esempio 1. Recupero di un documento FDF come stringa

<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>

Visualizzerà qualcosa tipo

%FDF-1.2
%âãÏÓ
1 0 obj
<< 
/FDF << /Fields 2 0 R >> 
>> 
endobj
2 0 obj
[ 
<< /T (foo)/V (bar)>> 
]
endobj
trailer
<<
/Root 1 0 R 

>>
%%EOF

Vedere anche: fdf_save(), fdf_open_string(), fdf_create() e fdf_close().

fdf_save

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_save -- Salva un documento FDF

Descrizione

bool fdf_save ( resource fdf_document [, string filename] )

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

fdf_set_ap

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_ap -- Imposta l'apparire di un campo

Descrizione

bool fdf_set_ap ( resource fdf_document, string field_name, int face, string filename, int page_number )

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.

fdf_set_encoding

(PHP 4 >= 4.1.0, PHP 5)

fdf_set_encoding -- Imposta la codifica dei caratteri per FDF

Descrizione

bool fdf_set_encoding ( resource fdf_document, string encoding )

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.

fdf_set_file

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_file -- Imposta un documento PDF per visualizzare i dati FDF presenti

Descrizione

bool fdf_set_file ( resource fdf_document, string url [, string target_frame] )

La 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

<?php
  /* imposta il content type a Adobe FDF */
  fdf_header();

  /* inizia un nuovo fdf */
  $fdf = fdf_create();
    
  /* imposta il campo "foo" a "bar" */
  $fdf_set_value($fdf, "foo", "bar");

  /* dice al client di visualizzare i dati fdf in "fdf_form.pdf" */
  fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");

  /* scrive fdf */
  fdf_save();

  /* chiusura */
  fdf_close();
?>

Vedere anche fdf_get_file() e fdf_set_target_frame().

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_flags -- Imposta i flag di un campo

Descrizione

bool fdf_set_flags ( resource fdf_document, string fieldname, int whichFlags, int newFlags )

La funzione fdf_set_flags() imposta i flag del campo fieldname passato

Vedere anche fdf_set_opt().

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_javascript_action -- Imposta un'azione javascript per un campo

Descrizione

bool fdf_set_javascript_action ( resource fdf_document, string fieldname, int trigger, string script )

La funzione fdf_set_javascript_action() imposta una azione javascript per il campo fieldname passato.

Vedere anche fdf_set_submit_form_action().

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_on_import_javascript -- Adds javascript code to be executed when Acrobat opens the FDF

Description

bool fdf_set_on_import_javascript ( resource fdfdoc, string script, bool before_data_import )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

See also fdf_add_doc_javascript() e fdf_set_javascript_action().

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_opt -- Imposta le opzioni per un campo

Descrizione

bool fdf_set_opt ( resource fdf_document, string fieldname, int element, string str1, string str2 )

La funzione fdf_set_opt() imposta le opzioni del campo fieldname dato.

Vedere anche fdf_set_flags().

fdf_set_status

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_status -- Imposta il valore per la chiave /STATUS

Descrizione

bool fdf_set_status ( resource fdf_document, string status )

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

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_submit_form_action -- Imposta un'azione per un campo nell'invio di un form

Descrizione

bool fdf_set_submit_form_action ( resource fdf_document, string fieldname, int trigger, string script, int flags )

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

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_target_frame -- Imposta il frame in cui visualizzare il form

Descrizione

bool fdf_set_target_frame ( resource fdf_document, string frame_name )

Imposta il frame in cui visualizzare il PDF risultante da fdf_save_file().

Vedere anche fdf_save_file().

fdf_set_value

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

fdf_set_value -- Imposta il valore di un campo

Descrizione

bool fdf_set_value ( resource fdf_document, string fieldname, mixed value [, int isName] )

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

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_version -- Imposta il numero di versione per un file FDF

Descrizione

string fdf_set_version ( resource fdf_document, string version )

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

XXXVII. Funzioni filePro

Introduzione

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


Installazione

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.

Sommario
filepro_fieldcount -- Conta quanti campi sono presenti in un database filePro
filepro_fieldname -- Restituisce il nome di un campo
filepro_fieldtype -- Restituisce il tipo del campo
filepro_fieldwidth -- Restituisce la dimensione di un campo
filepro_retrieve -- Preleva i dati da un database filePro
filepro_rowcount -- Conta quante righe sono presenti in un database filePro
filepro -- Legge e verifica la mappa del file

filepro_fieldcount

(PHP 3, PHP 4, PHP 5)

filepro_fieldcount -- Conta quanti campi sono presenti in un database filePro

Descrizione

int filepro_fieldcount ( void )

Restituisce il numero di campi (colonne) di un database filePro aperto.

Vedere anche filepro().

filepro_fieldname

(PHP 3, PHP 4, PHP 5)

filepro_fieldname -- Restituisce il nome di un campo

Descrizione

string filepro_fieldname ( int field_number )

Restituisce il nome del campo riferito all'indice inserito come parametro field_number.

filepro_fieldtype

(PHP 3, PHP 4, PHP 5)

filepro_fieldtype -- Restituisce il tipo del campo

Descrizione

string filepro_fieldtype ( int field_number )

Restituisce il tipo del campo riferito all'indice inserito come parametro field_number.

filepro_fieldwidth

(PHP 3, PHP 4, PHP 5)

filepro_fieldwidth -- Restituisce la dimensione di un campo

Descrizione

int filepro_fieldwidth ( int field_number )

Restituisce la lunghezza del campo riferito all'indice inserito come parametro field_number.

filepro_retrieve

(PHP 3, PHP 4, PHP 5)

filepro_retrieve -- Preleva i dati da un database filePro

Descrizione

string filepro_retrieve ( int row_number, int 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.

filepro_rowcount

(PHP 3, PHP 4, PHP 5)

filepro_rowcount -- Conta quante righe sono presenti in un database filePro

Descrizione

int filepro_rowcount ( void )

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

filepro

(PHP 3, PHP 4, PHP 5)

filepro -- Legge e verifica la mappa del file

Descrizione

bool filepro ( string directory )

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.

XXXVIII. Filesystem Functions


Requisiti

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.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione per Filesystem e Streams

NomeDefaultModificabile
allow_url_fopen"1"PHP_INI_SYSTEM
user_agentNULLPHP_INI_ALL
default_socket_timeout"60"PHP_INI_ALL
fromNULL??
auto_detect_line_endings"Off"PHP_INI_ALL

Breve descrizione dei parametri di configurazione.

allow_url_fopen boolean

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.

user_agent string

Definisce un agente utente il PHP.

default_socket_timeout integer

Timeout di default (in secondi) per gli stream sui socket.

Nota: Questa opzione di configurazione è stata inserita in PHP 4.3.0

from="joe@example.com" string

Imposta la password per l'ftp anonimo (il tuo indirizzo di posta elettronica).

auto_detect_line_endings boolean

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


Costanti predefinite

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.

GLOB_BRACE (integer)

GLOB_ONLYDIR (integer)

GLOB_MARK (integer)

GLOB_NOSORT (integer)

GLOB_NOCHECK (integer)

GLOB_NOESCAPE (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

FILE_USE_INCLUDE_PATH (integer)

FILE_APPEND (integer)

FILE_IGNORE_NEW_LINES (integer)

FILE_SKIP_EMPTY_LINES (integer)


Vedere anche:

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.

Sommario
basename -- Restituisce il nome del file dal percorso indicato
chgrp -- Cambia il gruppo del file
chmod -- Cambia le impostazioni del file
chown -- Cambia il proprietario del file
clearstatcache -- Libera la cache dello stato di un file
copy -- Copia un file
delete -- Vedere unlink() oppure unset()
dirname -- Restituisce il nome della directory dal percorso indicato
disk_free_space -- Restituisce lo spazio disponibile nella directory
disk_total_space -- Restituisce lo spazio totale di una directory
diskfreespace -- Alias di disk_free_space()
fclose -- Chiude un puntatore a file aperto
feof -- Verifica se è stata raggiunta la fine del file su un puntatore a file
fflush -- Invia l'output in un file
fgetc -- Prende un carattere da un puntatore a file
fgetcsv -- Prende una riga da un puntatore a file e l'analizza in cerca di campi CSV
fgets -- Prende una riga da un puntatore a file
fgetss -- Prende una riga da un puntatore a file ed elimina i tag HTML
file_exists -- Controlla se un file o directory esiste
file_get_contents -- Legge un file all'interno di una stringa
file_put_contents -- Write a string to a file
file -- Legge l'intero file in un vettore
fileatime -- Prende l'ora dell'ultimo accesso al file
filectime -- Prende l'ora in cui l'inode del file è stato modificato
filegroup -- Restituisce il gruppo di un file
fileinode -- Restituisce il numero di inode del file
filemtime -- Restituisce l'ora delle modifiche al file
fileowner -- Restituisce il proprietario del file
fileperms -- Restituisce i permessi sui file
filesize -- Restituisce la dimensione del file
filetype -- Restituisce il tipo di file
flock -- Sistema di bloccaggio file
fnmatch -- Match filename against a pattern
fopen -- Apre un file o un URL
fpassthru -- Invia tutti i dati rimanenti su un puntartore a file
fputcsv --  Format line as CSV and write to file pointer
fputs -- Alias di fwrite()
fread -- Legge un file salvaguardando la corrispondenza binaria
fscanf -- Analizza l'input da un file secondo un determinato formato
fseek -- Sposta un puntatore sul file
fstat -- Restituisce le informazioni riguardanti un file attraverso un puntatore al file aperto
ftell -- Comunica la posizione di lettura/scrittura del puntatore al file
ftruncate -- Tronca un file alla lunghezza data
fwrite -- Scrive un file salvaguardando la corrispondenza binaria
glob -- Find pathnames matching a pattern
is_dir -- Dice se la stringa corrisponde ad una directory
is_executable -- Dice se il file indicato è eseguibile
is_file -- Dice se il file è un file regolare
is_link -- Dice se il file è un link simbolico
is_readable -- Dice se un file è leggibile
is_uploaded_file -- Dice se un file fù caricato via HTTP POST.
is_writable -- Dice se un file è scrivibile
is_writeable -- Alias di is_writable()
link -- Crea un hard link
linkinfo -- Restituisce informazioni su un collegamento
lstat -- Da informazioni su un file o un link simbolico
mkdir -- Crea una directory
move_uploaded_file -- Muove un file caricato in una nuova posizione
parse_ini_file -- Legge il file di configurazione
pathinfo -- Restituisce informazioni su un percorso di file
pclose -- Chiude un puntatore ad un file di processo
popen -- Apre un puntatore ad un file di processo
readfile -- Invia un file
readlink -- Restituisce il target di un link simbolico
realpath -- Restituisce un percorso assoluto regolare
rename -- Rinomina un file o una directory
rewind -- Riavvolge la posizione di un puntatore a file
rmdir -- Rimuove una directory
set_file_buffer -- Alias di stream_set_write_buffer()
stat -- Da informazioni su un file
symlink -- Crea un link simbolico
tempnam -- Crea file con unico nome file
tmpfile -- Crea un file temporaneo
touch -- Imposta l'ora di modifica di un file
umask -- Cambia l'umask corrente
unlink -- Cancella un file

basename

(PHP 3, PHP 4, PHP 5)

basename -- Restituisce il nome del file dal percorso indicato

Descrizione

string basename ( string path [, string suffix] )

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

Esempio 1. Esempio di basename()

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);        // la variabile $file contiene "index.php"
$file = basename($path,".php"); // la variabile $file contiene "index"
?>

Nota: Il parametro suffix è stato aggiunto in PHP 4.1.0.

Vedere anche dirname()

chgrp

(PHP 3, PHP 4, PHP 5)

chgrp -- Cambia il gruppo del file

Descrizione

bool chgrp ( string filename, mixed group )

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.

Vedere anche chown() e chmod().

chmod

(PHP 3, PHP 4, PHP 5)

chmod -- Cambia le impostazioni del file

Descrizione

bool chmod ( string filename, int mode )

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.

Vedere anche chown() e chgrp().

chown

(PHP 3, PHP 4, PHP 5)

chown -- Cambia il proprietario del file

Descrizione

bool chown ( string filename, mixed user )

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

clearstatcache

(PHP 3, PHP 4, PHP 5)

clearstatcache -- Libera la cache dello stato di un file

Descrizione

void clearstatcache ( void )

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

copy

(PHP 3, PHP 4, PHP 5)

copy -- Copia un file

Descrizione

bool copy ( string source, string dest )

Copia il file source in dest. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. copy() example

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

$file = 'example.txt';
$newfile = 'example.txt.bak';

    if (!copy($file, $newfile)) {
    echo "Copia di $file non riuscita ...\n";
}
?>

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.

delete

(no version information, might be only in CVS)

delete -- Vedere unlink() oppure unset()

Descrizione

void delete ( string file )

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.

dirname

(PHP 3, PHP 4, PHP 5)

dirname -- Restituisce il nome della directory dal percorso indicato

Descrizione

string dirname ( string path )

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

Esempio 1. dirname() example

<?php
$path = "/etc/passwd";
$file = dirname($path); // $file contiene "/etc"
?>

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

disk_free_space

(PHP 4 >= 4.1.0, PHP 5)

disk_free_space -- Restituisce lo spazio disponibile nella directory

Descrizione

float disk_free_space ( string directory )

Data una stringa contenente una directory, questa funzione restituirà il numero di byte disponibili nel corrispondente filesystem o nella partizione corrispondente.

Esempio 1. Esempio disk_free_space()

<?php
// $df contiene il numero di byte disponibili in "/"
$df = disk_free_space("/"); 

// Con Windows:
disk_free_space("C:");
disk_free_space("D:");
?>

Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.

Vedere anche disk_total_space()

disk_total_space

(PHP 4 >= 4.1.0, PHP 5)

disk_total_space -- Restituisce lo spazio totale di una directory

Descrizione

float disk_total_space ( string directory )

Data una stringa contenente una directory, questa funzione restituirà il numero totale di byte del filesystem o della partizione corrispondente.

Esempio 1. disk_total_space() example

// $df contiene il numero totale di byte disponibile su "/"
$df = disk_total_space("/"); 

// Su Windows:
disk_total_space("C:");
disk_total_space("D:");
?>

Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.

Vedere anche disk_free_space()

diskfreespace

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

diskfreespace -- Alias di disk_free_space()

Descrizione

Questa funzione è un alias di disk_free_space().

fclose

(PHP 3, PHP 4, PHP 5)

fclose -- Chiude un puntatore a file aperto

Descrizione

bool fclose ( resource handle )

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

Esempio 1. Un semplice esempio di fclose()

<?php

  $handle = fopen('somefile.txt', 'r');
  
  fclose($handle);
  
?>

feof

(PHP 3, PHP 4, PHP 5)

feof -- Verifica se è stata raggiunta la fine del file su un puntatore a file

Descrizione

bool feof ( resource handle )

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

fflush

(PHP 4 >= 4.0.1, PHP 5)

fflush -- Invia l'output in un file

Descrizione

bool fflush ( resource handle )

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

fgetc

(PHP 3, PHP 4, PHP 5)

fgetc -- Prende un carattere da un puntatore a file

Descrizione

string fgetc ( resource handle )

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.

Esempio 1. Un esempio per fgetc()

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
    echo 'Non si riesce ad aprire il file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche fread(), fopen(), popen(), fsockopen() e fgets().

fgetcsv

(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

Descrizione

array fgetcsv ( resource handle [, int lunghezza [, string delimitatore [, string enclosure]]] )

handle

Un puntatore valido a un file che punta a un file aperto con successo da fopen(), popen(), o fsockopen().

length (Opzionale)

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.

delimiter (Opzionale)

Setta il delimitatore di campo (un solo carattere). Virgola per default.

enclosure (Opzionale)

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.

<?php
$row = 1;
$handle = fopen("test.csv","r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num campi sulla linea $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br>\n";
    }
}
fclose($handle);
?>

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.

Vedere anche explode(), file(), pack() e fputcsv().

fgets

(PHP 3, PHP 4, PHP 5)

fgets -- Prende una riga da un puntatore a file

Descrizione

string fgets ( resource handle, int length )

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:

Esempio 1. Legge un file riga per riga

<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($fd, 4096);
    echo $buffer;
}
fclose($handle);
?>

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

fgetss

(PHP 3, PHP 4, PHP 5)

fgetss -- Prende una riga da un puntatore a file ed elimina i tag HTML

Descrizione

string fgetss ( resource handle [, int length [, string allowable_tags]] )

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

file_exists

(PHP 3, PHP 4, PHP 5)

file_exists -- Controlla se un file o directory esiste

Descrizione

bool file_exists ( string filename )

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.

Esempio 1. Verificare l'esistenza di un file

<?php 
$filename = '/path/to/foo.txt'; 
 
if (file_exists($filename)) { 
    echo "il file $filename esiste"; 
} else { 
    echo "Il file $filename non esiste"; 
} 
?>

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

file_get_contents

(PHP 4 >= 4.3.0, PHP 5)

file_get_contents -- Legge un file all'interno di una stringa

Description

string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset]]] )

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

file_put_contents

(PHP 5)

file_put_contents -- Write a string to a file

Descrizione

int file_put_contents ( string filename, mixed data [, int flags [, resource context]] )

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

Elenco dei parametri

filename

The file name where to write the data

data

The data to write. Can be either a string, an array or a stream resource (explained above).

flags

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.

context

A context resource

Valori restituiti

The function returns the amount of bytes that were written to the file.

Log delle modifiche

VersioneDescrizione
5.1.0 Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

Note

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.

file

(PHP 3, PHP 4, PHP 5)

file -- Legge l'intero file in un vettore

Descrizione

array file ( string filename [, int use_include_path [, resource context]] )

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

fileatime

(PHP 3, PHP 4, PHP 5)

fileatime -- Prende l'ora dell'ultimo accesso al file

Descrizione

int fileatime ( string filename )

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

Esempio 1. Esempio per fileatime()

<?php

// visualizza, ad esempio, che somefile.txt è stato aperto il: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename è stato aperto il: " . date("F d Y H:i:s.", fileatime($filename));
}

?>

Vedere anche filemtime(), fileinode() e date().

filectime

(PHP 3, PHP 4, PHP 5)

filectime -- Prende l'ora in cui l'inode del file è stato modificato

Descrizione

int filectime ( string filename )

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

<?php
 
// Visualizza ad esempio:  somefile.txt è stato modificato: December 29 2002 22:16:23.
 
$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename è stato modificato: " . date("F d Y H:i:s.", filectime($filename));
}
 
?>

Vedere anche filemtime().

filegroup

(PHP 3, PHP 4, PHP 5)

filegroup -- Restituisce il gruppo di un file

Descrizione

int filegroup ( string filename )

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.

fileinode

(PHP 3, PHP 4, PHP 5)

fileinode -- Restituisce il numero di inode del file

Descrizione

int fileinode ( string filename )

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

filemtime

(PHP 3, PHP 4, PHP 5)

filemtime -- Restituisce l'ora delle modifiche al file

Descrizione

int filemtime ( string filename )

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.

Esempio 1. Esempio di uso di filemtime()

<?php
// ad esempio visualizzerà:  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

Vedere anche filectime(), stat(), touch() e getlastmod().

fileowner

(PHP 3, PHP 4, PHP 5)

fileowner -- Restituisce il proprietario del file

Descrizione

int fileowner ( string filename )

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

fileperms

(PHP 3, PHP 4, PHP 5)

fileperms -- Restituisce i permessi sui file

Descrizione

int fileperms ( string filename )

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 1. Mostra i permessi in valore ottale

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

Ciò produrrà il seguente output:

1777
0644

Esempio 2. Mostra gli interi permessi

<?php
$perms = fileperms('/etc/passwd');

if (($perms & 0xC000) == 0xC000) {
    // Socket
    $info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
    // Symbolic Link
    $info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
    // Regular
    $info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
    // Block special
    $info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
    // Directory
    $info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
    // Character special
    $info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
    // FIFO pipe
    $info = 'p';
} else {
    // Unknown
    $info = 'u';
}

// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x' ) :
            (($perms & 0x0800) ? 'S' : '-'));

// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x' ) :
            (($perms & 0x0400) ? 'S' : '-'));

// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x' ) :
            (($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

Ciò produrrà il seguente output:

-r--r--r--

Vedi anche is_readable(), e stat()

filesize

(PHP 3, PHP 4, PHP 5)

filesize -- Restituisce la dimensione del file

Descrizione

int filesize ( string filename )

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

Esempio 1. Esempio di uso di filesize()

<?php

// Ad esempio visualizzerà: somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Vedere anche file_exists()

filetype

(PHP 3, PHP 4, PHP 5)

filetype -- Restituisce il tipo di file

Descrizione

string filetype ( string filename )

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

Esempio 1. Esempio di uso di filetype()

<?php 
echo filetype('/etc/passwd');  // file 
echo filetype('/etc/');        // dir 
 
?>

Vedere anche: is_dir(), is_file(), is_link(), file_exists(), stat() e mime_content_type().

flock

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

flock -- Sistema di bloccaggio file

Descrizione

bool flock ( resource handle, int operation [, int &wouldblock] )

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.

Esempio 1. Esempio di uso di flock()

<?php
 
$fp = fopen("/tmp/lock.txt", "w+");
 
if (flock($fp, LOCK_EX)) { // Esegue un lock esclusivo
    fwrite($fp, "Write something here\n");
    flock($fp, LOCK_UN); // rilascia il lock
} else {
    echo "Non si riesce ad eseguire il lock del file !";
}
 
fclose($fp);
 
?>

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

(PHP 4 >= 4.3.0, PHP 5)

fnmatch -- Match filename against a pattern

Description

bool fnmatch ( string pattern, string string [, int flags] )

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.

Esempio 1. Checking a color name against a shell wildcard pattern.

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

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

fopen

(PHP 3, PHP 4, PHP 5)

fopen -- Apre un file o un URL

Descrizione

resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] )

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

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

Esempio 1. Esempi di fopen()

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

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

<?php
$handle = fopen("c:\\data\\info.txt", "r");
?>

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

fpassthru

(PHP 3, PHP 4, PHP 5)

fpassthru -- Invia tutti i dati rimanenti su un puntartore a file

Descrizione

int fpassthru ( resource handle )

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

<?php
 
// apre il file in modalità binaria
$name = ".\public\dev\img\ok.png";
$fp = fopen($name, 'rb');
 
// invia i giusti header
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
 
// invia l'immagine ed esce dallo script
fpassthru($fp);
exit;
 
?>

Vedere anche readfile(), fopen(), popen() e fsockopen()

fputcsv

(PHP 5 >= 5.1.0RC1)

fputcsv --  Format line as CSV and write to file pointer

Description

int fputcsv ( resource handle [, array fields [, string delimiter [, string enclosure]]] )

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

Esempio 1. fputcsv() example

<?php

$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {
    fputcsv($fp, split(',', $line));
}

fclose($fp);
?>

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

fputs

(PHP 3, PHP 4, PHP 5)

fputs -- Alias di fwrite()

Descrizione

fputs() è un alias di fwrite().

fread

(PHP 3, PHP 4, PHP 5)

fread -- Legge un file salvaguardando la corrispondenza binaria

Descrizione

string fread ( resource handle, int length )

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

fscanf

(PHP 4 >= 4.0.1, PHP 5)

fscanf -- Analizza l'input da un file secondo un determinato formato

Descrizione

mixed fscanf ( resource handle, string format [, mixed &...] )

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.

Esempio 1. Esempio di fscanf()

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf ($handle, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
    //... fai quacosa coi valori ...
}
fclose($handle);
?>

Esempio 2. Cntyennts of users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

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

fseek

(PHP 3, PHP 4, PHP 5)

fseek -- Sposta un puntatore sul file

Descrizione

int fseek ( resource handle, int offset [, int whence] )

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.

Esempio 1. Esempio di uso di fseek()

<?php
 
$fp = fopen('somefile.txt');

// Lettura di qualche dato
$data = fgets($fp, 4096);

// si torna ad inizio file
// come rewind($fp);
fseek($fp, 0);

?>

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.

Vedere anche ftell() e rewind().

fstat

(PHP 4, PHP 5)

fstat -- Restituisce le informazioni riguardanti un file attraverso un puntatore al file aperto

Descrizione

array fstat ( resource handle )

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

<?php

// apertura del file
$fp = fopen("/etc/passwd", "r");

// raccolta delle informazioni
$fstat = fstat($fp);

// chiusura del file
fclose($fp);

// scrittura della sola parte associativa
print_r(array_slice($fstat, 13));

?>

l'esempio visualizzerà :

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

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.

ftell

(PHP 3, PHP 4, PHP 5)

ftell -- Comunica la posizione di lettura/scrittura del puntatore al file

Descrizione

int ftell ( resource handle )

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

Esempio 1. Esempio di uso di ftell()

<?php

// apre un file e legge alcuni dati
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

Vedere anche fopen(), popen(), fseek() e rewind().

ftruncate

(PHP 4, PHP 5)

ftruncate -- Tronca un file alla lunghezza data

Descrizione

bool ftruncate ( resource handle, int size )

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.

Nota: Nelle versioni di PHP precedenti alla 4.3.3, la funzione ftruncate() restituisce un integer di valore 1 se l'operazione riesce, anziché restituire boolean TRUE.

See also fopen() and fseek().

fwrite

(PHP 3, PHP 4, PHP 5)

fwrite -- Scrive un file salvaguardando la corrispondenza binaria

Descrizione

int fwrite ( resource handle, string string [, int length] )

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

<?php
$filename = 'test.txt';
$somecontent = "Aggiunge questa riga al file\n";

// Verifica che il file esista e sia riscrivibile
if (is_writable($filename)) {

    // In questo esempio apriamo $filename in append mode.
    // Il puntatore del file è posizionato in fondo al file
    // è qui che verrà posizionato $somecontent quando eseguiremo fwrite().
    if (!$handle = fopen($filename, 'a')) {
         echo "Non si riesce ad aprire il file ($filename)";
         exit;
    }

    // Scrive $somecontent nel file aperto.
    if (!fwrite($handle, $somecontent) ===FALSE) {
        echo "Non si riesce a scrivere nel file ($filename)";
        exit;
    }

    echo "Riuscito, scritto ($somecontent) nel file ($filename)";

    fclose($handle);

} else {
    echo "Il file $filename non è accessibile";
}
?>

Vedere anche fread(), fopen(), fsockopen(), popen() e file_put_contents().

glob

(PHP 4 >= 4.3.0, PHP 5)

glob -- Find pathnames matching a pattern

Description

array glob ( string pattern [, int flags] )

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.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

Output will look something like:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.

See also opendir(), readdir(), closedir(), and fnmatch().

is_dir

(PHP 3, PHP 4, PHP 5)

is_dir -- Dice se la stringa corrisponde ad una directory

Descrizione

bool is_dir ( string filename )

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.

Esempio 1. Esempio di uso di is_dir()

<?
var_dump(is_dir('a_file.txt')) . "\n";
var_dump(is_dir('bogus_dir/abc')) . "\n";
var_dump(is_dir('..')); //su di una dir
?>

L'esempio precedente visualizzerà:

bool(false)
bool(false)
bool(true)

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

is_executable

(PHP 3, PHP 4, PHP 5)

is_executable -- Dice se il file indicato è eseguibile

Descrizione

bool is_executable ( string filename )

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.

Esempio 1. Esempio di uso di is_executable()

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
    echo $file.' è eseguibile';
} else {
    echo $file.' non è eseguibile';
}

?>

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_file() e is_link().

is_file

(PHP 3, PHP 4, PHP 5)

is_file -- Dice se il file è un file regolare

Descrizione

bool is_file ( string filename )

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

Vedere anche is_dir() e is_link().

is_link

(PHP 3, PHP 4, PHP 5)

is_link -- Dice se il file è un link simbolico

Descrizione

bool is_link ( string filename )

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

Vedere anche is_dir() e is_file().

is_readable

(PHP 3, PHP 4, PHP 5)

is_readable -- Dice se un file è leggibile

Descrizione

bool is_readable ( string filename )

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

is_uploaded_file

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file -- Dice se un file fù caricato via HTTP POST.

Descrizione

bool is_uploaded_file ( string filename )

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

<?php
/* Userland test for uploaded file. */
function is_uploaded_file($filename) 
{
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* User might have trailing slash in php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* This is how to use it, since you also don't have
 * move_uploaded_file() in these older versions: */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Possibile attacco su file in uploading: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

Vedi anche move_uploaded_file(), e la sezione Handling file uploads per un semplice esempio di utilizzo.

is_writable

(PHP 4, PHP 5)

is_writable -- Dice se un file è scrivibile

Descrizione

bool is_writable ( string filename )

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

is_writeable

(PHP 3, PHP 4, PHP 5)

is_writeable -- Alias di is_writable()

Descrizione

Questo è un alias per is_writable()

link

(PHP 3, PHP 4, PHP 5)

link -- Crea un hard link

Descrizione

bool link ( string target, string link )

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

(PHP 3, PHP 4, PHP 5)

linkinfo -- Restituisce informazioni su un collegamento

Descrizione

int linkinfo ( string path )

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.

Esempio 1. Esempio di uso di linkinfo()

<?php

echo linkinfo('/vmlinuz'); // 835

?>

Nota: Questa funzione non è implementata su piattaforme Windows

Vedere anche symlink(), link() e readlink().

lstat

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

lstat -- Da informazioni su un file o un link simbolico

Descrizione

array lstat ( string filename )

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

mkdir

(PHP 3, PHP 4, PHP 5)

mkdir -- Crea una directory

Descrizione

int mkdir ( string pathname [, int mode [, bool recursive [, resource context]]] )

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

Esempio 1. Esempio di uso di mkdir()

<?php
mkdir("/path/to/my/dir", 0700);
?>

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

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file -- Muove un file caricato in una nuova posizione

Descrizione

bool move_uploaded_file ( string filename, string destination )

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.

parse_ini_file

(PHP 4, PHP 5)

parse_ini_file -- Legge il file di configurazione

Descrizione

array parse_ini_file ( string filename [, bool process_sections] )

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 1. Contenuto di sample.ini

; Questo è un esempio di file di configurazione
; I commenti cominciano con ';', come in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = /usr/local/bin
URL = "http://www.example.com/~username"

Esempio 2. Esempio di uso di parse_ini_file()

<?php

define('BIRD', 'Dodo bird');

// Lettura senza sezioni
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Lettura con sezioni
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

?>

L'esempio produrrà:

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] = Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

)

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

(PHP 4 >= 4.0.3, PHP 5)

pathinfo -- Restituisce informazioni su un percorso di file

Descrizione

array pathinfo ( string path [, int options] )

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.

Esempio 1. pathinfo() Example

<?php 
       $path_parts = pathinfo('/www/htdocs/index.html');
       echo $path_parts['dirname'], "\n"; 
       echo $path_parts['basename'], "\n"; 
       echo $path_parts['extension'], "\n"; 
       
       ?>

Produrrà:

/www/htdocs 
 index.html 
 html

Nota: Per informazioni su come recuperare il path corrente, leggere la sezione su variabili riservate predefinite.

Vedere anche dirname(), basename(), parse_url() e realpath().

pclose

(PHP 3, PHP 4, PHP 5)

pclose -- Chiude un puntatore ad un file di processo

Descrizione

int pclose ( resource handle )

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

popen

(PHP 3, PHP 4, PHP 5)

popen -- Apre un puntatore ad un file di processo

Descrizione

resource popen ( string command, string mode )

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

Esempio 1. Esempio di uso di popen()

<?php
$handle = popen("/bin/ls", "r");
?>

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

readfile

(PHP 3, PHP 4, PHP 5)

readfile -- Invia un file

Descrizione

int readfile ( string filename [, bool use_include_path [, resource context]] )

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

(PHP 3, PHP 4, PHP 5)

readlink -- Restituisce il target di un link simbolico

Descrizione

string readlink ( string path )

readlink() si comporta analogamente alla funzione readlink di C e restituisce i conenuti del link simbolico path oppure FALSE in caso d'errore.

Esempio 1. Esempio di uso di readlink()

<?php
// ad esempio visualizza /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

Nota: Questa funzione non è implementata su piattaforme Windows

Vedere anche symlink(), readlink() e linkinfo().

realpath

(PHP 4, PHP 5)

realpath -- Restituisce un percorso assoluto regolare

Descrizione

string realpath ( string path )

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.

Esempio 1. Esempio di realpath()

<?php
$real_path = realpath("../../index.php");
?>

Vedere anche basename(), dirname() e pathinfo().

rename

(PHP 3, PHP 4, PHP 5)

rename -- Rinomina un file o una directory

Descrizione

bool rename ( string oldname, string newname [, resource context] )

Tenta di rinominare oldname in newname.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. Esempio di uso di rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

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

rewind

(PHP 3, PHP 4, PHP 5)

rewind -- Riavvolge la posizione di un puntatore a file

Descrizione

bool rewind ( resource handle )

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.

Vedere anche fseek() e ftell().

rmdir

(PHP 3, PHP 4, PHP 5)

rmdir -- Rimuove una directory

Descrizione

bool rmdir ( string dirname [, resource context] )

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.

Vedere anche mkdir() e unlink().

set_file_buffer

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

set_file_buffer -- Alias di stream_set_write_buffer()

Descrizione

Questa funzione è un alias di stream_set_write_buffer().

stat

(PHP 3, PHP 4, PHP 5)

stat -- Da informazioni su un file

Descrizione

array stat ( string filename )

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 numericoAssociativo (da PHP 4.0.6)Descrizione
0devdevice
1inoinode
2modemodalità di protezione dell'inode
3nlinknumero di link
4uidID utente del proprietario
5gidID del gruppo del proprietario
6rdevtipo di device con l'inode device *
7sizedimensione in byte
8atimeora dell'ultimo accesso (Unix timestamp)
9mtimeora del'ultima modifica (Unix timestamp)
10ctimeora dell'ultimo cambiamento di inode(Unix timestamp)
11blksizedimensione del blocco per l'I/O di filesystem *
12blocksnumero dei blocchi allocati
* - valida solo su sistemi che supportano il tipo st_blksize--altri sistemi (ad esempio Windows) restituiscono -1.

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

(PHP 3, PHP 4, PHP 5)

symlink -- Crea un link simbolico

Descrizione

bool symlink ( string target, string link )

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

tempnam

(PHP 3, PHP 4, PHP 5)

tempnam -- Crea file con unico nome file

Descrizionen

string tempnam ( string dir, string prefix )

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.

Esempio 1. tempnam() esempio

<?php $tmpfname = tempnam("/tmp", "FOO"); 
       
       $handle = fopen($tmpfname, "w"); 
       fwrite($handle, "writing to tempfile"); 
       fclose($handle); 
       
       // do here something 
       
       unlink($tmpfname); 
       ?>

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.

Vedere anche tmpfile() and unlink().

tmpfile

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

tmpfile -- Crea un file temporaneo

Descrizione

resource tmpfile ( void )

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.

Esempio 1. tmpfile() example

<?php 
         $temp = tmpfile(); 
         fwrite($temp, "writing to tempfile"); 
         fseek($temp, 0);
         echo fread($temp, 1024);
         fclose($temp);  // this removes the file 
         ?>

Il precedente esempio visualizzerà:

writing toi tempfile

Vedere anche tempnam().

touch

(PHP 3, PHP 4, PHP 5)

touch -- Imposta l'ora di modifica di un file

Descrizione

bool touch ( string filename [, int time [, int atime]] )

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.

Esempio 1. touch() example

<?php
if (touch($FileName)) {
    echo "$FileName modification time has been changed to present time";
} else {
    echo "Sorry, could not change modification time of $FileName";
}
?>

umask

(PHP 3, PHP 4, PHP 5)

umask -- Cambia l'umask corrente

Descrizione

int umask ( [int mask] )

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.

unlink

(PHP 3, PHP 4, PHP 5)

unlink -- Cancella un file

Descrizione

bool unlink ( string filename [, resource context] )

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.

XXXIX. Funzioni Firebird/InterBase

Introduzione

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:

magic_quotes_sybase = On


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione di InterBase

NomeDefaultModificabile
ibase.allow_persistent"On"PHP_INI_SYSTEM
ibase.max_persistent"-1"PHP_INI_SYSTEM
ibase.max_links"-1"PHP_INI_SYSTEM
ibase.default_dbNULLPHP_INI_SYSTEM
ibase.default_userNULLPHP_INI_ALL
ibase.default_passwordNULLPHP_INI_ALL
ibase.default_charsetNULLPHP_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
Per maggiori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

ibase.allow_persistent boolean

Stabilisce se permettere o meno le connessioni persistenti a Firebird/InterBase.

ibase.max_persistent integer

Indica il numero massimo di connessioni persistenti a Firebird/InterBase per processo. Le ulteriori connessioni create con ibase_pconnect() saranno non persistenti.

ibase.max_links integer

Indica il numero massimo di connessioni a Firebird/InterBase per processo, incluse le connessioni persistenti.

ibase.default_db string

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.

ibase.default_user string

Il nome utente da utilizzarsi per la connessione al database se non viene specificato.

ibase.default_password string

La password da utilizzare per connettersi al database se non viene specificata in fase di connessione.

ibase.default_charset string

Il set di caratteri da utilizzare per la connessione al database se non ne viene specificato uno al momento della connessione.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

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.


Costanti predefinite

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

CostanteDescrizione
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_READInizia una transazione di sola lettura.
IBASE_WRITEInizia una transazione di lettura/scrittura.
IBASE_CONSISTENCYInizia 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_CONCURRENCYInizia 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_COMMITTEDInizia 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_WAITIndica che la transazione deve attendere e riprovare in caso di conflitto.
IBASE_NOWAITIndica 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

CostanteDescrizione
IBASE_FETCH_BLOBSDisponibile 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_ARRAYSForza 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_UNIXTIMEIndica 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.

IBASE_BKP_IGNORE_CHECKSUMS

IBASE_BKP_IGNORE_LIMBO

IBASE_BKP_METADATA_ONLY

IBASE_BKP_NO_GARBAGE_COLLECT

IBASE_BKP_OLD_DESCRIPTIONS

IBASE_BKP_NON_TRANSPORTABLE

IBASE_BKP_CONVERT

Options to ibase_backup()()

IBASE_RES_DEACTIVATE_IDX

IBASE_RES_NO_SHADOW

IBASE_RES_NO_VALIDITY

IBASE_RES_ONE_AT_A_TIME

IBASE_RES_REPLACE

IBASE_RES_CREATE

IBASE_RES_USE_ALL_SPACE

Options to ibase_restore()

IBASE_PRP_PAGE_BUFFERS

IBASE_PRP_SWEEP_INTERVAL

IBASE_PRP_SHUTDOWN_DB

IBASE_PRP_DENY_NEW_TRANSACTIONS

IBASE_PRP_DENY_NEW_ATTACHMENTS

IBASE_PRP_RESERVE_SPACE

IBASE_PRP_RES_USE_FULL

IBASE_PRP_RES

IBASE_PRP_WRITE_MODE

IBASE_PRP_WM_ASYNC

IBASE_PRP_WM_SYNC

IBASE_PRP_ACCESS_MODE

IBASE_PRP_AM_READONLY

IBASE_PRP_AM_READWRITE

IBASE_PRP_SET_SQL_DIALECT

IBASE_PRP_ACTIVATE

IBASE_PRP_DB_ONLINE

IBASE_RPR_CHECK_DB

IBASE_RPR_IGNORE_CHECKSUM

IBASE_RPR_KILL_SHADOWS

IBASE_RPR_MEND_DB

IBASE_RPR_VALIDATE_DB

IBASE_RPR_FULL

IBASE_RPR_SWEEP_DB

Options to ibase_maintain_db()

IBASE_STS_DATA_PAGES

IBASE_STS_DB_LOG

IBASE_STS_HDR_PAGES

IBASE_STS_IDX_PAGES

IBASE_STS_SYS_RELATIONS

Options to ibase_db_info()

IBASE_SVC_SERVER_VERSION

IBASE_SVC_IMPLEMENTATION

IBASE_SVC_GET_ENV

IBASE_SVC_GET_ENV_LOCK

IBASE_SVC_GET_ENV_MSG

IBASE_SVC_USER_DBPATH

IBASE_SVC_SVR_DB_INFO

IBASE_SVC_GET_USERS

Opzioni per ibase_server_info()

Sommario
ibase_add_user --  Add a user to a security database (only for IB6 or later)
ibase_affected_rows --  Return the number of rows that were affected by the previous query
ibase_backup --  Initiates a backup task in the service manager and returns immediately
ibase_blob_add --  Aggiunge dati in un nuovo blob creato
ibase_blob_cancel --  Cancella la creazione di un blob
ibase_blob_close --  Chiude un blob
ibase_blob_create --  Crea un nuovo blob per aggiungerci dei dati
ibase_blob_echo --  Visualizza il contenuto di un blob sul browser
ibase_blob_get --  Ottiene len byte di dati dal blob aperto
ibase_blob_import --  Create un blob, copy il file al suo interno e lo chiude
ibase_blob_info --  Restituisce la lunghezza del blob e altre informazioni utlili
ibase_blob_open --  Apre un blob per ricavare parte di dati
ibase_close --  Chiude una connessione ad un database InterBase
ibase_commit_ret -- Commit a transaction without closing it
ibase_commit -- Esegue il commit di una transazione
ibase_connect --  Apre una connessione con un database InterBase
ibase_db_info --  Request statistics about a database
ibase_delete_user --  Delete a user from a security database (only for IB6 or later)
ibase_drop_db --  Drops a database
ibase_errcode --  Return an error code
ibase_errmsg --  Restituisce messaggi di errore
ibase_execute -- Esegue una query preparata in precedenza
ibase_fetch_assoc --  Fetch a result row from a query as an associative array
ibase_fetch_object -- Ottiene un oggetto da un database InterBase
ibase_fetch_row -- Elabora una riga da un database InterBase
ibase_field_info --  Ottiene informazioni su un campo
ibase_free_event_handler --  Cancels a registered event handler
ibase_free_query --  Libera la memoria allocata da una query preparata
ibase_free_result -- Libera la memoria allocata da un result set
ibase_gen_id --  Increments the named generator and returns its new value
ibase_maintain_db --  Execute a maintenance command on the database server
ibase_modify_user --  Modify a user to a security database (only for IB6 or later)
ibase_name_result --  Assigns a name to a result set
ibase_num_fields --  Ottiene il numero di campi in un result set
ibase_num_params --  Return the number of parameters in a prepared query
ibase_param_info --  Return information about a parameter in a prepared query
ibase_pconnect --  Crea una connessione persistente ad un database Interbase
ibase_prepare --  Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione
ibase_query -- Esegue una query su di un database InterBase
ibase_restore --  Initiates a restore task in the service manager and returns immediately
ibase_rollback_ret -- Roll back a transaction without closing it
ibase_rollback -- Esegue il roll back di una transazione
ibase_server_info --  Request information about a database server
ibase_service_attach --  Connect to the service manager
ibase_service_detach --  Disconnect from the service manager
ibase_set_event_handler --  Register a callback function to be called when events are posted
ibase_timefmt --  Imposta il formato delle colonne timestamp, date e time restituite dalle query
ibase_trans -- Inizia una transazione
ibase_wait_event --  Wait for an event to be posted by the database

ibase_add_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_add_user --  Add a user to a security database (only for IB6 or later)

Description

bool ibase_add_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

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

ibase_affected_rows

(PHP 5)

ibase_affected_rows --  Return the number of rows that were affected by the previous query

Description

int ibase_affected_rows ( [resource link_identifier] )

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

ibase_backup

(PHP 5)

ibase_backup --  Initiates a backup task in the service manager and returns immediately

Description

mixed ibase_backup ( resource service_handle, string source_db, string dest_file [, int options [, bool verbose]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_blob_add

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_add --  Aggiunge dati in un nuovo blob creato

Descrizione

bool ibase_blob_add ( resource blob_handle, string data )

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

ibase_blob_cancel

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_cancel --  Cancella la creazione di un blob

Descrizione

bool ibase_blob_cancel ( resource blob_handle )

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

ibase_blob_close

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_close --  Chiude un blob

Descrizione

mixed ibase_blob_close ( resource blob_handle )

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

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_create --  Crea un nuovo blob per aggiungerci dei dati

Descrizione

resource ibase_blob_create ( [resource link_identifier] )

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

ibase_blob_echo

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_echo --  Visualizza il contenuto di un blob sul browser

Descrizione

bool ibase_blob_echo ( string blob_id )

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

ibase_blob_get

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_get --  Ottiene len byte di dati dal blob aperto

Descrizione

string ibase_blob_get ( resource blob_handle, int len )

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

Questo esempio non fa altro che 'ibase_blob_echo($data->BLOB_VALUE)', mostra come ottenere le informazioni in una variabile $variable da manipolare a piacere.

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

ibase_blob_import

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_import --  Create un blob, copy il file al suo interno e lo chiude

Descrizione

string ibase_blob_import ( [resource link_identifier, resource file_handle] )

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

ibase_blob_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_info --  Restituisce la lunghezza del blob e altre informazioni utlili

Descrizione

array ibase_blob_info ( string blob_id )

La 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

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_blob_open --  Apre un blob per ricavare parte di dati

Descrizione

resource ibase_blob_open ( string blob_id )

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

ibase_close

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_close --  Chiude una connessione ad un database InterBase

Descrizione

bool ibase_close ( [resource connection_id] )

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

ibase_commit_ret

(PHP 5)

ibase_commit_ret -- Commit a transaction without closing it

Description

bool ibase_commit_ret ( [resource link_or_trans_identifier] )

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.

ibase_commit

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_commit -- Esegue il commit di una transazione

Descrizione

bool ibase_commit ( [resource link_identifier] )

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.

ibase_connect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_connect --  Apre una connessione con un database InterBase

Descrizione

resource ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]] )

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

<?php
    $host = 'localhost:/path/to/your.gdb';

    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row->email . "\n";
    }
    ibase_free_result($sth);
    ibase_close($dbh);
?>

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

ibase_db_info

(PHP 5)

ibase_db_info --  Request statistics about a database

Description

string ibase_db_info ( resource service_handle, string db, int action [, int argument] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_delete_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_delete_user --  Delete a user from a security database (only for IB6 or later)

Description

bool ibase_delete_user ( resource service_handle, string user_name )

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

ibase_drop_db

(PHP 5)

ibase_drop_db --  Drops a database

Description

bool ibase_drop_db ( [resource connection] )

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

ibase_errcode

(PHP 5)

ibase_errcode --  Return an error code

Description

int ibase_errcode ( void )

Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.

See also ibase_errmsg().

ibase_errmsg

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_errmsg --  Restituisce messaggi di errore

Descrizione

string ibase_errmsg ( void )

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

ibase_execute

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_execute -- Esegue una query preparata in precedenza

Descrizione

resource ibase_execute ( resource query [, int bind_args] )

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

<?php

    $dbh = ibase_connect($host, $username, $password);

    $updates = array(
        1 => 'Eric',
        5 => 'Filip',
        7 => 'Larry'
    );

    $query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

    while (list($baz, $bar) = each($updates)) {
        ibase_execute($query, $bar, $baz);
    }
?>

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

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc --  Fetch a result row from a query as an associative array

Description

array ibase_fetch_assoc ( resource result [, int fetch_flag] )

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

ibase_fetch_object

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_fetch_object -- Ottiene un oggetto da un database InterBase

Descrizione

object ibase_fetch_object ( resource result_id [, int fetch_flag] )

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

ibase_fetch_row

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_fetch_row -- Elabora una riga da un database InterBase

Descrizione

array ibase_fetch_row ( int result_identifier )

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.

ibase_field_info

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_field_info --  Ottiene informazioni su un campo

Descrizione

array ibase_field_info ( int result, int field number )

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

ibase_free_event_handler

(PHP 5)

ibase_free_event_handler --  Cancels a registered event handler

Description

bool ibase_free_event_handler ( resource event )

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

ibase_free_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_query --  Libera la memoria allocata da una query preparata

Descrizione

int ibase_free_query ( int query )

Libera una query preparata da ibase_prepare().

ibase_free_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_free_result -- Libera la memoria allocata da un result set

Descrizione

int ibase_free_result ( int result_identifier )

Libera un result set che è stato creato da ibase_query().

ibase_gen_id

(PHP 5)

ibase_gen_id --  Increments the named generator and returns its new value

Description

mixed ibase_gen_id ( string generator [, int increment [, resource link_identifier]] )

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.

ibase_maintain_db

(PHP 5)

ibase_maintain_db --  Execute a maintenance command on the database server

Description

bool ibase_maintain_db ( resource service_handle, string db, int action [, int argument] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user --  Modify a user to a security database (only for IB6 or later)

Description

bool ibase_modify_user ( resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]] )

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

ibase_name_result

(PHP 5)

ibase_name_result --  Assigns a name to a result set

Description

bool ibase_name_result ( resource result, string name )

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

ibase_num_fields

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_num_fields --  Ottiene il numero di campi in un result set

Descrizione

int ibase_num_fields ( int result_id )

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

ibase_num_params

(PHP 5)

ibase_num_params --  Return the number of parameters in a prepared query

Description

int ibase_num_params ( resource query )

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

ibase_param_info

(PHP 5)

ibase_param_info --  Return information about a parameter in a prepared query

Description

array ibase_param_info ( resource query, int param_number )

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

ibase_pconnect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_pconnect --  Crea una connessione persistente ad un database Interbase

Descrizione

int ibase_pconnect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]] )

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

ibase_prepare

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_prepare --  Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione

Descrizione

int ibase_prepare ( [int link_identifier, string query] )

Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione (tramite ibase_execute()).

ibase_query

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ibase_query -- Esegue una query su di un database InterBase

Descrizione

int ibase_query ( [int link_identifier, string query [, int bind_args]] )

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

ibase_restore

(PHP 5)

ibase_restore --  Initiates a restore task in the service manager and returns immediately

Description

mixed ibase_restore ( resource service_handle, string source_file, string dest_db [, int options [, bool verbose]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_rollback_ret

(PHP 5)

ibase_rollback_ret -- Roll back a transaction without closing it

Description

bool ibase_rollback_ret ( [resource link_or_trans_identifier] )

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.

ibase_rollback

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_rollback -- Esegue il roll back di una transazione

Descrizione

int ibase_rollback ( [int link_identifier, int trans_number] )

Rolls back transaction trans_number which was created with ibase_trans().

ibase_server_info

(PHP 5)

ibase_server_info --  Request information about a database server

Description

string ibase_server_info ( resource service_handle, int action )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_service_attach

(PHP 5)

ibase_service_attach --  Connect to the service manager

Description

resource ibase_service_attach ( string host, string dba_username, string dba_password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_service_detach

(PHP 5)

ibase_service_detach --  Disconnect from the service manager

Description

bool ibase_service_detach ( resource service_handle )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ibase_set_event_handler

(PHP 5)

ibase_set_event_handler --  Register a callback function to be called when events are posted

Description

resource ibase_set_event_handler ( callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

resource ibase_set_event_handler ( resource connection, callback event_handler, string event_name1 [, string event_name2 [, string ...]] )

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

ibase_timefmt

(PHP 3 >= 3.0.6, PHP 4)

ibase_timefmt --  Imposta il formato delle colonne timestamp, date e time restituite dalle query

Descrizione

int ibase_timefmt ( string format [, int columntype] )

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

ibase_trans

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ibase_trans -- Inizia una transazione

Descrizione

int ibase_trans ( [int trans_args [, int link_identifier]] )

Inizia una transazione.

ibase_wait_event

(PHP 5)

ibase_wait_event --  Wait for an event to be posted by the database

Description

string ibase_wait_event ( string event_name1 [, string event_name2 [, string ...]] )

string ibase_wait_event ( resource connection, string event_name1 [, string event_name2 [, string ...]] )

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

XL. Firebird/Interbase Functions (PDO_FIREBIRD)

Introduzione

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.

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird and Interbase databases.

Sommario
PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databases

PDO_FIREBIRD DSN

(no version information, might be only in CVS)

PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databases

Descrizione

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

DataSource

The hostname on which the database server resides.

Port

The port number for the server on which the database is running.

Database

The name of the database.

User

The name of the user that will connect to the database.

Password

The password for the user.

Esempi

Esempio 1. PDO_FIREBIRD DSN examples

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird and Interbase databases:
firebird:User=john;Password=mypass;Database=DATABASE.GDE;DataSource=localhost;Port=3050

XLI. Funzioni FriBiDi

Introduzione

FriBiDi è un'implementazione free del Unicode Bidirectional Algorithm.


Requisiti

Occorre scaricare ed installare il pacchetto FriBiDi.


Installazione

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


Costanti predefinite

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.

FRIBIDI_CHARSET_UTF8 (integer)

FRIBIDI_CHARSET_8859_6 (integer)

FRIBIDI_CHARSET_8859_8 (integer)

FRIBIDI_CHARSET_CP1255 (integer)

FRIBIDI_CHARSET_CP1256 (integer)

FRIBIDI_CHARSET_ISIRI_3342 (integer)

Sommario
fribidi_log2vis -- Converte una stringa logica in una visuale

fribidi_log2vis

(PHP 4 >= 4.0.4, PECL)

fribidi_log2vis -- Converte una stringa logica in una visuale

Descrizione

string fribidi_log2vis ( string str, string direction, int charset )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

XLII. FrontBase Functions

Introduzione

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.


Requisiti

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


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione per FrontBase

NomeDefaultModificabile
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_hostNULLPHP_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
Per maggiori dettagli e per le definizioni delle costanti PHP_INI_* vedere ini_set().


Costanti predefinite

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.

FBSQL_ASSOC (integer)

FBSQL_NUM (integer)

FBSQL_BOTH (integer)

FBSQL_LOCK_DEFERRED (integer)

FBSQL_LOCK_OPTIMISTIC (integer)

FBSQL_LOCK_PESSIMISTIC (integer)

FBSQL_ISO_READ_UNCOMMITTED (integer)

FBSQL_ISO_READ_COMMITTED (integer)

FBSQL_ISO_REPEATABLE_READ (integer)

FBSQL_ISO_SERIALIZABLE (integer)

FBSQL_ISO_VERSIONED (integer)

FBSQL_UNKNOWN (integer)

FBSQL_STOPPED (integer)

FBSQL_STARTING (integer)

FBSQL_RUNNING (integer)

FBSQL_STOPPING (integer)

FBSQL_NOEXEC (integer)

FBSQL_LOB_DIRECT (integer)

FBSQL_LOB_HANDLE (integer)

Sommario
fbsql_affected_rows --  Restituisce il numero di righe (tuple) interessate nella precedente operazione di FrontBase
fbsql_autocommit -- Abilita o disabilita autocommit
fbsql_blob_size --  Get the size of a BLOB
fbsql_change_user -- Cambia l'identità dell'utente connesso con una connessione attiva
fbsql_clob_size --  Get the size of a CLOB
fbsql_close -- Chiude la connessione a FrontBase
fbsql_commit -- Compie una transazione
fbsql_connect -- Apre una connessione al Server FrontBase
fbsql_create_blob -- Crea un BLOB
fbsql_create_clob -- Crea un CLOB
fbsql_create_db -- Crea un database
fbsql_data_seek -- Sposta il puntatore del risultato interno
fbsql_database_password --  Imposta o ricerca la password di un database FrontBase.
fbsql_database -- Imposta oppure ottiene il nome del database usato per la connessione
fbsql_db_query -- Manda una query FrontBase
fbsql_db_status -- Restituisce lo stato di un dato database.
fbsql_drop_db -- Cancella un database FrontBase
fbsql_errno --  Ritorna il valore numerico del messaggio di errore emesso dalla precedente operazione FrontBase.
fbsql_error --  Ritorna il testo del messaggio di errore emesso dalla precedente operazione FrontBase.
fbsql_fetch_array --  Restituisce una riga (tupla) di risultato in forma di Array associativo, Array enumerato o entrambi
fbsql_fetch_assoc --  Restituisce una riga (tupla) di risultato in forma di Array associativo.
fbsql_fetch_field --  Ottiene informazioni su una colonna da un set di risultati come oggetto
fbsql_fetch_lengths --  Ottiene la lunghezza di ciascun output in un set di risultati
fbsql_fetch_object -- Resituisce un riga da un set di risultati come oggetto
fbsql_fetch_row -- Ottiene una riga come matrice numerata
fbsql_field_flags --  Ottiene i flag associati al campo specificato
fbsql_field_len --  Restituisce la lunghezza di un campo
fbsql_field_name --  Restituisce il nome del campo specificato
fbsql_field_seek --  Imposta il puntatore del set di risultati ad un specifico indice di campo
fbsql_field_table --  Ottiene il nome della tabella in cui si trova il campo
fbsql_field_type --  Ottiene il tipo del campo specificato
fbsql_free_result -- Libera la memoria da un set di risultati
fbsql_get_autostart_info -- Nessuna descrizione fornita, per ora
fbsql_hostname -- Ottiene o imposta il nome del server per la connessione
fbsql_insert_id --  restituisce l'id generato dalla precedente operazione di INSERT
fbsql_list_dbs --  Elenca i database presenti su un server FrontBase
fbsql_list_fields -- Elenca i campi di un set di risultati
fbsql_list_tables -- Elenxa le tabelle presenti in un database FrontBase
fbsql_next_result --  Muove il puntatore interno al risultato successivo
fbsql_num_fields -- Ottiene il numero dei campi presenti in un set di risultati
fbsql_num_rows -- Restituisce il numero di righe presenti in un set di risultati
fbsql_password -- Ottiene o imposta la password per la connessione
fbsql_pconnect --  Apre una connessione persistente ad un server FrontBase
fbsql_query -- Invia una query a FrontBase
fbsql_read_blob -- Legge un BLOB dal database
fbsql_read_clob -- Legge un CLOB dal database
fbsql_result -- Restituisce i dati di una query
fbsql_rollback -- Esegue il rollback della transazione
fbsql_select_db -- Seleziona un database FrontBase
fbsql_set_lob_mode --  Imposta la modalità LOB in un set di risultati FrontBase
fbsql_set_password --  Change the password for a given user
fbsql_set_transaction --  Imposta i lock e l'isolamento delle transazioni
fbsql_start_db -- Attiva un database locale o remoto
fbsql_stop_db -- Ferma un database locale o remoto
fbsql_tablename -- Restituisce il nome della tabella dei campi
fbsql_username -- Ottiene o imposta l'utente per la connessione
fbsql_warnings -- Abilita o disabilita i warnings FrontBase

fbsql_affected_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_affected_rows --  Restituisce il numero di righe (tuple) interessate nella precedente operazione di FrontBase

Descrizione

int fbsql_affected_rows ( [int link_identifier] )

fbsql_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

(PHP 4 >= 4.0.6, PHP 5)

fbsql_autocommit -- Abilita o disabilita autocommit

Descrizione

bool fbsql_autocommit ( resource link_identifier [, bool OnOff] )

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

fbsql_blob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_blob_size --  Get the size of a BLOB

Descrizione

int fbsql_blob_size ( string blob_handle [, resource link_identifier] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_change_user

(no version information, might be only in CVS)

fbsql_change_user -- Cambia l'identità dell'utente connesso con una connessione attiva

Descrizione

resource fbsql_change_user ( string user, string password [, string database [, int link_identifier]] )

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

fbsql_clob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_clob_size --  Get the size of a CLOB

Descrizione

int fbsql_clob_size ( string clob_handle [, resource link_identifier] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_close

(PHP 4 >= 4.0.6, PHP 5)

fbsql_close -- Chiude la connessione a FrontBase

Descrizione

boolean fbsql_close ( [resource link_identifier] )

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.

Esempio 1. Uso di fbsql_close()

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);
?>

Vedere anche: fbsql_connect() e fbsql_pconnect().

fbsql_commit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_commit -- Compie una transazione

Descrizione

bool fbsql_commit ( [resource link_identifier] )

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

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_connect -- Apre una connessione al Server FrontBase

Descrizione

resource fbsql_connect ( [string hostname [, string username [, string password]]] )

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

Esempio 1. fbsql_connect()

<?php

    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);

?>

Vedere anche fbsql_pconnect() e fbsql_close().

fbsql_create_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_blob -- Crea un BLOB

Descrizione

string fbsql_create_blob ( string blob_data [, resource link_identifier] )

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

<?php
    $link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
        or die("Could not connect");
    $filename = "blobfile.bin";
    $fp = fopen($filename, "rb");
    $blobdata = fread($fp, filesize($filename));
    fclose($fp);
    
    $blobHandle = fbsql_create_blob($blobdata, $link);
    
    $sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
    $rs = fbsql_query($sql, $link);
?>

Vedere anche: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().

fbsql_create_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_clob -- Crea un CLOB

Descrizione

string fbsql_create_clob ( string clob_data [, resource link_identifier] )

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

<?php
    $link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
        or die("Could not connect");
    $filename = "clob_file.txt";
    $fp = fopen($filename, "rb");
    $clobdata = fread($fp, filesize($filename));
    fclose($fp);
    
    $clobHandle = fbsql_create_clob($clobdata, $link);
    
    $sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
    $rs = fbsql_query($sql, $link);
?>

Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().

fbsql_create_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_create_db -- Crea un database

Descrizione

bool fbsql_create_db ( string database name [, resource link_identifier] )

fbsql_create_db() crea un nuovo database FrontBase sul server, identificato dal parametro link_identifier.

Esempio 1. fbsql_create_db()

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    if (fbsql_create_db ("my_db")) {
        print("Database created successfully\n");
    } else {
        printf("Error creating database: %s\n", fbsql_error ());
    }
?>

Vedere anche fbsql_drop_db().

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_data_seek -- Sposta il puntatore del risultato interno

Descrizione

bool fbsql_data_seek ( resource result_identifier, int row_number )

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
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");

    fbsql_select_db ("samp_db")
        or die ("Could not select database");

    $query = "SELECT last_name, first_name FROM friends;";
    $result = fbsql_query ($query)
        or die ("Query failed");

    # fetch rows in reverse order

    for ($i = fbsql_num_rows ($result) - 1; $i >=0; $i--) {
        if (!fbsql_data_seek ($result, $i)) {
            printf ("Cannot seek to row %d\n", $i);
            continue;
        }

        if(!($row = fbsql_fetch_object ($result)))
            continue;

        printf("%s %s<BR>\n", $row->last_name, $row->first_name);
    }

    fbsql_free_result ($result);
?>

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database_password --  Imposta o ricerca la password di un database FrontBase.

Descrizione

string fbsql_database_password ( resource link_identifier [, string database_password] )

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

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    fbsql_database_password($link, "secret db password");
    fbsql_select_db($database, $link);
?>

Vedere anche: fbsql_connect(), fbsql_pconnect() e fbsql_select_db().

fbsql_database

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database -- Imposta oppure ottiene il nome del database usato per la connessione

Descrizione

string fbsql_database ( resource link_identifier [, string database] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_db_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_db_query -- Manda una query FrontBase

Descrizione

resource fbsql_db_query ( string database, string query [, resource link_identifier] )

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

fbsql_db_status

(PHP 4 >= 4.1.0, PHP 5)

fbsql_db_status -- Restituisce lo stato di un dato database.

Descrizione

int fbsql_db_status ( string database_name [, resource link_identifier] )

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

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_drop_db -- Cancella un database FrontBase

Descrizione

bool fbsql_drop_db ( string database_name [, resource link_identifier] )

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.

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5)

fbsql_errno --  Ritorna il valore numerico del messaggio di errore emesso dalla precedente operazione FrontBase.

Descrizione

int fbsql_errno ( [resource link_identifier] )

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

fbsql_error

(PHP 4 >= 4.0.6, PHP 5)

fbsql_error --  Ritorna il testo del messaggio di errore emesso dalla precedente operazione FrontBase.

Descrizione

string fbsql_error ( [resource link_identifier] )

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

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_array --  Restituisce una riga (tupla) di risultato in forma di Array associativo, Array enumerato o entrambi

Descrizione

array fbsql_fetch_array ( resource result [, int result_type] )

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

select t1.f1 as foo t2.f1 as bar from t1, t2

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 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select user_id, fullname from table");
while ($row = fbsql_fetch_array ($result)) {
    echo "user_id: ".$row["user_id"]."<br>\n";
    echo "user_id: ".$row[0]."<br>\n";
    echo "fullname: ".$row["fullname"]."<br>\n";
    echo "fullname: ".$row[1]."<br>\n";
}
fbsql_free_result ($result);
?>

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_assoc --  Restituisce una riga (tupla) di risultato in forma di Array associativo.

Descrizione

array fbsql_fetch_assoc ( resource result )

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

Esempio 1. fbsql_fetch_assoc()

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select * from table");
while ($row = fbsql_fetch_assoc ($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result ($result);
?>

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_field --  Ottiene informazioni su una colonna da un set di risultati come oggetto

Descrizione

object fbsql_fetch_field ( resource result [, int field_offset] )

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

<?php 
fbsql_connect($host, $user, $password)
    or die("Connessione non riuscita");
$result = fbsql_db_query("database", "select * from table")
    or die("Query fallita");
# ottiene i dati della colonna
$i = 0;
while ($i < fbsql_num_fields($result)) {
    echo "Informazioni per la colonna $i:<br />\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "Nessuna informazione disponibile<br />\n";
    }
    echo "<pre>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</pre>";
    $i++;
}
fbsql_free_result($result);
?>

Vedere anche fbsql_field_seek().

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_lengths --  Ottiene la lunghezza di ciascun output in un set di risultati

Descrizione

array fbsql_fetch_lengths ( [resource result] )

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

fbsql_fetch_object

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_object -- Resituisce un riga da un set di risultati come oggetto

Descrizione

object fbsql_fetch_object ( resource result [, int result_type] )

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

Esempio 1. Esempio di uso fbsql_fetch_object()

<?php 
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result($result);
?>

Vedere anche: fbsql_fetch_array() e fbsql_fetch_row().

fbsql_fetch_row

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_row -- Ottiene una riga come matrice numerata

Descrizione

array fbsql_fetch_row ( resource result )

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

fbsql_field_flags

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_flags --  Ottiene i flag associati al campo specificato

Descrizione

string fbsql_field_flags ( resource result, int field_offset )

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

fbsql_field_len

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_len --  Restituisce la lunghezza di un campo

Descrizione

int fbsql_field_len ( resource result, int field_offset )

La funzione fbsql_field_len() restituisce la lunghezza del campo indicato.

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_name --  Restituisce il nome del campo specificato

Descrizione

string fbsql_field_name ( resource result, int field_index )

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

<?php
// La tabella users è composta da tre campi: 
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);
?>

L'esempio precedente visualizzerà:

user_id
password

fbsql_field_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_seek --  Imposta il puntatore del set di risultati ad un specifico indice di campo

Descrizione

bool fbsql_field_seek ( resource result, int field_offset )

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

fbsql_field_table

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_table --  Ottiene il nome della tabella in cui si trova il campo

Descrizione

string fbsql_field_table ( resource result, int field_offset )

Ottiene il nome della tabella in cui si trova il campo.

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_type --  Ottiene il tipo del campo specificato

Descrizione

string fbsql_field_type ( resource result, int field_offset )

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

<?php 

fbsql_connect("localhost", "_SYSTEM", "");
fbsql_select_db("wisconsin");
$result = fbsql_query("SELECT * FROM onek;");
$fields = fbsql_num_fields($result);
$rows   = fbsql_num_rows($result);
$i = 0;
$table = fbsql_field_table($result, $i);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " records <br />";
echo "The table has the following fields <br />"; 
while ($i < $fields) {
    $type  = fbsql_field_type($result, $i);
    $name  = fbsql_field_name($result, $i);
    $len   = fbsql_field_len($result, $i);
    $flags = fbsql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "<br />";
    $i++;
}
fbsql_close();

?>

fbsql_free_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_free_result -- Libera la memoria da un set di risultati

Descrizione

bool fbsql_free_result ( resource result )

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.

fbsql_get_autostart_info

(PHP 4 >= 4.1.0, PHP 5)

fbsql_get_autostart_info -- Nessuna descrizione fornita, per ora

Descrizione

array fbsql_get_autostart_info ( [resource link_identifier] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_hostname

(PHP 4 >= 4.0.6, PHP 5)

fbsql_hostname -- Ottiene o imposta il nome del server per la connessione

Descrizione

string fbsql_hostname ( resource link_identifier [, string host_name] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_insert_id

(PHP 4 >= 4.0.6, PHP 5)

fbsql_insert_id --  restituisce l'id generato dalla precedente operazione di INSERT

Descrizione

int fbsql_insert_id ( [resource link_identifier] )

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

fbsql_list_dbs

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_dbs --  Elenca i database presenti su un server FrontBase

Descrizione

resource fbsql_list_dbs ( [resource link_identifier] )

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

Esempio 1. Esempio di uso di fbsql_list_dbs()

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

L'esempio precedente visualizzerà:

database1
database2
database3
...

Nota: L'esempio precedente sarebbe semplice con fbsql_fetch_row() o altre funzioni simili.

fbsql_list_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_fields -- Elenca i campi di un set di risultati

Descrizione

resource fbsql_list_fields ( string database_name, string table_name [, resource link_identifier] )

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

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?>

L'esempio precedente visualizzerà:

field1
field2
field3
...

fbsql_list_tables

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_tables -- Elenxa le tabelle presenti in un database FrontBase

Descrizione

resource fbsql_list_tables ( string database [, resource link_identifier] )

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.

fbsql_next_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_next_result --  Muove il puntatore interno al risultato successivo

Descrizione

bool fbsql_next_result ( resource result_id )

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
    $link = fbsql_connect("localhost", "_SYSTEM", "secret");
    fbsql_select_db("MyDB", $link);
    $SQL = "Select * from table1; select * from table2;";
    $rs = fbsql_query($SQL, $link);
    do {
        while ($row = fbsql_fetch_row($rs)) {
        }
    } while (fbsql_next_result($rs));
    fbsql_free_result($rs);
    fbsql_close($link);
?>

fbsql_num_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_fields -- Ottiene il numero dei campi presenti in un set di risultati

Descrizione

int fbsql_num_fields ( resource result )

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

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_rows -- Restituisce il numero di righe presenti in un set di risultati

Descrizione

int fbsql_num_rows ( resource result )

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

Esempio 1. Esempio di uso di fbsql_num_rows()

<?php

$link = fbsql_connect("localhost", "username", "password"); 
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link); 
$num_rows = fbsql_num_rows($result); 

echo "$num_rows Rows\n";

?>

Vedere anche: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db() e fbsql_query().

fbsql_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_password -- Ottiene o imposta la password per la connessione

Descrizione

string fbsql_password ( resource link_identifier [, string password] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_pconnect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_pconnect --  Apre una connessione persistente ad un server FrontBase

Descrizione

resource fbsql_pconnect ( [string hostname [, string username [, string password]]] )

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

fbsql_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_query -- Invia una query a FrontBase

Descrizione

resource fbsql_query ( string query [, resource link_identifier] )

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:

Esempio 1. Esempio di uso di fbsql_query()

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

La seguente query è semanticamente errata se my_col non è una colonna della tabella my_tbl, pertanto fbsql_query() fallirà e restituirà FALSE:

Esempio 2. Esempio di uso di fbsql_query()

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl")
    or die ("Invalid query");
?>

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

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_blob -- Legge un BLOB dal database

Descrizione

string fbsql_read_blob ( string blob_handle [, resource link_identifier] )

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

<?php
    $link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
        or die("Connessione non riuscita");
    $sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] contiene i dati BLOB per la prima riga
    fbsql_free_result($rs);
    
    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] ora contiene il puntatore ai dati BLOB per la prima riga
    $blob_data = fbsql_read_blob($row_data[0]);
    fbsql_free_result($rs);
    
?>

Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_clob -- Legge un CLOB dal database

Descrizione

string fbsql_read_clob ( string clob_handle [, resource link_identifier] )

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

<?php
    $link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
        or die("Connessione non riuscita");
    $sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] contiene i dati CLOB per la prima riga
    fbsql_free_result($rs);
    
    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] ora contiene il puntatore ai dati CLOB per la prima riga
    $clob_data = fbsql_read_clob($row_data[0]);
    fbsql_free_result($rs);
    
?>

Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().

fbsql_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_result -- Restituisce i dati di una query

Descrizione

mixed fbsql_result ( resource result, int row [, mixed field] )

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

fbsql_rollback

(PHP 4 >= 4.0.6, PHP 5)

fbsql_rollback -- Esegue il rollback della transazione

Descrizione

bool fbsql_rollback ( [resource link_identifier] )

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

fbsql_select_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_select_db -- Seleziona un database FrontBase

Descrizione

bool fbsql_select_db ( string database_name [, resource link_identifier] )

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

fbsql_set_lob_mode

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_lob_mode --  Imposta la modalità LOB in un set di risultati FrontBase

Descrizione

bool fbsql_set_lob_mode ( resource result, string database_name )

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

fbsql_set_password

(PHP 5)

fbsql_set_password --  Change the password for a given user

Descrizione

bool fbsql_set_password ( resource link_identifier, string user, string password, string old_password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_transaction --  Imposta i lock e l'isolamento delle transazioni

Descrizione

void fbsql_set_transaction ( resource link_identifier, int Locking, int Isolation )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_start_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_start_db -- Attiva un database locale o remoto

Descrizione

bool fbsql_start_db ( string database_name [, resource link_identifier] )

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

fbsql_start_db()

Vedere anche: fbsql_db_status() e fbsql_stop_db().

fbsql_stop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_stop_db -- Ferma un database locale o remoto

Descrizione

bool fbsql_stop_db ( string database_name [, resource link_identifier] )

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

fbsql_stop_db()

Vedere anche: fbsql_db_status() e fbsql_start_db().

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5)

fbsql_tablename -- Restituisce il nome della tabella dei campi

Descrizione

string fbsql_tablename ( resource result, int i )

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.

Esempio 1. Esempio di uso di fbsql_tablename()

<?php 
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_tablename($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>

fbsql_username

(PHP 4 >= 4.0.6, PHP 5)

fbsql_username -- Ottiene o imposta l'utente per la connessione

Descrizione

string fbsql_username ( resource link_identifier [, string username] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

fbsql_warnings

(PHP 4 >= 4.0.6, PHP 5)

fbsql_warnings -- Abilita o disabilita i warnings FrontBase

Descrizione

bool fbsql_warnings ( [bool OnOff] )

Restituisce TRUE se i warnings sono abilitati oppure FALSE.

La funzione fbsql_warnings() abilita o disabilita i warnings FrontBase.

XLIII. Funzioni FTP

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

<?php
// stabilire una connessione
$conn_id = ftp_connect($ftp_server); 

// login con user name e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// controllo della connessione
if ((!$conn_id) || (!$login_result)) { 
        echo "La connessione FTP è fallita!";
        echo "Tentativo di connessione a $ftp_server per l'utente $ftp_user_name"; 
        die; 
    } else {
        echo "Connesso a $ftp_server, utente $ftp_user_name";
    }

// upload del file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); 

// controllo dello stato di upload
if (!$upload) { 
        echo "Il caricamento FTP non è andato a buon fine!";
    } else {
        echo "Caricato il file $source_file su $ftp_server come $destination_file";
    }

// chiudere il flusso FTP 
ftp_quit($conn_id); 
?>

Sommario
ftp_alloc -- Allocates space for a file to be uploaded
ftp_cdup -- Passa alla directory superiore
ftp_chdir -- Cambia le directory su un server FTP
ftp_chmod -- Set permissions on a file via FTP
ftp_close -- Chiude una connessione FTP
ftp_connect -- Apre una connessione FTP
ftp_delete -- Cancella un file sul server FTP
ftp_exec -- Richiede l'esecuzione di un programma sul server FTP
ftp_fget -- Scarica un file dal server FTP e lo salva su un file aperto
ftp_fput -- Carica un file aperto sul server FTP
ftp_get_option -- Recupera diversi comportamenti dello stream FTP durante l'esecuzione
ftp_get -- Scarica un file dal server FTP
ftp_login -- Esegue il log ad una connessione FTP
ftp_mdtm -- Restituisce l'orario dell'ultima modifica al file corrente
ftp_mkdir -- Crea una directory
ftp_nb_continue -- Continua a ricevere/trasmettere un file in modalita' non bloccante
ftp_nb_fget -- Recupera un file dal server FTP e lo scrive su un file aperto, in modalita' non bloccante
ftp_nb_fput -- Salva il contenuto di un file aperto sul server FTP in modalita' non bloccante
ftp_nb_get -- Recupera un file dal server FTP e lo scrive su un file locale in modalita' non bloccante
ftp_nb_put -- Salva un file sul server FTP in modalita' non bloccante
ftp_nlist -- Restituisce la lista dei file nella directory prescelta
ftp_pasv -- Attivaa o disattiva il modo passivo
ftp_put -- Trasferisce un file al server FTP
ftp_pwd -- Restituisce il nome della directory corrente
ftp_quit -- Alias di ftp_close()
ftp_raw -- Invia un comando di qualsiasi tipo ad un server FTP
ftp_rawlist -- Restituisce un elenco dettagliato dei files nella directory in esame
ftp_rename -- Rinomina un file sul server FTP
ftp_rmdir -- Elimina una directory
ftp_set_option -- Imposta varie opzioni per l'esecuzione di FTP
ftp_site -- Invia al server un comando SITE
ftp_size -- Restituisce le dimensioni del file specificato
ftp_ssl_connect -- Apre una connessione SSL-FTP connessione
ftp_systype -- Restituisce l'identificatore di tipo del server FTP remoto

ftp_alloc

(PHP 5)

ftp_alloc -- Allocates space for a file to be uploaded

Descrizione

bool ftp_alloc ( resource ftp_stream, int filesize [, string &result] )

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.

Elenco dei parametri

ftp_stream

The link identifier of the FTP connection.

filezise

The number of bytes to allocate.

return

A textual representation of the servers response will be returned by reference in result if a variable is provided.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. ftp_alloc() example

<?php

$file = "/home/user/myfile";

/* connect to the server */
$conn_id = ftp_connect('ftp.example.com');
$login_result = ftp_login($conn_id, 'anonymous', 'user@example.com');

if (ftp_alloc($conn_id, filesize($file), $result)) {
  echo "Space successfully allocated on server.  Sending $file.\n";
  ftp_put($conn_id, '/incomming/myfile', $file, FTP_BINARY);
} else {
  echo "Unable to allocate space on server.  Server said: $result\n";
}

ftp_close($conn_id);

?>

Vedere anche:

ftp_put()
ftp_fput()

ftp_cdup

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_cdup -- Passa alla directory superiore

Descrizione

bool ftp_cdup ( resource ftp_stream )

Passa alla directory superiore.

Esempio 1. ftp_cdup() example

<?php
// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// cambia la directory corrente in html
ftp_chdir($conn_id, 'html');

echo ftp_pwd($conn_id); // /html 

// torna alla directory padre
if (ftp_cdup($conn_id)) { 
  echo "cdup successful\n";
} else {
  echo "cdup not successful\n";
}

echo ftp_pwd($conn_id); // /

ftp_close($conn_id);
?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedi anche ftp_chdir().

ftp_chdir

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_chdir -- Cambia le directory su un server FTP

Descrizione

bool ftp_chdir ( resource ftp_stream, string directory )

Passa dalla directory corrente alla directory specificata.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. esempio ftp_chdir()

<?php

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server); 

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// controlla la connessione
if ((!$conn_id) || (!$login_result)) {
    die("FTP connection has failed !");
}

echo "Current directory: " . ftp_pwd($conn_id) . "\n";

// tenta di passare alla directory somedir
if (ftp_chdir($conn_id, "somedir")) {
    echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else { 
    echo "Couldn't change directory\n";
}

// chiude la connessione
ftp_close($conn_id);
?>

Vedi anche ftp_cdup().

ftp_chmod

(PHP 5)

ftp_chmod -- Set permissions on a file via FTP

Descrizione

int ftp_chmod ( resource ftp_stream, int mode, string filename )

Sets the permissions on the specified remote file to mode.

Elenco dei parametri

ftp_stream

The link identifier of the FTP connection.

mode

The new permissions, given as an octal value.

filename

The remote file.

Valori restituiti

Returns the new file permissions on success or FALSE on error.

Esempi

Esempio 1. ftp_chmod() example

<?php
$file = 'public_html/index.php';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to chmod $file to 644
if (ftp_chmod($conn_id, 0644, $file) !== false) {
 echo "$file chmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

Vedere anche:

chmod()

ftp_close

(PHP 4 >= 4.2.0, PHP 5)

ftp_close -- Chiude una connessione FTP

Descrizione

void ftp_close ( resource ftp_stream )

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

<?php

//stabilisce la connessione
$conn_id = ftp_connect($ftp_server);
// si collega con nome utente e password

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// stampa la directory corrente
echo ftp_pwd($conn_id); // /

// chiude la connessione
ftp_close($conn_id);
?>

Vedere anche ftp_connect()

ftp_connect

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_connect -- Apre una connessione FTP

Descrizione

resource ftp_connect ( string host [, int port [, int timeout]] )

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.

Esempio 1. Esempio di funzione ftp_connect()

<?php

$ftp_server = "ftp.example.com";

// stabilisce una connessione o esce
$conn_id = ftp_connect($ftp_server) or die("Impossibile collegarsi a $ftp_server"); 

?>

Vedere anche ftp_close(), e ftp_ssl_connect().

ftp_delete

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_delete -- Cancella un file sul server FTP

Descrizione

bool ftp_delete ( resource ftp_stream, string path )

ftp_delete() cancella il file specificato da path dal server FTP.

Esempio 1. Esempio di funzione ftp_delete()

<?php
$file = 'public_html/old.txt';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password


$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a cancellare $file
if (ftp_delete($conn_id, $file)) {
 echo "$file cancellato correttamente\n";
} else {
 echo "impossibile cancellare $file\n";
}

// chiude la connessione
ftp_close($conn_id);
?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ftp_exec

(PHP 4 >= 4.0.3, PHP 5)

ftp_exec -- Richiede l'esecuzione di un programma sul server FTP

Descrizione

bool ftp_exec ( resource ftp_stream, string command )

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

<?php

$command = 'ls -al';

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if ($res = ftp_exec($conn_id, $command)) {
    echo "$comando eseguito correttamente<br />\n";
    echo nl2br($res);
} else {
    echo 'impossibile eseguire ' . $command;
}

?>

Vedere anche ftp_raw().

ftp_fget

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_fget -- Scarica un file dal server FTP e lo salva su un file aperto

Descrizione

bool ftp_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos] )

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

<?php

// apre in lettura un qualche file
$file = 'somefile.txt';
$fp = fopen($file, 'w');

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a scaricare $file
if (ftp_fget($conn_id, $fp, $file, FTP_ASCII, 1)) {
 echo "scrittura su $file completata con successo\n";
} else {
 echo "Problemi con $file\n";
}

// chiude la connessione e l'handle del file
ftp_close($conn_id);
fclose($fp);
?>

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

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_fput -- Carica un file aperto sul server FTP

Descrizione

bool ftp_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos] )

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

<?php

// apre in lettura un qualche file
$file = 'somefile.txt';
$fp = fopen($file, 'r');

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a caricare $file
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
    echo "$file caricato con successo\n";
} else {
    echo "Problemi con il caricamento di $file\n";
}

// chiude la connessione e l'handle del file
ftp_close($conn_id);
fclose($fp);

?>

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

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_get_option -- Recupera diversi comportamenti dello stream FTP durante l'esecuzione

Descrizione

mixed ftp_get_option ( resource ftp_stream, int option )

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

Esempio 1. Esempio di funzione ftp_get_option()

<?php
// Recupera il time out dello stream FTP richiesto
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

Vedere anche ftp_set_option().

ftp_get

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_get -- Scarica un file dal server FTP

Descrizione

bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos] )

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

<?php

// definisce alcune variabili
$local_file = 'local.zip';
$server_file = 'server.zip';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a scaricare $server_file e a salvarlo su $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Scrittura su $local_file terminata con successo\n";
} else {
    echo "Problemi nello scaricamento\n";
}

// chiude la connessione
ftp_close($conn_id);

?>

Vedere anche ftp_fget(), ftp_nb_get() e ftp_nb_fget().

ftp_login

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_login -- Esegue il log ad una connessione FTP

Descrizione

bool ftp_login ( resource ftp_stream, string username, string password )

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
                     
$ftp_server = "ftp.example.com";
$ftp_user = "foo";
$ftp_pass = "bar";

// esegue una connessione o esce
$conn_id = ftp_connect($ftp_server) or die("Impossibile connettersi a $ftp_server"); 

// prova a connettersi
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connesso come $ftp_user@$ftp_server\n";
} else {
    echo "Impossibile connettersi come $ftp_user\n";
}

// chiude la connessione
ftp_close($conn_id);  
?>

ftp_mdtm

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_mdtm -- Restituisce l'orario dell'ultima modifica al file corrente

Descrizione

int ftp_mdtm ( resource ftp_stream, string remote_file )

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

<?php

$file = 'somefile.txt';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// recupera l'ultimo orario di modifica
$buff = ftp_mdtm($conn_id, $file);

if ($buff != -1) {
    // somefile.txt e' stato modificato l'ultima volta il: 26 marzo 2003 14:16:41.
    echo "$file e' stato modificato l'ultima volta il : " . date("F d Y H:i:s.", $buff);
} else {
    echo "Impossibile visualizzare mdtime";
}

// chiude la connessione
ftp_close($conn_id);

?>

Nota: Non tutti i server includono questa funzione!

Nota: La funzione ftp_mdtm() non funziona con le directories.

ftp_mkdir

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_mkdir -- Crea una directory

Descrizione

string ftp_mkdir ( resource ftp_stream, string directory )

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

<?php

$dir = 'www';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a creare la directory $dir
if (ftp_mkdir($conn_id, $dir)) {
 echo "$dir creata con successo\n";
} else {
 echo "Problemi nella creazione di $dir\n";
}

// chiude la connessione
ftp_close($conn_id);
?>

Vedere anche ftp_rmdir().

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_continue -- Continua a ricevere/trasmettere un file in modalita' non bloccante

Descrizione

int ftp_nb_continue ( resource ftp_stream )

Continua a ricevere/trasmettere un file in modalita' non bloccante.

Esempio 1. Esempio di funzioneftp_nb_continue()

<?php

// Inizia lo scaricamento
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Continua lo scaricamento...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nello scaricamento del file...";
   exit(1);
}
?>

Restituisce FTP_FAILED oppure FTP_FINISHED oppure FTP_MOREDATA.

ftp_nb_fget

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

Descrizione

int ftp_nb_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos] )

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

<?php

// apre un file in lettura
$file = 'index.php';
$fp = fopen($file, 'w');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Inizia lo scaricamento
$ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // esegue altre operazioni
   echo ".";

   // Continua lo scaricamento...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nello scaricamento del file...";
   exit(1);
}

// close filepointer
fclose($fp);
?>

Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.

Vedere anche ftp_nb_get(), ftp_nb_continue(), ftp_fget(), and ftp_get().

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fput -- Salva il contenuto di un file aperto sul server FTP in modalita' non bloccante

Descrizione

int ftp_nb_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos] )

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

<?php

$file = 'index.php';

$fp = fopen($file, 'r');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Inizia il trasferimento del file al server
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // esegue altre operazioni
   echo ".";

   // continua il trasferimento...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nel trasferimento del file al server...";
   exit(1);
}

fclose($fp);
?>

Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.

Vedere anche ftp_nb_put(), ftp_nb_continue(), ftp_put() e ftp_fput().

ftp_nb_get

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

Descrizione

int ftp_nb_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos] )

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

<?php

// Inizia lo scaricamento
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // esegue altre operazioni
   echo ".";

   // Continua lo scaricamento...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nello scaricamento del file...";
   exit(1);
}
?>

Esempio 2. Ripresa di uno scaricamento con ftp_nb_get()

<?php

// Inizio 
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY, 
                      filesize("test"));
// oppure: $ret = ftp_nb_get($my_connection, "test", "README", 
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {
   
   // esegue altre operazioni
   echo ".";

   // Continua lo scaricamento...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nello scaricamento del file...";
   exit(1);
}
?>

Esempio 3. Ripresa di uno scaricamento dalla posizione 100 su un nuovo file con ftp_nb_get()

<?php

// Esclusione di Autoseek (ricerca automatica)
ftp_set_option($my_connection, FTP_AUTOSEEK, false);

// Inizio
$ret = ftp_nb_get($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   /* ... */
   
   // Continua lo scaricamento...
   $ret = ftp_nb_continue($my_connection);
}
?>

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

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_put -- Salva un file sul server FTP in modalita' non bloccante

Descrizione

int ftp_nb_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos] )

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

<?php

// Inizia il trasferimento
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // esegue altre operazioni
   echo ".";

   // continua il trasferimento...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nel trasferimento del file...";
   exit(1);
}
?>

Esempio 2. Ripresa di un trasferimento con ftp_nb_put()

<?php

// Inizio
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", 
                      FTP_BINARY, ftp_size("test.remote"));
// oppure: $ret = ftp_nb_put($my_connection, "test.remote", "test.local", 
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {
   
   // esegue altre operazioni
   echo ".";

   // Continua il trasferimento...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "Errore nel trasferimento del file...";
   exit(1);
}
?>

Vedere anche ftp_nb_fput(), ftp_nb_continue(), ftp_put(), e ftp_fput().

ftp_nlist

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_nlist -- Restituisce la lista dei file nella directory prescelta

Descrizione

array ftp_nlist ( resource ftp_stream, string directory )

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

<?php

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con nome utente e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// recupera il contenuto della directory corrente
$contents = ftp_nlist($conn_id, ".");

// visualizza $contents
var_dump($contents);

?>

    L'esempio precedente visualizza qualcosa del tipo:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

Vedere anche ftp_rawlist().

ftp_pasv

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_pasv -- Attivaa o disattiva il modo passivo

Descrizione

bool ftp_pasv ( resource ftp_stream, bool pasv )

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

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// attiva il modo passivo
ftp_pasv($conn_id, true);

// trasferisce un file al server
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "$file trasferito correttamente\n";
} else {
 echo "Si e' verificato un problema durante il trasferimento di $file\n";
}

// chiude la connessione
ftp_close($conn_id);
?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ftp_put

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_put -- Trasferisce un file al server FTP

Descrizione

bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos] )

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

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// trasferisce un file al server
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "$file trasferito correttamente\n";
} else {
 echo "Si e' verificato un problema durante il trasferimento di $file\n";
}

// chiude la connessione
ftp_close($conn_id);
?>

Vedere anche ftp_fput(), ftp_nb_fput(), e ftp_nb_put().

ftp_pwd

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_pwd -- Restituisce il nome della directory corrente

Descrizione

string ftp_pwd ( resource ftp_stream )

Restituisce la directory corrente oppure FALSE in caso di errore.

Esempio 1. Esempio di funzione ftp_pwd()

<?php

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// si sposta sulla directory public_html
ftp_chdir($conn_id, 'public_html');

// stampa la directory corrente
echo ftp_pwd($conn_id); // /public_html

// chiude la connessione
ftp_close($conn_id);
?>

ftp_quit

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_quit -- Alias di ftp_close()

Descrizione

Questa funzione e' un alias di ftp_close().

ftp_raw

(PHP 5)

ftp_raw -- Invia un comando di qualsiasi tipo ad un server FTP

Descrizione

array ftp_raw ( resource ftp_stream, string command )

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.

Esempio 1. Utilizzo di ftp_raw() per collegarsi in modo manuale ad un server FTP.

<?php
$fp = ftp_connect("ftp.example.com");

/* Equivalente a: 
   ftp_login($fp, "joeblow", "secret"); */
ftp_raw($fp, "USER joeblow");
ftp_raw($fp, "PASS secret");
?>

Vedi anche: ftp_exec()

ftp_rawlist

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_rawlist -- Restituisce un elenco dettagliato dei files nella directory in esame

Descrizione

array ftp_rawlist ( resource ftp_stream, string directory )

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

<?php

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// ottiene l'elenco dei files di /
$buff = ftp_rawlist($conn_id, '/');

// chiude la connessione
ftp_close($conn_id);

// visualizza il contenuto del buffer
var_dump($buff);
?>

    L'esempio precedente produrra' qualcosa di simile a:    

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

Vedere anche ftp_nlist().

ftp_rename

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_rename -- Rinomina un file sul server FTP

Descrizione

bool ftp_rename ( resource ftp_stream, string from, string to )

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

<?php
$old_file = 'somefile.txt.bak';
$new_file = 'somefile.txt';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega con username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a cambiare il nome $old_file nel nome $new_file
if (ftp_rename($conn_id, $old_file, $new_file)) {
 echo "cambiamento nome da $old_file a $new_file effettuato\n";
} else {
 echo "Si e' verificato un problema durante il cambiamento di nome da $old_file a $new_file\n";
}

// chiude la connessione
ftp_close($conn_id);
?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ftp_rmdir

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_rmdir -- Elimina una directory

Descrizione

bool ftp_rmdir ( resource ftp_stream, string directory )

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

<?php

$dir = 'www/';

// stabilisce la connesione
$conn_id = ftp_connect($ftp_server);

// si collega con username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// prova a eliminare la directory $dir
if (ftp_rmdir($conn_id, $dir)) {
    echo "Directory $dir eliminata\n";
} else {
    echo "Si e' verificato un problema durante l'eliminazione di $dir\n";
}

ftp_close($conn_id);

?>

Vedere anche ftp_mkdir().

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_set_option -- Imposta varie opzioni per l'esecuzione di FTP

Descrizione

bool ftp_set_option ( resource ftp_stream, int option, mixed value )

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

Esempio 1. Esempio di funzione ftp_set_option()

<?php
// Imposta il timeout di rete a 10 secondi
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

Vedere anche ftp_get_option().

ftp_site

(PHP 3 >= 3.0.15, PHP 4, PHP 5)

ftp_site -- Invia al server un comando SITE

Descrizione

bool ftp_site ( resource ftp_stream, string cmd )

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

<?php
/* Connessione al server FTP */
$conn = ftp_connect('ftp.example.com');
if (!$conn) die('Impossibile connettersi a ftp.example.com');

/* Collegarsi come "user" con password "pass" */
if (!ftp_login($conn, 'user', 'pass')) die('Errore nel collegamento come "user" a ftp.example.com');

/* Invio: comando "SITE CHMOD 0600 /home/user/privatefile" al server ftp */
if (ftp_site($conn, 'CHMOD 0600 /home/user/privatefile')) {
   echo "Comando eseguito correttamente.\n";
} else {
   die('Errore nell'esecuzione del comando.');
}
?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche: ftp_raw()

ftp_size

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_size -- Restituisce le dimensioni del file specificato

Descrizione

int ftp_size ( resource ftp_stream, string remote_file )

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

<?php

$file = 'somefile.txt';

// stabilisce la connessione
$conn_id = ftp_connect($ftp_server);

// si collega come username e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// recupera le dimensioni di $file
$res = ftp_size($conn_id, $file);

if ($res != -1) {
    echo "le dimensioni del file $file sono di $res bytes";
} else {
    echo "impossibile stabilire le dimensioni";
}

// chiude la connessione
ftp_close($conn_id);

?>

Vedere anche ftp_rawlist().

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5)

ftp_ssl_connect -- Apre una connessione SSL-FTP connessione

Descrizione

resource ftp_ssl_connect ( string host [, int port [, int timeout]] )

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

<?php

// stabilisce una connessione ssl
$conn_id = ftp_ssl_connect($ftp_server);

// si collega come username e password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

echo ftp_pwd($conn_id); // /

// chiude la connessione ssl
ftp_close($conn_id);
?>

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

ftp_systype

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ftp_systype -- Restituisce l'identificatore di tipo del server FTP remoto

Descrizione

string ftp_systype ( resource ftp_stream )

Restituisce il tipo del sistema remoto, o FALSE in caso di errore.

Esempio 1. Esempio di funzioneftp_systype()

<?php

// connessione ftp
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'user', 'password');

// recupera il tipo del sistema
if ($type = ftp_systype($ftp)) {
    echo "Example.com utilizza $type\n";
} else {
    echo "Impossibile determinare il tipo del sistema";
}

?>

L'esempio precedente produrra' in uscita qualosa di simile a:

Example.com utilizza UNIX

XLIV. Function Handling Functions

Introduzione

These functions all handle various operations involved in working with functions.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
call_user_func_array --  Call a user function given with an array of parameters
call_user_func --  Call a user function given by the first parameter
create_function -- Create an anonymous (lambda-style) function
func_get_arg -- Return an item from the argument list
func_get_args --  Returns an array comprising a function's argument list
func_num_args --  Returns the number of arguments passed to the function
function_exists --  Return TRUE if the given function has been defined
get_defined_functions --  Returns an array of all defined functions
register_shutdown_function --  Register a function for execution on shutdown
register_tick_function --  Register a function for execution on each tick
unregister_tick_function --  De-register a function for execution on each tick

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array --  Call a user function given with an array of parameters

Description

mixed call_user_func_array ( callback function, array param_arr )

Call a user defined function given by function, with the parameters in param_arr. For example:

Esempio 1. call_user_func_array() example

<?php
function debug($var, $val) 
{
    echo "***DEBUGGING\nVARIABLE: $var\nVALUE:";
    if (is_array($val) || is_object($val) || is_resource($val)) {
        print_r($val);
    } else {
        echo "\n$val\n";
    }
    echo "***\n";
}

$c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];

call_user_func_array('debug', array("host", $host));
call_user_func_array('debug', array("c", $c));
call_user_func_array('debug', array("_POST", $_POST));
?>

See also call_user_func(), and information about the callback type

call_user_func

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

call_user_func --  Call a user function given by the first parameter

Description

mixed call_user_func ( callback function [, mixed parameter [, mixed ...]] )

Call a user defined function given by the function parameter. Take the following:

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

<?php
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a; // 0

call_user_func_array('increment', array(&$a)); // You can use this instead
echo $a; // 1
?>

See also: is_callable(), call_user_func_array(), e information about the callback type.

create_function

(PHP 4 >= 4.0.1, PHP 5)

create_function -- Create an anonymous (lambda-style) function

Description

string create_function ( string args, string code )

Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

You can use this function, to (for example) create a function from information gathered at run time:

Esempio 1. Creating an anonymous function with create_function()

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>

Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

Esempio 2. Making a general processing function with create_function()

<?php
function process($var1, $var2, $farr) 
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . " , ".crc32(b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

and when you run the code above, the output will be:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

Esempio 3. Using anonymous functions as callback functions

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av); 
?>

outputs:

Array
(
  [0] => the mango
  [1] => a mango
  [2] => that mango
  [3] => this mango
)

an array of strings ordered from shorter to longer

<?php

$sv = array("small", "larger", "a big string", "it is a string thing");
print_r($sv);

?>

outputs:

Array
(
  [0] => small
  [1] => larger
  [2] => a big string
  [3] => it is a string thing
)

sort it from longer to shorter

<?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?>

outputs:

Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

func_get_arg

(PHP 4, PHP 5)

func_get_arg -- Return an item from the argument list

Description

mixed func_get_arg ( int arg_num )

Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition. 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.

func_get_args

(PHP 4, PHP 5)

func_get_args --  Returns an array comprising a function's argument list

Description

array func_get_args ( void )

Returns an array in which each element is 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.

func_num_args

(PHP 4, PHP 5)

func_num_args --  Returns the number of arguments passed to the function

Description

int func_num_args ( void )

Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function. 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.

function_exists

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

function_exists --  Return TRUE if the given function has been defined

Description

bool function_exists ( string function_name )

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. 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().

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5)

get_defined_functions --  Returns an array of all defined functions

Description

array get_defined_functions ( void )

This function returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

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

register_shutdown_function

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

register_shutdown_function --  Register a function for execution on shutdown

Description

void register_shutdown_function ( callback function [, mixed parameter [, mixed ...]] )

Registers the function named by function to be executed when script processing is complete.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

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.

register_tick_function

(PHP 4 >= 4.0.3, PHP 5)

register_tick_function --  Register a function for execution on each tick

Description

bool register_tick_function ( callback function [, mixed arg [, mixed ...]] )

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.

Esempio 1. register_tick_function() example

<?php
// using a function as the callback
register_tick_function('my_function', true);

// using an object->method
$object = new my_class();
register_tick_function(array(&$object, 'my_method'), true);
?>

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

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5)

unregister_tick_function --  De-register a function for execution on each tick

Description

void unregister_tick_function ( string function_name )

De-registers the function named by function_name so it is no longer executed when a tick is called.

XLV. Gettext

Introduzione

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.


Requisiti

To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
bindtextdomain -- Sets the path for a domain
dcgettext -- Overrides the domain for a single lookup
dcngettext -- Plural version of dcgettext
dgettext -- Override the current domain
dngettext -- Plural version of dgettext
gettext -- Lookup a message in the current domain
ngettext -- Plural version of gettext
textdomain -- Sets the default domain

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5)

bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

string bind_textdomain_codeset ( string domain, string codeset )

With bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.

bindtextdomain

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

bindtextdomain -- Sets the path for a domain

Description

string bindtextdomain ( string domain, string directory )

The bindtextdomain() function sets the path for a domain. It returns the full pathname for the domain currently being set.

Esempio 1. bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale'); 

?>

This will output:

/usr/share/myapp/locale

dcgettext

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

dcgettext -- Overrides the domain for a single lookup

Description

string dcgettext ( string domain, string message, int category )

This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.

See also gettext().

dcngettext

(PHP 4 >= 4.2.0, PHP 5)

dcngettext -- Plural version of dcgettext

Description

string dcngettext ( string domain, string msgid1, string msgid2, int n, int category )

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

dgettext

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

dgettext -- Override the current domain

Description

string dgettext ( string domain, string message )

The dgettext() function allows you to override the current domain for a single message lookup.

See also gettext().

dngettext

(PHP 4 >= 4.2.0, PHP 5)

dngettext -- Plural version of dgettext

Description

string dngettext ( string domain, string msgid1, string msgid2, int n )

The dngettext() function allows you to override the current domain for a single plural message lookup.

See also ngettext().

gettext

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

gettext -- Lookup a message in the current domain

Description

string gettext ( string message )

This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use the underscore character '_' as an alias to this function.

Esempio 1. gettext()-check

<?php
// Set language to German
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

See also setlocale().

ngettext

(PHP 4 >= 4.2.0, PHP 5)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n )

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.

Esempio 1. ngettext() example

<?php

setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

?>

textdomain

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

textdomain -- Sets the default domain

Descrizione

string textdomain ( string text_domain )

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Elenco dei parametri

text_domain

The new message domain, or NULL to get the current setting without changing it

Valori restituiti

If successful, this function returns the current message domain, after possibly changing it.

XLVI. Funzioni GMP

Introduzione

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.


Requisiti

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.


Installazione

Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto GMP utilizzando il parametro --with-gmp.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)


Esempi

Esempio 1. Funzione fattoriale usando GMP

<?php
function fact ($x) 
{
    if ($x <= 1) {
        return 1;
    } else {
        return gmp_mul($x, fact($x-1));
    }
}

echo gmp_strval (fact (1000)) . "\n";
?>

Questo calcolerà il fattoriale di 1000 (numero abbastanza grande) molto velocemente.


Vedere anche:

Ulteriori funzioni matematiche sono elencate nelle sezioni BCMath Funzione Matematiche a Precisione Arbitraria e Funzioni Matematiche.

Sommario
gmp_abs -- Valore assoluto
gmp_add -- Somma di numeri
gmp_and -- AND logico
gmp_clrbit -- Pulisce bit
gmp_cmp -- Confronto di numeri
gmp_com -- Calcola il complemento a uno di 'a'
gmp_div_q -- Divide due numberi
gmp_div_qr -- Divide due numeri e restituisce quoziente e resto
gmp_div_r -- Resto di una divisione
gmp_div -- Divisione di numberi
gmp_divexact -- Divisione intera di numeri
gmp_fact -- Fattoriale
gmp_gcd -- Calcola il MCD
gmp_gcdext -- Calcola il MCD e moltiplicatori
gmp_hamdist -- Distanza dell'hamming
gmp_init -- Crea un numero GMP
gmp_intval -- Converte un numero GMP in un intero
gmp_invert -- Inversione di modulo
gmp_jacobi -- Simbolo di Jacobi
gmp_legendre -- Simbolo di Legendre
gmp_mod -- Modulo
gmp_mul -- Prodotto di numeri
gmp_neg -- Rende un numero negativo
gmp_or -- OR logico
gmp_perfect_square -- Controllo quadrato perfetto
gmp_popcount -- Conteggio della popolazione
gmp_pow -- Eleva un numero a potenza
gmp_powm -- Modulo di un elevamento a potenza.
gmp_prob_prime -- Controlla se il numero è "probabilmente primo"
gmp_random -- Generatore di numeri casuali
gmp_scan0 -- Ricerca per 0
gmp_scan1 -- Ricerca per 1
gmp_setbit -- Imposta bit
gmp_sign -- Segno di un numero
gmp_sqrt -- Radice quadrata
gmp_sqrtrem -- Radice quadrata con resto
gmp_strval -- Converte un numero GMP in una stringa
gmp_sub -- Sottrazione di numeri
gmp_xor -- XOR logico

gmp_abs

(PHP 4 >= 4.0.4, PHP 5)

gmp_abs -- Valore assoluto

Descrizione

resource gmp_abs ( resource a )

Restituisce il valore assoluto di a.

gmp_add

(PHP 4 >= 4.0.4, PHP 5)

gmp_add -- Somma di numeri

Descrizione

resource gmp_add ( resource a, resource b )

Somma due numeri GMP. Il risultato, sarà un numero GMP che rappresenta la somma degli argomenti.

gmp_and

(PHP 4 >= 4.0.4, PHP 5)

gmp_and -- AND logico

Descrizione

resource gmp_and ( resource a, resource b )

Calcola l'AND logico di due numeri GMP.

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_clrbit -- Pulisce bit

Descrizione

resource gmp_clrbit ( resource &a, int index )

Ripulisce (imposta a 0) il bit index in a.

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5)

gmp_cmp -- Confronto di numeri

Descrizione

int gmp_cmp ( resource a, resource b )

Restituisce un valore positivo se a > b, zero se a = b e negativo se a < b.

gmp_com

(PHP 4 >= 4.0.4, PHP 5)

gmp_com -- Calcola il complemento a uno di 'a'

Descrizione

resource gmp_com ( resource a )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_q -- Divide due numberi

Descrizione

resource gmp_div_q ( resource a, resource b [, int round] )

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

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_qr -- Divide due numeri e restituisce quoziente e resto

Descrizione

array gmp_div_qr ( resource n, resource d [, int round] )

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.

Esempio 1. Divisione di numeri GMP

<?php
    $a = gmp_init ("0x41682179fbf5");
    $res = gmp_div_qr ($a, "0xDEFE75");
    printf("Result is: q - %s, r - %s", 
            gmp_strval ($res[0]), gmp_strval ($res[1]));
?>

Vedere anche gmp_div_q(), gmp_div_r().

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_r -- Resto di una divisione

Descrizione

resource gmp_div_r ( resource n, resource d [, int round] )

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

gmp_div

(PHP 4 >= 4.0.4, PHP 5)

gmp_div -- Divisione di numberi

Descrizione

resource gmp_div ( resource a, resource b )

Questa funzione è la stessa di gmp_div_q().

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5)

gmp_divexact -- Divisione intera di numeri

Descrizione

resource gmp_divexact ( resource n, resource d )

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.

gmp_fact

(PHP 4 >= 4.0.4, PHP 5)

gmp_fact -- Fattoriale

Descrizione

resource gmp_fact ( int a )

Calcola il fattoriale (a!) di a.

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcd -- Calcola il MCD

Descrizione

resource gmp_gcd ( resource a, resource b )

Calcola il massimo comune divisore (MCD) di a e b. Il risultato è sempre positivo, anche se uno o entrambi gli operatori sono negativi.

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcdext -- Calcola il MCD e moltiplicatori

Descrizione

array gmp_gcdext ( resource a, resource b )

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.

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5)

gmp_hamdist -- Distanza dell'hamming

Descrizione

int gmp_hamdist ( resource a, resource b )

Restituisce la distanza di hamming tra a e b. Entrambe gli operandi dovrebbero essere non-negativi.

gmp_init

(PHP 4 >= 4.0.4, PHP 5)

gmp_init -- Crea un numero GMP

Descrizione

resource gmp_init ( mixed number )

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.

Esempio 1. Creare un numero GMP

<?php
    $a = gmp_init (123456);
    $b = gmp_init ("0xFFFFDEBACDFEDF7200");
?>

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

gmp_intval

(PHP 4 >= 4.0.4, PHP 5)

gmp_intval -- Converte un numero GMP in un intero

Descrizione

int gmp_intval ( resource gmpnumber )

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

gmp_invert

(PHP 4 >= 4.0.4, PHP 5)

gmp_invert -- Inversione di modulo

Descrizione

resource gmp_invert ( resource a, resource b )

Calcola l'inverso di a modulo b. Restituisce un valore FALSE se l'inversione non esiste.

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5)

gmp_jacobi -- Simbolo di Jacobi

Descrizione

int gmp_jacobi ( resource a, resource p )

Calcola il simbolo di Jacobi di a e p. p p potrebbe essere dispari e deve essere positivo.

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5)

gmp_legendre -- Simbolo di Legendre

Descrizione

int gmp_legendre ( resource a, resource p )

Calcolo del Legendre symbol di a e p. p potrebbe essere dispari e deve essere positivo.

gmp_mod

(PHP 4 >= 4.0.4, PHP 5)

gmp_mod -- Modulo

Descrizione

resource gmp_mod ( resource n, resource d )

Calcola il modulo di n rispetto a d. Il risultato è sempre non-negativo, il segno di d viene ignorato.

gmp_mul

(PHP 4 >= 4.0.4, PHP 5)

gmp_mul -- Prodotto di numeri

Descrizione

resource gmp_mul ( resource a, resource b )

Moltiplica a per b e restituisce il risultato.

gmp_neg

(PHP 4 >= 4.0.4, PHP 5)

gmp_neg -- Rende un numero negativo

Descrizione

resource gmp_neg ( resource a )

Restituisce a.

gmp_or

(PHP 4 >= 4.0.4, PHP 5)

gmp_or -- OR logico

Descrizione

resource gmp_or ( resource a, resource b )

Calcola l'OR logico di due numeri GMP.

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5)

gmp_perfect_square -- Controllo quadrato perfetto

Descrizione

bool gmp_perfect_square ( resource a )

Restituisce un valore vero TRUE se a è un quadrato perfetto,falso FALSE se non lo è.

Vedere anche: gmp_sqrt(), gmp_sqrtrm().

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5)

gmp_popcount -- Conteggio della popolazione

Descrizione

int gmp_popcount ( resource a )

Restituisce il conteggio della popolazione di a.

gmp_pow

(PHP 4 >= 4.0.4, PHP 5)

gmp_pow -- Eleva un numero a potenza

Descrizione

resource gmp_pow ( resource base, int exp )

Eleva la base base ad una potenza exp. Nel caso di 0^0 il risultato sarà 1. L'argomento exp non può essere negativo.

gmp_powm

(PHP 4 >= 4.0.4, PHP 5)

gmp_powm -- Modulo di un elevamento a potenza.

Descrizione

resource gmp_powm ( resource base, resource exp, resource mod )

Calcola il (base elevato a potenza exp) modulo mod. Se exp è negativo, il risultato sarà indefinito.

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5)

gmp_prob_prime -- Controlla se il numero è "probabilmente primo"

Descrizione

int gmp_prob_prime ( resource a [, int reps] )

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.

gmp_random

(PHP 4 >= 4.0.4, PHP 5)

gmp_random -- Generatore di numeri casuali

Descrizione

resource gmp_random ( int limiter )

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.

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan0 -- Ricerca per 0

Descrizione

int gmp_scan0 ( resource a, int start )

Cerca in a, partendo dal bit startverso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan1 -- Ricerca per 1

Descrizione

int gmp_scan1 ( resource a, int start )

Cerca in a, partendo dal bit start, verso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_setbit -- Imposta bit

Descrizione

resource gmp_setbit ( resource &a, int index [, bool set_clear] )

Sets bit index in a. set_clear definisce se il bit è settato su 0 o su 1. Di default il bit è settato a 1.

gmp_sign

(PHP 4 >= 4.0.4, PHP 5)

gmp_sign -- Segno di un numero

Descrizione

int gmp_sign ( resource a )

Restituisce il segno di a : 1 se a è positivo e -1 se è negativo.

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrt -- Radice quadrata

Descrizione

resource gmp_sqrt ( resource a )

Calcola la radice quadrata di a.

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrtrem -- Radice quadrata con resto

Descrizione

array gmp_sqrtrem ( resource a )

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

gmp_strval

(PHP 4 >= 4.0.4, PHP 5)

gmp_strval -- Converte un numero GMP in una stringa

Descrizione

string gmp_strval ( resource gmpnumber [, int base] )

Converte un numero GMP in una stringa rappresentato in base base. La base di default è 10. Le basi consentite variano dal 2 al 36.

Esempio 1. Converte un numero GMP in una stringa

<?php
    $a = gmp_init("0x41682179fbf5");
    printf ("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

gmp_sub

(PHP 4 >= 4.0.4, PHP 5)

gmp_sub -- Sottrazione di numeri

Descrizione

resource gmp_sub ( resource a, resource b )

Sottrae b da a e restituisce il risultato.

gmp_xor

(PHP 4 >= 4.0.4, PHP 5)

gmp_xor -- XOR logico

Descrizione

resource gmp_xor ( resource a, resource b )

Calcola l'OR logico esclusivo (XOR) di due numeri GMP.

XLVII. Net_Gopher

Introduzione

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.


Installazione

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


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

<?php
dl("gopher.so");

readfile("gopher://gopher.example.com/somedocument");
?>

Sommario
gopher_parsedir -- Translate a gopher formatted directory entry into an associative array.

gopher_parsedir

(PECL)

gopher_parsedir -- Translate a gopher formatted directory entry into an associative array.

Descrizione

array gopher_parsedir ( string dirent )

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.

Esempi

Esempio 1. Hypothetical output from gopher://gopher.example.com/

0All about my gopher site.	/allabout.txt	gopher.example.com	70
9A picture of my cat.	/pics/cat.png	gopher.example.com	70
1A collection of my writings.	/stories	gopher.example.com	70
hThe HTTP version of this site.	URL:http://www.example.com	gopher.example.com	70
1Mirror of this site in Spain.	/	gopher.ejemplo.co.es	70
iWelcome to my gopher site.		error.host	1
iPlease select one of the options above		error.host	1
iSend complaints to /dev/null		error.host	1
iLong live gopher!		error.host	1

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

<?php
dl("gopher.so");

$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}

/* Expected Output
   ---------------

Array (
  [type] => 0
  [title] => All about my gopher site.
  [path] => /allabout.txt
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 9
  [title] => A picture of my cat.
  [path] => /pics/cat.png
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => A collection of my writings.
  [path] => /stories
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 254
  [title] => The HTTP version of this site.
  [path] => URL:http://www.example.com
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => Mirror of this site in Spain.
  [path] => /
  [host] => gopher.ejemplo.co.es
  [port] => 70
)
Array (
  [type] => 255
  [title] => Welcome to my gopher site.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Please select one of the options above.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Send complaints to /dev/null
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Long live gopher!
  [path] =>
  [host] => error.host
  [port] => 1
)
*/
?>

The values given by type are associated with the following constants.

Tabella 1. Gopher Constants

ConstantDefinition
GOPHER_DOCUMENTStandard text/plain document.
GOPHER_DIRECTORYA resource containing a gopher formatted directory listing.
GOPHER_BINHEXA BinHex encoded binary file.
GOPHER_DOSBINARYA DOS formatted binary archive.
GOPHER_UUENCODEDA UUEncoded file.
GOPHER_BINARYA generic binary file.
GOPHER_INFOAn Informational entry
GOPHER_HTTPA reference to an HTTP resource.
GOPHER_UNKNOWN An unrecognized entry, the line will be returned in data.

XLVIII. Funzioni HTTP

Introduzione

Queste funzioni permettono di modificare l'output inviato verso un browser attraverso manipolazioni a livello di protocollo HTTP.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
header -- Spedisce un header HTTP
headers_list -- Returns a list of response headers sent (or ready to send)
headers_sent -- Restituisce TRUE se gli header sono stati trasmessi.
setcookie -- Spedisce un cookie
setrawcookie -- Send a cookie without urlencoding the cookie value

header

(PHP 3, PHP 4, PHP 5)

header -- Spedisce un header HTTP

Descrizione

int header ( string string [, bool replace] )

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:

header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM',false);

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:

header ("Location: http://".$HTTP_SERVER_VARS['HTTP_HOST']
                       ."/".dirname($HTTP_SERVER_VARS['PHP_SELF'])
                       ."/".$relative_url);

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.

header ("HTTP/1.0 404 Not Found");

Nota: In PHP 3, questo funziona solo se PHP è compilato come modulo Apache. Potete ottenere lo stesso effetto usando l'header Status.

header("Status: 404 Not Found");

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

(PHP 5)

headers_list -- Returns a list of response headers sent (or ready to send)

Description

array headers_list ( void )

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

<?php

/* setcookie() will add a response header on its own */
setcookie('foo', 'bar');

/* Define a custom response header
   This will be ignored by most clients */
header("X-Sample-Test: foo");

/* Specify plain text content in our response */
header('Content-type: text/plain');

/* What headers are going to be sent? */
var_dump(headers_list());

?>

this will output :

array(4) {
  [0]=>
  string(12) "X-Powered-By"
  [1]=>
  string(10) "Set-Cookie"
  [2]=>
  string(13) "X-Sample-Test"
  [3]=>
  string(12) "Content-type"
}

See Also: headers_sent(), header(), and setcookie().

headers_sent

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

headers_sent -- Restituisce TRUE se gli header sono stati trasmessi.

Descrizione

bool headers_sent ( void )

Questa funzione restituisce TRUE se gli header HTTP sono stati spedite correttamente, FALSE in caso contrario.

Vedi anche header()

setcookie

(PHP 3, PHP 4, PHP 5)

setcookie -- Spedisce un cookie

Descrizione

int setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]] )

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:

Esempio 1. setcookie() esempi di spedizione/creazione

setcookie ("TestCookie", "Test Value");
setcookie ("TestCookie", $value,time()+3600);  /* aspira in 1 ora */
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".utoronto.ca", 1);

Gli esempi mostrano come cancellare i cookie introdotti nell'esempio precedente:

Esempio 2. setcookie() esempi di cancellazione

setcookie ("TestCookie");
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);
Per cancellare un cookie dovete assicurarvi che la data di scadenza del cookie sia già trascorsa, in questo modo il cookie verrà rimosso dal client.

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:

echo $TestCookie;
echo $HTTP_COOKIE_VARS["TestCookie"];

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&lt;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

(PHP 5)

setrawcookie -- Send a cookie without urlencoding the cookie value

Description

bool setrawcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )

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.

XLIX. Hyperwave Functions

Introduzione

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:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.


Requisiti

This extension needs a Hyperwave server downloadable from http://www.hyperwave.com/.


Installazione

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


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with

RewriteEngine on

You will need scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Hyperwave configuration options

NameDefaultChangeableChangelog
hyperwave.allow_persistent"0"PHP_INI_SYSTEMAvailable since PHP 4.3.2.
hyperwave.default_port"418"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

HW_ATTR_LANG (integer)

HW_ATTR_NR (integer)

HW_ATTR_NONE (integer)


Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().

  • The names of several functions are not fixed, yet.

  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.

  • Conversion form object record into object array needs to handle any multiple attribute.

Sommario
hw_Array2Objrec -- Convert attributes from object array to object record
hw_changeobject --  Changes attributes of an object (obsolete)
hw_Children -- Object ids of children
hw_ChildrenObj -- Object records of children
hw_Close -- Closes the Hyperwave connection
hw_Connect -- Opens a connection
hw_connection_info --  Prints information about the connection to Hyperwave server
hw_cp -- Copies objects
hw_Deleteobject -- Deletes object
hw_DocByAnchor -- Object id object belonging to anchor
hw_DocByAnchorObj -- Object record object belonging to anchor
hw_Document_Attributes -- Object record of hw_document
hw_Document_BodyTag -- Body tag of hw_document
hw_Document_Content -- Returns content of hw_document
hw_Document_SetContent -- Sets/replaces content of hw_document
hw_Document_Size -- Size of hw_document
hw_dummy --  Hyperwave dummy function
hw_EditText -- Retrieve text document
hw_Error -- Error number
hw_ErrorMsg -- Returns error message
hw_Free_Document -- Frees hw_document
hw_GetAnchors -- Object ids of anchors of document
hw_GetAnchorsObj -- Object records of anchors of document
hw_GetAndLock -- Return object record and lock object
hw_GetChildColl -- Object ids of child collections
hw_GetChildCollObj -- Object records of child collections
hw_GetChildDocColl -- Object ids of child documents of collection
hw_GetChildDocCollObj -- Object records of child documents of collection
hw_GetObject -- Object record
hw_GetObjectByQuery -- Search object
hw_GetObjectByQueryColl -- Search object in collection
hw_GetObjectByQueryCollObj -- Search object in collection
hw_GetObjectByQueryObj -- Search object
hw_GetParents -- Object ids of parents
hw_GetParentsObj -- Object records of parents
hw_getrellink --  Get link from source to dest relative to rootid
hw_GetRemote -- Gets a remote document
hw_getremotechildren -- Gets children of remote document
hw_GetSrcByDestObj -- Returns anchors pointing at object
hw_GetText -- Retrieve text document
hw_getusername -- Name of currently logged in user
hw_Identify -- Identifies as user
hw_InCollections -- Check if object ids in collections
hw_Info -- Info about connection
hw_InsColl -- Insert collection
hw_InsDoc -- Insert document
hw_insertanchors --  Inserts only anchors into text
hw_InsertDocument -- Upload any document
hw_InsertObject -- Inserts an object record
hw_mapid -- Maps global id on virtual local id
hw_Modifyobject -- Modifies object record
hw_mv -- Moves objects
hw_New_Document -- Create new document
hw_objrec2array -- Convert attributes from object record to object array
hw_Output_Document -- Prints hw_document
hw_pConnect -- Make a persistent database connection
hw_PipeDocument -- Retrieve any document
hw_Root -- Root object id
hw_setlinkroot --  Set the id to which links are calculated
hw_stat --  Returns status string
hw_Unlock -- Unlock object
hw_Who -- List of currently logged in users

hw_Array2Objrec

(PHP 3 >= 3.0.4, PHP 4, PECL)

hw_Array2Objrec -- Convert attributes from object array to object record

Description

string hw_array2objrec ( array object_array )

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

See also hw_objrec2array().

hw_changeobject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_changeobject --  Changes attributes of an object (obsolete)

Description

bool hw_changeobject ( int link, int objid, array attributes )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_Children

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Children -- Object ids of children

Description

array hw_children ( int connection, int objectID )

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_ChildrenObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_ChildrenObj -- Object records of children

Description

array hw_childrenobj ( int connection, int objectID )

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Close

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Close -- Closes the Hyperwave connection

Description

bool hw_close ( int connection )

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

hw_Connect

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Connect -- Opens a connection

Description

int hw_connect ( string host, int port [, string username, string password] )

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

hw_connection_info

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_connection_info --  Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_cp

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_cp -- Copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination_id )

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

hw_Deleteobject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Deleteobject -- Deletes object

Description

bool hw_deleteobject ( int connection, int object_to_delete )

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

hw_DocByAnchor

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_DocByAnchor -- Object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID )

Returns an th object id of the document to which anchorID belongs.

hw_DocByAnchorObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_DocByAnchorObj -- Object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID )

Returns an th object record of the document to which anchorID belongs.

hw_Document_Attributes

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_Attributes -- Object record of hw_document

Description

string hw_document_attributes ( int hw_document )

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

hw_Document_BodyTag

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_BodyTag -- Body tag of hw_document

Description

string hw_document_bodytag ( int hw_document [, string prefix] )

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

hw_Document_Content

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_Content -- Returns content of hw_document

Description

string hw_document_content ( int hw_document )

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().

hw_Document_SetContent

(PHP 4, PECL)

hw_Document_SetContent -- Sets/replaces content of hw_document

Description

bool hw_document_setcontent ( int hw_document, string content )

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

See also hw_document_attributes(), hw_document_size(), and hw_document_content().

hw_Document_Size

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Document_Size -- Size of hw_document

Description

int hw_document_size ( int hw_document )

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

hw_dummy

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_dummy --  Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_EditText

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_EditText -- Retrieve text document

Description

bool hw_edittext ( int connection, int hw_document )

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), and hw_gettext().

hw_Error

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Error -- Error number

Description

int hw_error ( int connection )

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

hw_ErrorMsg

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_ErrorMsg -- Returns error message

Description

string hw_errormsg ( int connection )

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

hw_Free_Document

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Free_Document -- Frees hw_document

Description

bool hw_free_document ( int hw_document )

Frees the memory occupied by the Hyperwave document.

hw_GetAnchors

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetAnchors -- Object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID )

Returns an array of object ids with anchors of the document with object ID objectID.

hw_GetAnchorsObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetAnchorsObj -- Object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID )

Returns an array of object records with anchors of the document with object ID objectID.

hw_GetAndLock

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetAndLock -- Return object record and lock object

Description

string hw_getandlock ( int connection, int objectID )

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

See also hw_unlock(), and hw_getobject().

hw_GetChildColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildColl -- Object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID )

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

hw_GetChildCollObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildCollObj -- Object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID )

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

hw_GetChildDocColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildDocColl -- Object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID )

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

hw_GetChildDocCollObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetChildDocCollObj -- Object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID )

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

hw_GetObject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObject -- Object record

Description

mixed hw_getobject ( int connection, mixed objectID [, string query] )

Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |

"!" <expr> | /* NOT */

<expr> "||" <expr> | /* OR */

<expr> "&&" <expr> | /* AND */

<attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" | /* equal */

"<" | /* less than (string compare) */

">" | /* greater than (string compare) */

"~" /* regular expression matching */

The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

See also hw_getandlock(), and hw_getobjectbyquery().

hw_GetObjectByQuery

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQuery -- Search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits )

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

hw_GetObjectByQueryColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQueryColl -- Search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits )

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

hw_GetObjectByQueryCollObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQueryCollObj -- Search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits )

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

hw_GetObjectByQueryObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetObjectByQueryObj -- Search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits )

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

hw_GetParents

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetParents -- Object ids of parents

Description

array hw_getparents ( int connection, int objectID )

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetParentsObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetParentsObj -- Object records of parents

Description

array hw_getparentsobj ( int connection, int objectID )

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

hw_getrellink

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_getrellink --  Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_GetRemote

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID )

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources 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().

hw_getremotechildren

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_getremotechildren -- Gets children of remote document

Description

mixed hw_getremotechildren ( int connection, string object_record )

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself 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().

hw_GetSrcByDestObj

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID )

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

hw_GetText

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_GetText -- Retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix] )

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document 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().

hw_getusername

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_getusername -- Name of currently logged in user

Description

string hw_getusername ( int connection )

Returns the username of the connection.

hw_Identify

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Identify -- Identifies as user

Description

string hw_identify ( int link, string username, string password )

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

hw_InCollections

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InCollections -- Check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections )

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

hw_Info

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Info -- Info about connection

Description

string hw_info ( int connection )

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InsColl

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsColl -- Insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array )

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

hw_InsDoc

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsDoc -- Insert document

Description

int hw_insdoc ( resource connection, int parentID, string object_record [, string text] )

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

hw_insertanchors

(PHP 4 >= 4.0.4, PECL)

hw_insertanchors --  Inserts only anchors into text

Description

bool hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_InsertDocument

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsertDocument -- Upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document )

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

hw_InsertObject

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_InsertObject -- Inserts an object record

Description

int hw_insertobject ( int connection, string object_rec, string parameter )

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.

See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().

hw_mapid

(PHP 3 >= 3.0.13, PHP 4, PECL)

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server_id, int object_id )

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

hw_Modifyobject

(PHP 3 >= 3.0.7, PHP 4, PECL)

hw_Modifyobject -- Modifies object record

Description

bool hw_modifyobject ( int connection, int object_to_change, array remove, array add [, int mode] )

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means 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().

Esempio 1. modifying an attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Esempio 2. adding a completely new attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Nota: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Esempio 3. modifying Title attribute

<?php
       $remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
or

Esempio 4. modifying Title attribute

<?php
       $remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
This removes the English title 'Books' and adds the English title 'Articles' and the German title 'Artikel'.

Esempio 5. removing attribute

<?php
       $remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Nota: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Nota: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Nota: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Nota: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Nota: You may not 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.

hw_mv

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_mv -- Moves objects

Description

int hw_mv ( int connection, array object_id_array, int source_id, int destination_id )

Moves the objects with object ids as specified in the second parameter from the collection with id source_id to the collection with the id destination_id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

The value returned is the number of moved objects.

See also hw_cp(), and hw_deleteobject().

hw_New_Document

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_New_Document -- Create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size )

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().

hw_objrec2array

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_objrec2array -- Convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format] )

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.

See also hw_array2objrec().

hw_Output_Document

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Output_Document -- Prints hw_document

Description

bool hw_output_document ( int hw_document )

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

hw_pConnect

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_pConnect -- Make a persistent database connection

Description

int hw_pconnect ( string host, int port [, string username, string password] )

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

hw_PipeDocument

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_PipeDocument -- Retrieve any document

Description

int hw_pipedocument ( int connection, int objectID [, array url_prefixes] )

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

hw_Root

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Root -- Root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

hw_setlinkroot

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_setlinkroot --  Set the id to which links are calculated

Description

int hw_setlinkroot ( int link, int rootid )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_stat

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_stat --  Returns status string

Description

string hw_stat ( int link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_Unlock

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Unlock -- Unlock object

Description

bool hw_unlock ( int connection, int objectID )

Unlocks a document, so other users regain access.

See also hw_getandlock().

hw_Who

(PHP 3 >= 3.0.3, PHP 4, PECL)

hw_Who -- List of currently logged in users

Description

array hw_who ( int connection )

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.

L. Hyperwave API Functions

Introduzione

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.


Requisiti

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.


Installazione

After installing the Hyperwave SDK, configure PHP with --with-hwapi[=DIR].


Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Hyperwave API configuration options

NameDefaultChangeableChangelog
hwapi.allow_persistent"0"PHP_INI_SYSTEM 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Classes

The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.

  • HW_API

  • HW_API_Object

  • HW_API_Attribute

  • HW_API_Error

  • HW_API_Content

  • HW_API_Reason

Some basic classes like HW_API_String, HW_API_String_Array, etc., which exist in the Hyperwave SDK have not been implemented since PHP has powerful replacements for them.

Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing 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.

Sommario
hw_api_attribute->key -- Returns key of the attribute
hw_api_attribute->langdepvalue -- Returns value for a given language
hw_api_attribute->value -- Returns value of the attribute
hw_api_attribute->values -- Returns all values of the attribute
hw_api_attribute -- Creates instance of class hw_api_attribute
hw_api->checkin -- Checks in an object
hw_api->checkout -- Checks out an object
hw_api->children -- Returns children of an object
hw_api_content->mimetype -- Returns mimetype
hw_api_content->read -- Read content
hw_api->content -- Returns content of an object
hw_api->copy -- Copies physically
hw_api->dbstat -- Returns statistics about database server
hw_api->dcstat -- Returns statistics about document cache server
hw_api->dstanchors -- Returns a list of all destination anchors
hw_api->dstofsrcanchor -- Returns destination of a source anchor
hw_api_error->count -- Returns number of reasons
hw_api_error->reason -- Returns reason of error
hw_api->find -- Search for objects
hw_api->ftstat -- Returns statistics about fulltext server
hwapi_hgcsp -- Returns object of class hw_api
hw_api->hwstat -- Returns statistics about Hyperwave server
hw_api->identify -- Log into Hyperwave Server
hw_api->info -- Returns information about server configuration
hw_api->insert -- Inserts a new object
hw_api->insertanchor -- Inserts a new object of type anchor
hw_api->insertcollection -- Inserts a new object of type collection
hw_api->insertdocument -- Inserts a new object of type document
hw_api->link -- Creates a link to an object
hw_api->lock -- Locks an object
hw_api->move -- Moves object between collections
hw_api_content -- Create new instance of class hw_api_content
hw_api_object->assign -- Clones object
hw_api_object->attreditable -- Checks whether an attribute is editable
hw_api_object->count -- Returns number of attributes
hw_api_object->insert -- Inserts new attribute
hw_api_object -- Creates a new instance of class hw_api_object
hw_api_object->remove -- Removes attribute
hw_api_object->title -- Returns the title attribute
hw_api_object->value -- Returns value of attribute
hw_api->object -- Retrieve attribute information
hw_api->objectbyanchor -- Returns the object an anchor belongs to
hw_api->parents -- Returns parents of an object
hw_api_reason->description -- Returns description of reason
hw_api_reason->type -- Returns type of reason
hw_api->remove -- Delete an object
hw_api->replace -- Replaces an object
hw_api->setcommittedversion -- Commits version other than last version
hw_api->srcanchors -- Returns a list of all source anchors
hw_api->srcsofdst -- Returns source of a destination object
hw_api->unlock -- Unlocks a locked object
hw_api->user -- Returns the own user object
hw_api->userlist -- Returns a list of all logged in users

hw_api_attribute->key

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

string hw_api_attribute->key ( void )

Returns the name of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

string hw_api_attribute->langdepvalue ( string language )

Returns the value in the given language of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

string hw_api_attribute->value ( void )

Returns the value of the attribute.

See also hwapi_attribute_key(), hwapi_attribute_values().

hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

array hw_api_attribute->values ( void )

Returns all values of the attribute as an array of strings.

See also hwapi_attribute_value().

hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

HW_API_Attribute hw_api_attribute ( [string name [, string value]] )

Creates a new instance of hw_api_attribute with the given name and value.

hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

bool hw_api->checkin ( array parameter )

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:

HW_API_CHECKIN_NORMAL

Checks in and commits the object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.

HW_API_CHECKIN_FORCE_VERSION_CONTROL

Checks in an object even if it is not under version control.

HW_API_CHECKIN_REVERT_IF_NOT_CHANGED

Check if the new version is different from the last version. Unless this is the case the object will be checked in.

HW_API_CHECKIN_KEEP_TIME_MODIFIED

Keeps the time modified from the most recent object.

HW_API_CHECKIN_NO_AUTO_COMMIT

The object is not automatically committed on check-in.

See also hwapi_checkout().

hw_api->checkout

(no version information, might be only in CVS)

hw_api->checkout -- Checks out an object

Description

bool hw_api->checkout ( array parameter )

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:

HW_API_CHECKIN_NORMAL

Checks out an object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

See also hwapi_checkin().

hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

array hw_api->children ( array parameter )

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_parents().

hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

string hw_api_content->mimetype ( void )

Returns the mimetype of the content.

hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

string hw_api_content->read ( string buffer, int len )

Reads len bytes from the content into the given buffer.

hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

HW_API_Content hw_api->content ( array parameter )

This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

hw_api_object hw_api->copy ( array parameter )

This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

See also hwapi_move(), hwapi_link().

hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

hw_api_object hw_api->dbstat ( array parameter )

See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().

hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

hw_api_object hw_api->dcstat ( array parameter )

See also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

array hw_api->dstanchors ( array parameter )

Retrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_srcanchors().

hw_api->dstofsrcanchor

(no version information, might be only in CVS)

hw_api->dstofsrcanchor -- Returns destination of a source anchor

Description

hw_api_object hw_api->dstofsrcanchor ( array parameter )

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_srcanchors(), hwapi_dstanchors(), hwapi_objectbyanchor().

hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

int hw_api_error->count ( void )

Returns the number of error reasons.

See also hwapi_error_reason().

hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

HW_API_Reason hw_api_error->reason ( void )

Returns the first error reason.

See also hwapi_error_count().

hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

array hw_api->find ( array parameter )

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

hw_api->ftstat

(no version information, might be only in CVS)

hw_api->ftstat -- Returns statistics about fulltext server

Description

hw_api_object hw_api->ftstat ( array parameter )

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().

hwapi_hgcsp

(no version information, might be only in CVS)

hwapi_hgcsp -- Returns object of class hw_api

Description

HW_API hwapi_hgcsp ( string hostname [, int port] )

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP. If you do not pass a port number, 418 is used.

See also hwapi_hwtp().

hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

hw_api_object hw_api->hwstat ( array parameter )

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

bool hw_api->identify ( array parameter )

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.

hw_api->info

(no version information, might be only in CVS)

hw_api->info -- Returns information about server configuration

Description

array hw_api->info ( array parameter )

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().

hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

hw_api_object hw_api->insert ( array parameter )

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set. The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding 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:

HW_API_INSERT_NORMAL

The object in inserted into the server.

HW_API_INSERT_FORCE_VERSION_CONTROL

HW_API_INSERT_AUTOMATIC_CHECKOUT

HW_API_INSERT_PLAIN

HW_API_INSERT_KEEP_TIME_MODIFIED

HW_API_INSERT_DELAY_INDEXING

See also hwapi_replace().

hw_api->insertanchor

(no version information, might be only in CVS)

hw_api->insertanchor -- Inserts a new object of type anchor

Description

hw_api_object hw_api->insertanchor ( array parameter )

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

See also hwapi_insertdocument(), hwapi_insertcollection(), hwapi_insert().

hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

hw_api_object hw_api->insertcollection ( array parameter )

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insertdocument(), hwapi_insertanchor(), hwapi_insert().

hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

hw_api_object hw_api->insertdocument ( array parameter )

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insert() hwapi_insertanchor(), hwapi_insertcollection().

hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

bool hw_api->link ( array parameter )

Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

The function returns TRUE on success or an error object.

See also hwapi_copy().

hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

bool hw_api->lock ( array parameter )

Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the 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().

hw_api->move

(no version information, might be only in CVS)

hw_api->move -- Moves object between collections

Description

bool hw_api->move ( array parameter )

See also hw_objrec2array().

hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

HW_API_Content hw_api_content ( string content, string mimetype )

Creates a new content object from the string content. The mimetype is set to mimetype.

hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

bool hw_api_object->assign ( array parameter )

Clones the attributes of an object.

hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

bool hw_api_object->attreditable ( array parameter )

hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

int hw_api_object->count ( array parameter )

hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

bool hw_api_object->insert ( HW_API_Attribute attribute )

Adds an attribute to the object. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_remove().

hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

hw_api_object hw_api_object ( array parameter )

See also hwapi_lock().

hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

bool hw_api_object->remove ( string name )

Removes the attribute with the given name. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_insert().

hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

string hw_api_object->title ( array parameter )

hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

string hw_api_object->value ( string name )

Returns the value of the attribute with the given name or FALSE if an error occurred.

hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

hw_api_object hw_api->object ( array parameter )

This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

This simple example retrieves an object and checks for errors.

Esempio 1. Retrieve an object

<?php
function handle_error($error) 
{
  $reason = $error->reason(0);
  echo "Type: <b>";
  switch ($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</b><br />\n";
  echo "Description: " . $reason->description("en") . "<br />\n";
}

function list_attr($obj) 
{
  echo "<table>\n";
  $count = $obj->count();
  for ($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("<tr><td align=\"right\" bgcolor=\"#c0c0c0\"><b>%s</b></td><td bgcolor=\"#F0F0F0\">%s</td></tr>\n",
             $attr->key(), $attr->value());
  }
  echo "</table>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection", "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if (get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

See also hwapi_content().

hw_api->objectbyanchor

(no version information, might be only in CVS)

hw_api->objectbyanchor -- Returns the object an anchor belongs to

Description

hw_api_object hw_api->objectbyanchor ( array parameter )

This function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_dstofsrcanchor(), hwapi_srcanchors(), hwapi_dstanchors().

hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

array hw_api->parents ( array parameter )

Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_children().

hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

string hw_api_reason->description ( void )

Returns the description of a reason

hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

HW_API_Reason hw_api_reason->type ( void )

Returns the type of a reason.

hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

bool hw_api->remove ( array parameter )

Removes an object from the specified parent. Collections will be removed recursively. You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance. The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be 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().

hw_api->replace

(no version information, might be only in CVS)

hw_api->replace -- Replaces an object

Description

hw_api_object hw_api->replace ( array parameter )

Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL

The object on the server is replace with the object passed.

HW_API_REPLACE_FORCE_VERSION_CONTROL

HW_API_REPLACE_AUTOMATIC_CHECKOUT

HW_API_REPLACE_AUTOMATIC_CHECKIN

HW_API_REPLACE_PLAIN

HW_API_REPLACE_REVERT_IF_NOT_CHANGED

HW_API_REPLACE_KEEP_TIME_MODIFIED

See also hwapi_insert().

hw_api->setcommittedversion

(no version information, might be only in CVS)

hw_api->setcommittedversion -- Commits version other than last version

Description

hw_api_object hw_api->setcommittedversion ( array parameter )

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

hw_api->srcanchors

(no version information, might be only in CVS)

hw_api->srcanchors -- Returns a list of all source anchors

Description

array hw_api->srcanchors ( array parameter )

Retrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_dstanchors().

hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

array hw_api->srcsofdst ( array parameter )

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

See also hwapi_dstofsrcanchor().

hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

bool hw_api->unlock ( array parameter )

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Returns TRUE on success or an object of class HW_API_Error.

See also hwapi_lock().

hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

hw_api_object hw_api->user ( array parameter )

See also hwapi_userlist().

hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

array hw_api->userlist ( array parameter )

See also hwapi_user().

LI. IBM DB2, Cloudscape and Apache Derby Functions

Introduzione

These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).


Requisiti

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.


Requirements on Linux or Unix

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
If you do not set this option in php.ini, you must issue the following command to modify your environment variables to enable access to DB2:
bash$ source /home/db2inst1/sqllib/db2profile
To enable your PHP-enabled Web server to access these functions, you must either set the ibm_db2.instance_name configuration option in php.ini, or source the DB2 instance environment in your Web server start script (typically /etc/init.d/httpd or /etc/init.d/apache).


Installazione

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
The configure command defaults to /opt/IBM/db2/V8.1.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. ibm_db2 Opioni di configurazione

NomeDefaultModificabileChangelog
ibm_db2.binmode"1"PHP_INI_ALL 
ibm_db2.instance_nameNULLPHP_INI_SYSTEM 

Breve descrizione dei parametri di configurazione.

ibm_db2.binmode integer

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)

ibm_db2.instance_name string

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.


Costanti predefinite

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.

DB2_BINARY (integer)

Specifies that binary data shall be returned as is. This is the default mode.

DB2_CONVERT (integer)

Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.

DB2_PASSTHRU (integer)

Specifies that binary data shall be converted to a NULL value.

DB2_SCROLLABLE (integer)

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.

DB2_FORWARD_ONLY (integer)

Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

DB2_PARAM_IN (integer)

Specifies the PHP variable should be bound as an IN parameter for a stored procedure.

DB2_PARAM_OUT (integer)

Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.

DB2_PARAM_INOUT (integer)

Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.

DB2_PARAM_FILE (integer)

Specifies that the column should be bound directly to a file for input or output.

DB2_AUTOCOMMIT_ON (integer)

Specifies that autocommit should be turned on.

DB2_AUTOCOMMIT_OFF (integer)

Specifies that autocommit should be turned off.

DB2_DOUBLE (integer)

Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.

DB2_LONG (integer)

Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.

DB2_CHAR (integer)

Specifies that the variable should be bound as a CHAR or VARCHAR data type.


Tipi di risorse

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

Sommario
db2_autocommit --  Returns or sets the AUTOCOMMIT state for a database connection
db2_bind_param --  Binds a PHP variable to an SQL statement parameter
db2_client_info -- Returns an object with properties that describe the DB2 database client
db2_close --  Closes a database connection
db2_column_privileges --  Returns a result set listing the columns and associated privileges for a table
db2_columns --  Returns a result set listing the columns and associated metadata for a table
db2_commit --  Commits a transaction
db2_conn_error --  Returns a string containing the SQLSTATE returned by the last connection attempt
db2_conn_errormsg --  Returns the last connection error message and SQLCODE value
db2_connect --  Returns a connection to a database
db2_cursor_type --  Returns the cursor type used by a statement resource
db2_exec --  Executes an SQL statement directly
db2_execute --  Executes a prepared SQL statement
db2_fetch_array --  Returns an array, indexed by column position, representing a row in a result set
db2_fetch_assoc --  Returns an array, indexed by column name, representing a row in a result set
db2_fetch_both --  Returns an array, indexed by both column name and position, representing a row in a result set
db2_fetch_object --  Returns an object with properties representing columns in the fetched row
db2_fetch_row --  Sets the result set pointer to the next row or requested row
db2_field_display_size --  Returns the maximum number of bytes required to display a column
db2_field_name --  Returns the name of the column in the result set
db2_field_num --  Returns the position of the named column in a result set
db2_field_precision --  Returns the precision of the indicated column in a result set
db2_field_scale --  Returns the scale of the indicated column in a result set
db2_field_type --  Returns the data type of the indicated column in a result set
db2_field_width --  Returns the width of the current value of the indicated column in a result set
db2_foreign_keys --  Returns a result set listing the foreign keys for a table
db2_free_result --  Frees resources associated with a result set
db2_free_stmt --  Frees resources associated with the indicated statement resource
db2_next_result --  Requests the next result set from a stored procedure
db2_num_fields --  Returns the number of fields contained in a result set
db2_num_rows --  Returns the number of rows affected by an SQL statement
db2_pconnect --  Returns a persistent connection to a database
db2_prepare --  Prepares an SQL statement to be executed
db2_primary_keys --  Returns a result set listing primary keys for a table
db2_procedure_columns --  Returns a result set listing stored procedure parameters
db2_procedures --  Returns a result set listing the stored procedures registered in a database
db2_result --  Returns a single column from a row in the result set
db2_rollback --  Rolls back a transaction
db2_server_info -- Returns an object with properties that describe the DB2 database server
db2_special_columns --  Returns a result set listing the unique row identifier columns for a table
db2_statistics --  Returns a result set listing the index and statistics for a table
db2_stmt_error --  Returns a string containing the SQLSTATE returned by an SQL statement
db2_stmt_errormsg --  Returns a string containing the last SQL statement error message
db2_table_privileges --  Returns a result set listing the tables and associated privileges in a database
db2_tables --  Returns a result set listing the tables and associated metadata in a database

db2_autocommit

(PECL)

db2_autocommit --  Returns or sets the AUTOCOMMIT state for a database connection

Descrizione

mixed db2_autocommit ( resource connection [, bool value] )

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

Elenco dei parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

value

One of the following constants:

DB2_AUTOCOMMIT_OFF

Turns AUTOCOMMIT off.

DB2_AUTOCOMMIT_ON

Turns AUTOCOMMIT on.

Valori restituiti

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.

Esempi

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.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

Il precedente esempio visualizzerà:

0 -- AUTOCOMMIT is off.

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.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);

// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
    print "Turning AUTOCOMMIT on succeeded.\n";
}

// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

Il precedente esempio visualizzerà:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

db2_bind_param

(PECL)

db2_bind_param --  Binds a PHP variable to an SQL statement parameter

Descrizione

bool db2_bind_param ( resource stmt, int parameter-number, string variable-name [, int parameter-type [, int data-type [, int precision [, int scale]]]] )

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

Elenco dei parametri

stmt

A prepared statement returned from db2_prepare().

parameter-number

Specifies the 1-indexed position of the parameter in the prepared statement.

variable-name

A string specifying the name of the PHP variable to bind to the parameter specified by parameter-number.

parameter-type

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

data-type

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 .

precision

Specifies the precision with which the variable should be bound to the database.

scale

Specifies the scale with which the variable should be bound to the database.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

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

<?php

$sql = 'SELECT name, breed, weight FROM animals
    WHERE weight > ? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;

db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);

// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;

if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
        print "{$row[0]}, {$row[1]}, {$row[2]}\n";	
    }
}
?>

Il precedente esempio visualizzerà:

Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3

Esempio 2. Calling stored procedures with IN and OUT parameters

The stored procedure match_animal in the following example accepts three different parameters:

  1. an input (IN) parameter that accepts the name of the first animal as input

  2. an input-output (INOUT) parameter that accepts the name of the second animal as input and returns the string TRUE if an animal in the database matches that name

  3. an output (OUT) parameter that returns the sum of the weight of the two identified animals

In addition, the stored procedure returns a result set consisting of the animals listed in alphabetic order starting at the animal corresponding to the input value of the first parameter and ending at the animal corresponding to the input value of the second parameter.

<?php

$sql = 'CALL match_animal(?, ?, ?)';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

$name = "Peaches";
$second_name = "Rickety Ride";
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "second_name", DB2_PARAM_INOUT);
db2_bind_param($stmt, 3, "weight", DB2_PARAM_OUT);

print "Values of bound parameters _before_ CALL:\n";
print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

if (db2_execute($stmt)) {
    print "Values of bound parameters _after_ CALL:\n";
    print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

    print "Results:\n";
    while ($row = db2_fetch_array($stmt)) {
        print "  {$row[0]}, {$row[1]}, {$row[2]}\n";	
    }
}
?>

Il precedente esempio visualizzerà:

Values of bound parameters _before_ CALL:
  1: Peaches 2: Rickety Ride 3:

Values of bound parameters _after_ CALL:
  1: Peaches 2: TRUE 3: 22

Results:
  Peaches, dog, 12.3
  Pook, cat, 3.2
  Rickety Ride, goat, 9.7

db2_client_info

(no version information, might be only in CVS)

db2_client_info -- Returns an object with properties that describe the DB2 database client

Descrizione

object db2_client_info ( resource connection )

This 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 nameReturn typeDescription
APPL_CODEPAGEintThe application code page.
CONN_CODEPAGEintThe code page for the current connection.
DATA_SOURCE_NAMEstringThe data source name (DSN) used to create the current connection to the database.
DRIVER_NAMEstringThe name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VERstringThe 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_VERstringThe 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_CONFORMANCEstringThe level of ODBC SQL grammar supported by the client:

MINIMUM

Supports the minimum ODBC SQL grammar.

CORE

Supports the core ODBC SQL grammar.

EXTENDED

Supports extended ODBC SQL grammar.

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

Elenco dei parametri

connection

Specifies an active DB2 client connection.

Valori restituiti

Returns an object on a successful call. Returns FALSE on failure.

Esempi

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

<?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );

if ($client) {
    echo "DRIVER_NAME: "; 		var_dump( $client->DRIVER_NAME );	 
    echo "DRIVER_VER: "; 		var_dump( $client->DRIVER_VER );	 
    echo "DATA_SOURCE_NAME: "; 		var_dump( $client->DATA_SOURCE_NAME );	 
    echo "DRIVER_ODBC_VER: "; 		var_dump( $client->DRIVER_ODBC_VER );	 
    echo "ODBC_VER: "; 			var_dump( $client->ODBC_VER );	 
    echo "ODBC_SQL_CONFORMANCE: "; 	var_dump( $client->ODBC_SQL_CONFORMANCE );	 
    echo "APPL_CODEPAGE: "; 		var_dump( $client->APPL_CODEPAGE );	 
    echo "CONN_CODEPAGE: "; 		var_dump( $client->CONN_CODEPAGE );	 
}
else {
    echo "Error retrieving client information.
     Perhaps your database connection was invalid.";
}
db2_close($conn);

?>

Il precedente esempio visualizzerà:

DRIVER_NAME: string(8) "libdb2.a"
DRIVER_VER: string(10) "08.02.0001"
DATA_SOURCE_NAME: string(6) "SAMPLE"
DRIVER_ODBC_VER: string(5) "03.51"
ODBC_VER: string(10) "03.01.0000"
ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
APPL_CODEPAGE: int(819)
CONN_CODEPAGE: int(819)

Vedere anche:

db2_server_info()

db2_close

(PECL)

db2_close --  Closes a database connection

Descrizione

bool db2_close ( resource connection )

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.

Elenco dei parametri

connection

Specifies an active DB2 client connection.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

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.

<?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

Il precedente esempio visualizzerà:

Connection was successfully closed.

db2_column_privileges

(PECL)

db2_column_privileges --  Returns a result set listing the columns and associated privileges for a table

Descrizione

resource db2_column_privileges ( resource connection [, string qualifier [, string schema [, string table-name [, string column-name]]]] )

Returns a result set listing the columns and associated privileges for a table.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. To match all schemas, pass NULL or an empty string.

table-name

The name of the table or view. To match all tables in the database, pass NULL or an empty string.

column-name

The name of the column. To match all columns in the table, pass NULL or an empty string.

Valori restituiti

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 nameDescription
TABLE_CATName of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema.
TABLE_NAMEName of the table or view.
COLUMN_NAMEName of the column.
GRANTORAuthorization ID of the user who granted the privilege.
GRANTEEAuthorization ID of the user to whom the privilege was granted.
PRIVILEGEThe privilege for the column.
IS_GRANTABLEWhether the GRANTEE is permitted to grant this privilege to other users.

db2_columns

(PECL)

db2_columns --  Returns a result set listing the columns and associated metadata for a table

Descrizione

resource db2_columns ( resource connection [, string qualifier [, string schema [, string table-name [, string column-name]]]] )

Returns a result set listing the columns and associated metadata for a table.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. To match all schemas, pass '%'.

table-name

The name of the table or view. To match all tables in the database, pass NULL or an empty string.

column-name

The name of the column. To match all columns in the table, pass NULL or an empty string.

Valori restituiti

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 nameDescription
TABLE_CATName of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema.
TABLE_NAMEName of the table or view.
COLUMN_NAMEName of the column.
DATA_TYPEThe SQL data type for the column represented as an integer value.
TYPE_NAMEA string representing the data type for the column.
COLUMN_SIZEAn 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).
NULLABLEAn integer value representing whether the column is nullable or not.
REMARKSDescription of the column.
COLUMN_DEFDefault value for the column.
SQL_DATA_TYPEAn 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_POSITIONThe 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_commit

(PECL)

db2_commit --  Commits a transaction

Descrizione

bool db2_commit ( resource connection )

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.

Elenco dei parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

db2_conn_error

(PECL)

db2_conn_error --  Returns a string containing the SQLSTATE returned by the last connection attempt

Descrizione

string db2_conn_error ( [resource connection] )

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

Elenco dei parametri

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Valori restituiti

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.

Esempi

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

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print "SQLSTATE value: " . db2_conn_error();
}
?>

Il precedente esempio visualizzerà:

SQLSTATE value: 08001

db2_conn_errormsg

(PECL)

db2_conn_errormsg --  Returns the last connection error message and SQLCODE value

Descrizione

string db2_conn_errormsg ( [resource connection] )

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.

Elenco dei parametri

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Valori restituiti

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.

Esempi

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

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print db2_conn_errormsg();
}
?>

Il precedente esempio visualizzerà:

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

db2_connect

(PECL)

db2_connect --  Returns a connection to a database

Descrizione

resource db2_connect ( string database, string username, string password [, array options] )

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

Elenco dei parametri

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:

database

The name of the database.

hostname

The hostname or IP address of the database server.

port

The TCP/IP port on which the database is listening for requests.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

username

The username with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

password

The password with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

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.

Valori restituiti

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.

Esempi

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.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$conn = db2_connect($database, $user, $password);

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Il precedente esempio visualizzerà:

Connection succeeded.

Esempio 2. Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$hostname = 'localhost';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Il precedente esempio visualizzerà:

Connection succeeded.

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.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);

$conn = db2_connect($database, $user, $password, $options);

if ($conn) {
    echo "Connection succeeded.\n";
    if (db2_autocommit($conn)) {
         echo "Autocommit is on.\n";
    }
    else {
         echo "Autocommit is off.\n";
    }
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Il precedente esempio visualizzerà:

Connection succeeded.
Autocommit is off.

db2_cursor_type

(PECL)

db2_cursor_type --  Returns the cursor type used by a statement resource

Descrizione

int db2_cursor_type ( resource stmt )

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.

Elenco dei parametri

stmt

A valid statement resource.

Valori restituiti

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.

Vedere anche:

db2_prepare()

db2_exec

(PECL)

db2_exec --  Executes an SQL statement directly

Descrizione

resource db2_exec ( resource connection, string statement [, array options] )

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.

Elenco dei parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement. The statement cannot contain any parameter markers.

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

cursor

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.

Valori restituiti

Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.

Esempi

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.

<?php
$conn = db2_connect($database, $user, $password);

// Create the test table
$create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32),
    name CHAR(16), weight DECIMAL(7,2))';
$result = db2_exec($conn, $create);
if ($result) {
    print "Successfully created the table.\n";
}

// Populate the test table
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
    array(3, 'gold fish', 'Bubbles', 0.1),
    array(4, 'budgerigar', 'Gizmo', 0.2),
    array(5, 'goat', 'Rickety Ride', 9.7),
    array(6, 'llama', 'Sweater', 150)
);

foreach ($animals as $animal) {
    $rc = db2_exec($conn, "INSERT INTO animals (id, breed, name, weight)
      VALUES ({$animal[0]}, '{$animal[1]}', '{$animal[2]}', {$animal[3]})");
    if ($rc) {
        print "Insert... ";
    }
}
?>

Il precedente esempio visualizzerà:

Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...

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

<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
    WHERE weight < 10.0
    ORDER BY name";
if ($conn) {
    require_once('prepare.inc');
    $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
    while ($row = db2_fetch_array($stmt)) {
        print "$row[0]\n";
    }
} 
?>

Il precedente esempio visualizzerà:

Bubbles
Gizmo
Pook
Rickety Ride

db2_execute

(PECL)

db2_execute --  Executes a prepared SQL statement

Descrizione

bool db2_execute ( resource stmt [, array parameters] )

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

Elenco dei parametri

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

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

<?php
$pet = array(0, 'cat', 'Pook', 3.2);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';

$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    $result = db2_execute($stmt, $pet);
    if ($result) {
        print "Successfully added new pet.";
    }
}
?>

Il precedente esempio visualizzerà:

Successfully added new pet.

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.

<?php
$num_pets = 0;
$res = db2_prepare($conn, "CALL count_my_pets(?)");
$rc = db2_bind_param($res, 1, "num_pets", DB2_PARAM_OUT);
$rc = db2_execute($res);
print "I have $num_pets pets!";
?>

Il precedente esempio visualizzerà:

I have 7 pets!

db2_fetch_array

(PECL)

db2_fetch_array --  Returns an array, indexed by column position, representing a row in a result set

Descrizione

array db2_fetch_array ( resource stmt [, int row_number] )

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

Elenco dei parametri

stmt

A valid stmt resource containing a result set.

row_number

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.

Valori restituiti

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.

Esempi

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_array($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n", 
        $row[0], $row[1], $row[2], $row[3]);
}
?>

Il precedente esempio visualizzerà:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_array($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n", 
        $row[0], $row[1], $row[2], $row[3]);
    $i = $i + 2;
}
?>

Il precedente esempio visualizzerà:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

db2_fetch_assoc

(PECL)

db2_fetch_assoc --  Returns an array, indexed by column name, representing a row in a result set

Descrizione

array db2_fetch_assoc ( resource stmt [, int row_number] )

Returns an array, indexed by column name, representing a row in a result set.

Elenco dei parametri

stmt

A valid stmt resource containing a result set.

row_number

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.

Valori restituiti

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.

Esempi

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_assoc($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n", 
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
}
?>

Il precedente esempio visualizzerà:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n", 
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
    $i = $i + 2;
}
?>

Il precedente esempio visualizzerà:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

db2_fetch_both

(PECL)

db2_fetch_both --  Returns an array, indexed by both column name and position, representing a row in a result set

Descrizione

array db2_fetch_both ( resource stmt [, int row_number] )

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

Elenco dei parametri

stmt

A valid stmt resource containing a result set.

row_number

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.

Valori restituiti

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.

Esempi

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_both($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n", 
        $row['ID'], $row[0], $row['BREED'], $row[3]);
}
?>

Il precedente esempio visualizzerà:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_both($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n", 
        $row[0], $row['NAME'], $row[2], $row['WEIGHT']);
    $i = $i + 2;
}
?>

Il precedente esempio visualizzerà:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

db2_fetch_object

(PECL)

db2_fetch_object --  Returns an object with properties representing columns in the fetched row

Descrizione

object db2_fetch_object ( resource stmt [, int row_number] )

Returns an object in which each property represents a column returned in the row fetched from a result set.

Elenco dei parametri

stmt

A valid stmt resource containing a result set.

row_number

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.

Valori restituiti

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.

Esempi

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

<?php
$conn = db2_connect($database, $user, $password);

$sql = "SELECT breed, RTRIM(name) AS name
    FROM animals
    WHERE id = ?";

if ($conn) {
    $stmt = db2_prepare($conn, $sql);
    db2_execute($stmt, array(0));

    while ($pet = db2_fetch_object($stmt)) {
        echo "Come here, {$pet->NAME}, my little {$pet->BREED}!";
    }
    db2_close($conn);
}
?>

Il precedente esempio visualizzerà:

Come here, Pook, my little cat!

db2_fetch_row

(PECL)

db2_fetch_row --  Sets the result set pointer to the next row or requested row

Descrizione

bool db2_fetch_row ( resource stmt [, int row_number] )

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.

Elenco dei parametri

stmt

A valid stmt resource.

row_number

With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.

Valori restituiti

Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.

Esempi

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

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 1);
    print "$name $breed";
}
?>

Il precedente esempio visualizzerà:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

db2_field_display_size

(PECL)

db2_field_display_size --  Returns the maximum number of bytes required to display a column

Descrizione

int db2_field_display_size ( resource stmt, mixed column )

Returns the maximum number of bytes required to display a column in a result set.

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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

(PECL)

db2_field_name --  Returns the name of the column in the result set

Descrizione

string db2_field_name ( resource stmt, mixed column )

Returns the name of the specified column in the result set.

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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_num

(PECL)

db2_field_num --  Returns the position of the named column in a result set

Descrizione

int db2_field_num ( resource stmt, mixed column )

Returns the position of the named column in a result set.

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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_precision

(PECL)

db2_field_precision --  Returns the precision of the indicated column in a result set

Descrizione

int db2_field_precision ( resource stmt, mixed column )

Returns the precision of the indicated column in a result set.

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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_scale

(PECL)

db2_field_scale --  Returns the scale of the indicated column in a result set

Descrizione

int db2_field_scale ( resource stmt, mixed column )

Returns the scale of the indicated column in a result set.

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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_type

(PECL)

db2_field_type --  Returns the data type of the indicated column in a result set

Descrizione

string db2_field_type ( resource stmt, mixed column )

Returns the data type of the indicated column in a result set.

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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_width

(PECL)

db2_field_width --  Returns the width of the current value of the indicated column in a result set

Descrizione

int db2_field_width ( resource stmt, mixed column )

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

Elenco dei parametri

stmt

Specifies a statement resource containing a result set.

column

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.

Valori restituiti

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_foreign_keys

(PECL)

db2_foreign_keys --  Returns a result set listing the foreign keys for a table

Descrizione

resource db2_foreign_keys ( resource connection, string qualifier, string schema, string table-name )

Returns a result set listing the foreign keys for a table.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. If schema is NULL, db2_foreign_keys() matches the schema for the current connection.

table-name

The name of the table.

Valori restituiti

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 nameDescription
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_NAMEName of the table containing the primary key.
PKCOLUMN_NAMEName 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_NAMEName of the table containing the foreign key.
FKCOLUMN_NAMEName of the column containing the foreign key.
KEY_SEQ1-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_NAMEThe name of the foreign key.
PK_NAMEThe 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_free_result

(PECL)

db2_free_result --  Frees resources associated with a result set

Descrizione

bool db2_free_result ( resource stmt )

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.

Elenco dei parametri

stmt

A valid statement resource.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

db2_free_stmt()

db2_free_stmt

(PECL)

db2_free_stmt --  Frees resources associated with the indicated statement resource

Descrizione

bool db2_free_stmt ( resource stmt )

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.

Elenco dei parametri

stmt

A valid statement resource.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

db2_free_result()

db2_next_result

(PECL)

db2_next_result --  Requests the next result set from a stored procedure

Descrizione

resource db2_next_result ( resource stmt )

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.

Elenco dei parametri

stmt

A prepared statement returned from db2_exec() or db2_execute().

Valori restituiti

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.

Esempi

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.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
  $stmt = db2_exec($conn, 'CALL multiResults()');

  print "Fetching first result set\n";
  while ($row = db2_fetch_array($stmt)) {
    var_dump($row);
  }

  print "\nFetching second result set\n";
  $res = db2_next_result($stmt);
  if ($res) {
    while ($row = db2_fetch_array($res)) {
      var_dump($row);
    }
  }

  print "\nFetching third result set\n";
  $res2 = db2_next_result($stmt);
  if ($res2) {
    while ($row = db2_fetch_array($res2)) {
      var_dump($row);
    }
  }

  db2_close($conn);
}
?>

Il precedente esempio visualizzerà:

Fetching first result set
array(2) {
  [0]=>
  string(16) "Bubbles         "
  [1]=>
  int(3)
}
array(2) {
  [0]=>
  string(16) "Gizmo           "
  [1]=>
  int(4)
}

Fetching second result set
array(4) {
  [0]=>
  string(16) "Sweater         "
  [1]=>
  int(6)
  [2]=>
  string(5) "llama"
  [3]=>
  string(6) "150.00"
}
array(4) {
  [0]=>
  string(16) "Smarty          "
  [1]=>
  int(2)
  [2]=>
  string(5) "horse"
  [3]=>
  string(6) "350.00"
}

Fetching third result set
array(1) {
  [0]=>
  string(16) "Bubbles         "
}
array(1) {
  [0]=>
  string(16) "Gizmo           "
}

db2_num_fields

(PECL)

db2_num_fields --  Returns the number of fields contained in a result set

Descrizione

int db2_num_fields ( resource stmt )

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.

Elenco dei parametri

stmt

A valid statement resource containing a result set.

Valori restituiti

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.

Esempi

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.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, $sql);
$columns = db2_num_fields($stmt);

echo "There are {$columns} columns in the result set.";
?>

Il precedente esempio visualizzerà:

There are 4 columns in the result set.

db2_num_rows

(PECL)

db2_num_rows --  Returns the number of rows affected by an SQL statement

Descrizione

int db2_num_rows ( resource stmt )

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.

Elenco dei parametri

stmt

A valid stmt resource containing a result set.

Valori restituiti

Returns the number of rows affected by the last SQL statement issued by the specified statement handle.

db2_pconnect

(PECL)

db2_pconnect --  Returns a persistent connection to a database

Descrizione

resource db2_pconnect ( string database, string username, string password [, array options] )

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.

Elenco dei parametri

database

The database alias in the DB2 client catalog.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

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.

Valori restituiti

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.

Esempi

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.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$pconn = db2_pconnect($database, $user, $password);

if ($pconn) {
    echo "Persistent connection succeeded.";
}
else {
    echo "Persistent connection failed.";
}

$pconn2 = db2_pconnect($database, $user, $password);
if ($pconn) {
    echo "Second persistent connection succeeded.";
}
else {
    echo "Second persistent connection failed.";
}
?>

Il precedente esempio visualizzerà:

Persistent connection succeeded.
Second persistent connection succeeded.

Vedere anche:

db2_connect()

db2_prepare

(PECL)

db2_prepare --  Prepares an SQL statement to be executed

Descrizione

resource db2_prepare ( resource connection, string statement [, array options] )

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

Elenco dei parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement, optionally containing one or more parameter markers..

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

cursor

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.

Valori restituiti

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

Esempi

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

<?php
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    foreach ($animals as $animal) {
        $result = db2_execute($stmt, $animal);
    }
}
?>

db2_primary_keys

(PECL)

db2_primary_keys --  Returns a result set listing primary keys for a table

Descrizione

resource db2_primary_keys ( resource connection, string qualifier, string schema, string table-name )

Returns a result set listing the primary keys for a table.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. If schema is NULL, db2_primary_keys() matches the schema for the current connection.

table-name

The name of the table.

Valori restituiti

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 nameDescription
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_NAMEName of the table containing the primary key.
COLUMN_NAMEName of the column containing the primary key.
KEY_SEQ1-indexed position of the column in the key.
PK_NAMEThe name of the primary key.

db2_procedure_columns

(PECL)

db2_procedure_columns --  Returns a result set listing stored procedure parameters

Descrizione

resource db2_procedure_columns ( resource connection, string qualifier, string schema, string procedure, string parameter )

Returns a result set listing the parameters for one or more stored procedures.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

parameter

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.

Valori restituiti

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 nameDescription
PROCEDURE_CATThe catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEMName of the schema that contains the stored procedure.
PROCEDURE_NAMEName of the procedure.
COLUMN_NAMEName of the parameter.
COLUMN_TYPE

An integer value representing the type of the parameter:

Return valueParameter type
1 (SQL_PARAM_INPUT)Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT)Input/output (INOUT) parameter.
3 (SQL_PARAM_OUTPUT)Output (OUT) parameter.

DATA_TYPEThe SQL data type for the parameter represented as an integer value.
TYPE_NAMEA string representing the data type for the parameter.
COLUMN_SIZEAn 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).
NULLABLEAn integer value representing whether the parameter is nullable or not.
REMARKSDescription of the parameter.
COLUMN_DEFDefault value for the parameter.
SQL_DATA_TYPEAn 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_POSITIONThe 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_procedures

(PECL)

db2_procedures --  Returns a result set listing the stored procedures registered in a database

Descrizione

resource db2_procedures ( resource connection, string qualifier, string schema, string procedure )

Returns a result set listing the stored procedures registered in a database.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

Valori restituiti

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 nameDescription
PROCEDURE_CATThe catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEMName of the schema that contains the stored procedure.
PROCEDURE_NAMEName of the procedure.
NUM_INPUT_PARAMSNumber of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMSNumber of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETSNumber of result sets returned by the stored procedure.
REMARKSAny comments about the stored procedure.
PROCEDURE_TYPEAlways returns 1, indicating that the stored procedure does not return a return value.

db2_result

(PECL)

db2_result --  Returns a single column from a row in the result set

Descrizione

mixed db2_result ( resource stmt, mixed column )

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.

Elenco dei parametri

stmt

A valid stmt resource.

column

Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.

Valori restituiti

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.

Esempi

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

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 'BREED');
    print "$name $breed";
}
?>

Il precedente esempio visualizzerà:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

db2_rollback

(PECL)

db2_rollback --  Rolls back a transaction

Descrizione

bool db2_rollback ( resource connection )

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.

Elenco dei parametri

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

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.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";
    
    // Turn AUTOCOMMIT off
    db2_autocommit($conn, DB2_AUTOCOMMIT_OFF);
   
    // Delete all rows from ANIMALS
    db2_exec($conn, "DELETE FROM animals");
    
    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";
    
    // Roll back the DELETE statement
    db2_rollback( $conn );
    
    $stmt = db2_exec( $conn, "SELECT count(*) FROM animals" );
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";
    db2_close($conn);
}
?>

Il precedente esempio visualizzerà:

7
0
7

db2_server_info

(no version information, might be only in CVS)

db2_server_info -- Returns an object with properties that describe the DB2 database server

Descrizione

object db2_server_info ( resource connection )

This 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 nameReturn typeDescription
DBMS_NAMEstringThe 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_VERstringThe 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_CODEPAGEintThe code page of the database to which you are connected.
DB_NAMEstringThe name of the database to which you are connected.
DFT_ISOLATIONstringThe default transaction isolation level supported by the server:

UR

Uncommitted read: changes are immediately visible by all concurrent transactions.

CS

Cursor stability: a row read by one transaction can be altered and committed by a second concurrent transaction.

RS

Read stability: a transaction can add or remove rows matching a search condition or a pending transaction.

RR

Repeatable read: data affected by pending transaction is not available to other transactions.

NC

No commit: any changes are visible at the end of a successful operation. Explicit commits and rollbacks are not allowed.

IDENTIFIER_QUOTE_CHARstringThe character used to delimit an identifier.
INST_NAMEstringThe instance on the database server that contains the database.
ISOLATION_OPTIONarrayAn array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDSarrayAn array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSEboolTRUE 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_LENintMaximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LENintMaximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZEintMaximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LENintMaximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZEintMaximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LENintMaximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LENintMaximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LENintMaximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNSboolTRUE 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.
PROCEDURESboolTRUE 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_CHARSstringA string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCEstringThe level of conformance to the ANSI/ISO SQL-92 specification offered by the database server:

ENTRY

Entry-level SQL-92 compliance.

FIPS127

FIPS-127-2 transitional compliance.

FULL

Full level SQL-92 compliance.

INTERMEDIATE

Intermediate level SQL-92 compliance.

Elenco dei parametri

connection

Specifies an active DB2 client connection.

Valori restituiti

Returns an object on a successful call. Returns FALSE on failure.

Esempi

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

<?php

$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');

$server = db2_server_info( $conn );

if ($server) {
    echo "DBMS_NAME: ";                 var_dump( $server->DBMS_NAME );
    echo "DBMS_VER: ";                  var_dump( $server->DBMS_VER );
    echo "DB_CODEPAGE: ";               var_dump( $server->DB_CODEPAGE );
    echo "DB_NAME: ";                   var_dump( $server->DB_NAME );
    echo "INST_NAME: ";                 var_dump( $server->INST_NAME );
    echo "SPECIAL_CHARS: ";             var_dump( $server->SPECIAL_CHARS );
    echo "KEYWORDS: ";                  var_dump( sizeof($server->KEYWORDS) );
    echo "DFT_ISOLATION: ";             var_dump( $server->DFT_ISOLATION );
    echo "ISOLATION_OPTION: ";
    $il = '';
    foreach( $server->ISOLATION_OPTION as $opt )
    {
       $il .= $opt." ";
    }
    var_dump( $il );
    echo "SQL_CONFORMANCE: ";           var_dump( $server->SQL_CONFORMANCE );
    echo "PROCEDURES: ";                var_dump( $server->PROCEDURES );
    echo "IDENTIFIER_QUOTE_CHAR: ";     var_dump( $server->IDENTIFIER_QUOTE_CHAR );
    echo "LIKE_ESCAPE_CLAUSE: ";        var_dump( $server->LIKE_ESCAPE_CLAUSE );
    echo "MAX_COL_NAME_LEN: ";          var_dump( $server->MAX_COL_NAME_LEN );
    echo "MAX_ROW_SIZE: ";              var_dump( $server->MAX_ROW_SIZE );
    echo "MAX_IDENTIFIER_LEN: ";        var_dump( $server->MAX_IDENTIFIER_LEN );
    echo "MAX_INDEX_SIZE: ";            var_dump( $server->MAX_INDEX_SIZE );
    echo "MAX_PROC_NAME_LEN: ";         var_dump( $server->MAX_PROC_NAME_LEN );
    echo "MAX_SCHEMA_NAME_LEN: ";       var_dump( $server->MAX_SCHEMA_NAME_LEN );
    echo "MAX_STATEMENT_LEN: ";         var_dump( $server->MAX_STATEMENT_LEN );
    echo "MAX_TABLE_NAME_LEN: ";        var_dump( $server->MAX_TABLE_NAME_LEN );
    echo "NON_NULLABLE_COLUMNS: ";      var_dump( $server->NON_NULLABLE_COLUMNS );

    db2_close($conn);
}
?>

Il precedente esempio visualizzerà:

DBMS_NAME: string(9) "DB2/LINUX"
DBMS_VER: string(10) "08.02.0000"
DB_CODEPAGE: int(1208)
DB_NAME: string(6) "SAMPLE"
INST_NAME: string(8) "db2inst1"
SPECIAL_CHARS: string(2) "@#"
KEYWORDS: int(179)
DFT_ISOLATION: string(2) "CS"
ISOLATION_OPTION: string(12) "UR CS RS RR "
SQL_CONFORMANCE: string(7) "FIPS127"
PROCEDURES: bool(true)
IDENTIFIER_QUOTE_CHAR: string(1) """
LIKE_ESCAPE_CLAUSE: bool(true)
MAX_COL_NAME_LEN: int(30)
MAX_ROW_SIZE: int(32677)
MAX_IDENTIFIER_LEN: int(18)
MAX_INDEX_SIZE: int(1024)
MAX_PROC_NAME_LEN: int(128)
MAX_SCHEMA_NAME_LEN: int(30)
MAX_STATEMENT_LEN: int(2097152)
MAX_TABLE_NAME_LEN: int(128)
NON_NULLABLE_COLUMNS: bool(true)

Vedere anche:

db2_client_info()

db2_special_columns

(PECL)

db2_special_columns --  Returns a result set listing the unique row identifier columns for a table

Descrizione

resource db2_special_columns ( resource connection, string qualifier, string schema, string table_name, int scope )

Returns a result set listing the unique row identifier columns for a table.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables.

table_name

The name of the table.

scope

Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:

Integer valueSQL constantDescription
0SQL_SCOPE_CURROWRow identifier is valid only while the cursor is positioned on the row.
1SQL_SCOPE_TRANSACTIONRow identifier is valid for the duration of the transaction.
2SQL_SCOPE_SESSIONRow identifier is valid for the duration of the connection.

Valori restituiti

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 nameDescription
SCOPE

Integer valueSQL constantDescription
0SQL_SCOPE_CURROWRow identifier is valid only while the cursor is positioned on the row.
1SQL_SCOPE_TRANSACTIONRow identifier is valid for the duration of the transaction.
2SQL_SCOPE_SESSIONRow identifier is valid for the duration of the connection.

COLUMN_NAMEName of the unique column.
DATA_TYPESQL data type for the column.
TYPE_NAMECharacter string representation of the SQL data type for the column.
COLUMN_SIZEAn 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_COLUMNAlways returns 1.

db2_statistics

(PECL)

db2_statistics --  Returns a result set listing the index and statistics for a table

Descrizione

resource db2_statistics ( resource connection, string qualifier, string schema, string table-name, bool unique )

Returns a result set listing the index and statistics for a table.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

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.

table_name

The name of the table.

unique

An integer value representing the type of index information to return.

0

Return only the information for unique indexes on the table.

1

Return the information for all indexes on the table.

Valori restituiti

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 nameDescription
TABLE_CATThe catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema that contains the table.
TABLE_NAMEName 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:

Return valueParameter type
0 (SQL_FALSE)The index allows duplicate values.
1 (SQL_TRUE)The index values must be unique.
NULLThis row is statistics information for the table itself.

INDEX_QUALIFIERA string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAMEA string representing the name of the index.
TYPE

An integer value representing the type of information contained in this row of the result set:

Return valueParameter type
0 (SQL_TABLE_STAT)The row contains statistics about the table itself.
1 (SQL_INDEX_CLUSTERED)The row contains information about a clustered index.
2 (SQL_INDEX_HASH)The row contains information about a hashed index.
3 (SQL_INDEX_OTHER)The row contains information about a type of index that is neither clustered nor hashed.

ORDINAL_POSITIONThe 1-indexed position of the column in the index. NULL if the row contains statistics information about the table itself.
COLUMN_NAMEThe 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_CONDITIONAlways returns NULL.

db2_stmt_error

(PECL)

db2_stmt_error --  Returns a string containing the SQLSTATE returned by an SQL statement

Descrizione

string db2_stmt_error ( [resource stmt] )

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.

Elenco dei parametri

stmt

A valid statement resource.

Valori restituiti

Returns a string containing an SQLSTATE value.

db2_stmt_errormsg

(PECL)

db2_stmt_errormsg --  Returns a string containing the last SQL statement error message

Descrizione

string db2_stmt_errormsg ( [resource stmt] )

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

Elenco dei parametri

stmt

A valid statement resource.

Valori restituiti

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

db2_table_privileges

(PECL)

db2_table_privileges --  Returns a result set listing the tables and associated privileges in a database

Descrizione

resource db2_table_privileges ( resource connection [, string qualifier [, string schema [, string table_name]]] )

Returns a result set listing the tables and associated privileges in a database.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table_name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

Valori restituiti

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 nameDescription
TABLE_CATThe catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema that contains the table.
TABLE_NAMEName of the table.
GRANTORAuthorization ID of the user who granted the privilege.
GRANTEEAuthorization 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_tables

(PECL)

db2_tables --  Returns a result set listing the tables and associated metadata in a database

Descrizione

resource db2_tables ( resource connection [, string qualifier [, string schema [, string table-name [, string table-type]]]] )

Returns a result set listing the tables and associated metadata in a database.

Elenco dei parametri

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table-name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

table-type

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.

Valori restituiti

Returns a statement resource with a result set containing rows describing the tables that match the specified parameters. The rows are composed of the following columns:

Column nameDescription
TABLE_CATThe catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEMName of the schema that contains the table.
TABLE_NAMEName of the table.
TABLE_TYPETable type identifier for the table.
REMARKSDescription of the table.

LII. ICAP Functions [deprecated]

Introduzione

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.


Requisiti

The icap library has to be installed, which is not longer supported and available.


Installazione

To get these functions to work, you have to compile PHP with --with-icap.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
icap_close -- Close an ICAP stream
icap_create_calendar --  Create a new calendar
icap_delete_calendar --  Delete a calendar
icap_delete_event -- Delete an event from an ICAP calendar
icap_fetch_event -- Fetches an event from the calendar stream/
icap_list_alarms --  Return a list of events that has an alarm triggered at the given datetime
icap_list_events --  Return a list of events between two given datetimes
icap_open -- Opens up an ICAP connection
icap_rename_calendar --  Rename a calendar
icap_reopen --  Reopen ICAP stream to new calendar
icap_snooze -- Snooze an alarm
icap_store_event -- Store an event into an ICAP calendar

icap_close

(no version information, might be only in CVS)

icap_close -- Close an ICAP stream

Description

int icap_close ( int icap_stream [, int flags] )

Closes the given icap stream.

icap_create_calendar

(PHP 4 <= 4.2.3)

icap_create_calendar --  Create a new calendar

Description

string icap_create_calendar ( int stream_id, string calendar )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

icap_delete_calendar

(PHP 4 <= 4.2.3)

icap_delete_calendar --  Delete a calendar

Description

string icap_delete_calendar ( int stream_id, string calendar )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

icap_delete_event

(PHP 4 <= 4.2.3)

icap_delete_event -- Delete an event from an ICAP calendar

Description

string icap_delete_event ( int stream_id, int uid )

icap_delete_event() deletes the calendar event specified by the uid.

Returns TRUE.

icap_fetch_event

(PHP 4 <= 4.2.3)

icap_fetch_event -- Fetches an event from the calendar stream/

Description

int icap_fetch_event ( int stream_id, int event_id [, int options] )

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.

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

icap_list_alarms

(PHP 4 <= 4.2.3)

icap_list_alarms --  Return a list of events that has an alarm triggered at the given datetime

Description

int icap_list_alarms ( int stream_id, array date, array time )

Returns 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

icap_list_events

(PHP 4 <= 4.2.3)

icap_list_events --  Return a list of events between two given datetimes

Description

array icap_list_events ( int stream_id, int begin_date [, int end_date] )

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

icap_open

(PHP 4 <= 4.2.3)

icap_open -- Opens up an ICAP connection

Description

resource icap_open ( string calendar, string username, string password, string options )

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.

icap_rename_calendar

(PHP 4 <= 4.2.3)

icap_rename_calendar --  Rename a calendar

Description

string icap_rename_calendar ( int stream_id, string old_name, string new_name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

icap_reopen

(PHP 4 <= 4.2.3)

icap_reopen --  Reopen ICAP stream to new calendar

Description

int icap_reopen ( int stream_id, string calendar [, int options] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

icap_snooze

(PHP 4 <= 4.2.3)

icap_snooze -- Snooze an alarm

Description

string icap_snooze ( int stream_id, int uid )

icap_snooze() turns on an alarm for a calendar event specified by the uid.

Returns TRUE.

icap_store_event

(PHP 4 <= 4.2.3)

icap_store_event -- Store an event into an ICAP calendar

Description

string icap_store_event ( int stream_id, object event )

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.

LIII. Iconv

Introduzione

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.


Requisiti

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


Installazione

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


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione di Iconv

NomeDefaultModificabile
iconv.input_encodingICONV_INPUT_ENCODINGPHP_INI_ALL
iconv.output_encodingICONV_OUTPUT_ENCODINGPHP_INI_ALL
iconv.internal_encodingICONV_INTERNAL_ENCODINGPHP_INI_ALL
Per maggiori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Dalla versione 4.3.0 di PHP è possibile identificare da untime quale implementazione di iconv è adottata da questo modulo.

Tabella 2. Costanti iconv

NomeTipoDescrizione
ICONV_IMPLstringIl nome dell'implementazione
ICONV_VERSIONstringVersione 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

NomeTipoDescrizione
ICONV_MIME_DECODE_STRICTintegerMaschera di bit utilizzata da iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERRORintegerMaschera di bit utilizzata per iconv_mime_decode()


Vedere anche:

Vedere anche GNU Recode.

Sommario
iconv_get_encoding -- Visualizza l'attuale impostazione per la conversione dei caratteri codificati
iconv_mime_decode_headers --  Decodes multiple MIME header fields at once
iconv_mime_decode --  Decodes a MIME header field
iconv_mime_encode --  Composes a MIME header field
iconv_set_encoding -- Setta l'attuale impostazione per la conversione dei caratteri codificati
iconv_strlen --  Returns the character count of string
iconv_strpos --  Finds position of first occurrence of a needle within a haystack
iconv_strrpos --  Finds the last occurrence of a needle within the specified range of haystack
iconv_substr --  Cut out part of a string
iconv -- Converte una stringa nel set di caratteri richiesto
ob_iconv_handler -- Converte caratteri codificati come un output buffer handler

iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_get_encoding -- Visualizza l'attuale impostazione per la conversione dei caratteri codificati

Descrizione

array iconv_get_encoding ( [string type] )

Restituisce l'attuale impostazione di ob_iconv_handler() come array o FALSE in caso di insuccesso.

Vedere anche: iconv_set_encoding() e ob_iconv_handler().

iconv_mime_decode_headers

(PHP 5)

iconv_mime_decode_headers --  Decodes multiple MIME header fields at once

Description

array iconv_mime_decode_headers ( string encoded_headers [, int mode [, string charset]] )

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

ValueConstantDescription
1ICONV_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.
2ICONV_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

<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>

Il precedente esempio visualizzerà:

Array
(
    [Subject] => Prüfung Prüfung
    [To] => example@example.com
    [Date] => Thu, 1 Jan 1970 00:00:00 +0000
    [Message-Id] => <example@example.com>
    [Received] => Array
        (
            [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
            [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
        )

)

See also iconv_mime_decode(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().

iconv_mime_decode

(PHP 5)

iconv_mime_decode --  Decodes a MIME header field

Description

string iconv_mime_decode ( string encoded_header [, int mode [, string charset]] )

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

ValueConstantDescription
1ICONV_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.
2ICONV_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.

Esempio 1. iconv_mime_decode() example

<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

See also iconv_mime_decode_headers(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().

iconv_mime_encode

(PHP 5)

iconv_mime_encode --  Composes a MIME header field

Description

string iconv_mime_encode ( string field_name, string field_value [, array preferences] )

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
In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

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

ItemTypeDescriptionDefault valueExample
schemeboolean 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. BB
input-charsetstring 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-charsetstring 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-lengthinteger 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. 76996
line-break-charsstring 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:

<?php
$preferences = array(
    "input-charset" => "ISO-8859-1",
    "output-charset" => "UTF-8",
    "line-length" => 76,
    "line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung_Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>

See also imap_binary(), mb_encode_mimeheader() and imap_8bit().

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_set_encoding -- Setta l'attuale impostazione per la conversione dei caratteri codificati

Descrizione

array iconv_set_encoding ( string type, string charset )

Cambia il valore di type in charset e restituisc TRUE in caso di successo o FALSE in caso di fallimento.

Esempio 1. Esempio di iconv_set_encoding():

iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");

Vedere anche: iconv_get_encoding() e ob_iconv_handler().

iconv_strlen

(PHP 5)

iconv_strlen --  Returns the character count of string

Description

int iconv_strlen ( string str [, string charset] )

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

iconv_strpos

(PHP 5)

iconv_strpos --  Finds position of first occurrence of a needle within a haystack

Description

int iconv_strpos ( string haystack, string needle [, int offset [, string charset]] )

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

iconv_strrpos

(PHP 5)

iconv_strrpos --  Finds the last occurrence of a needle within the specified range of haystack

Description

int iconv_strrpos ( string haystack, string needle [, string charset] )

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

iconv_substr

(PHP 5)

iconv_substr --  Cut out part of a string

Description

string iconv_substr ( string str, int offset [, int length [, string charset]] )

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

iconv

(PHP 4 >= 4.0.5, PHP 5)

iconv -- Converte una stringa nel set di caratteri richiesto

Descrizione

string iconv ( string in_charset, string out_charset, string str )

Converte la stringa codificata nel parametro stringa in in_charset nella stringa codificata in out_charset. Restituisce la stringa convertita o FALSE, se fallisce.

Esempio 1. Esempio di iconv():

echo iconv("ISO-8859-1","UTF-8","This is test.");

ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5)

ob_iconv_handler -- Converte caratteri codificati come un output buffer handler

Descrizione

array ob_iconv_handler ( string contents, int status )

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

Esempio 1. Esempio di ob_iconv_handler():

ob_start("ob_iconv_handler"); // start output buffering

Vedere anche: iconv_get_encoding() e iconv_set_encoding().

LIV. ID3 Functions

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Predefined Constants

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

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

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

ID3_V2_1 is used if you are working with ID3 V2.1 tags.

ID3_V2_2 (integer)

ID3_V2_2 is used if you are working with ID3 V2.2 tags.

ID3_V2_3 (integer)

ID3_V2_3 is used if you are working with ID3 V2.3 tags.

ID3_V2_4 (integer)

ID3_V2_4 is used if you are working with ID3 V2.4 tags.

ID3_BEST (integer)

ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.

Sommario
id3_get_frame_long_name -- Get the long name of an ID3v2 frame
id3_get_frame_short_name -- Get the short name of an ID3v2 frame
id3_get_genre_id -- Get the id for a genre
id3_get_genre_list -- Get all possible genre values
id3_get_genre_name -- Get the name for a genre id
id3_get_tag -- Get all information stored in an ID3 tag
id3_get_version -- Get version of an ID3 tag
id3_remove_tag -- Remove an existing ID3 tag
id3_set_tag -- Update information stored in an ID3 tag

id3_get_frame_long_name

(PECL)

id3_get_frame_long_name -- Get the long name of an ID3v2 frame

Description

string id3_get_frame_long_name ( string frameId )

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

Esempio 1. id3_get_frame_long_name() example

<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>

This will output:

Original lyricist(s)/text writer(s)

See also id3_get_frame_short_name().

id3_get_frame_short_name

(PECL)

id3_get_frame_short_name -- Get the short name of an ID3v2 frame

Description

string id3_get_frame_short_name ( string frameId )

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

Esempio 1. id3_get_frame_short_name() example

<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>

This will output:

originalLyricist

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

(PECL)

id3_get_genre_id -- Get the id for a genre

Description

int id3_get_genre_id ( string genre )

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.

Esempio 1. id3_get_genre_id() example

<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>

This will output:

20

See also id3_get_genre_list() and id3_get_genre_name().

id3_get_genre_list

(PECL)

id3_get_genre_list -- Get all possible genre values

Description

array id3_get_genre_list ( void )

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

<?php
$genres = id3_get_genre_list();
print_r($genres);
?>

This will output:

Array
(
    [0] => Blues
    [1] => Classic Rock
    [2] => Country
    [3] => Dance
    [4] => Disco
    [5] => Funk
    [6] => Grunge
    [7] => Hip-Hop
    [8] => Jazz
    [9] => Metal
    [10] => New Age
    [11] => Oldies
    [12] => Other
    [13] => Pop
    [14] => R&B
    [15] => Rap
    [16] => Reggae
    [17] => Rock
    [18] => Techno
    [19] => Industrial
    [20] => Alternative
    [21] => Ska
    [22] => Death Metal
    [23] => Pranks
    [24] => Soundtrack
    [25] => Euro-Techno
    [26] => Ambient
    [27] => Trip-Hop
    [28] => Vocal
    [29] => Jazz+Funk
    [30] => Fusion
    [31] => Trance
    [32] => Classical
    [33] => Instrumental
    [34] => Acid
    [35] => House
    [36] => Game
    [37] => Sound Clip
    [38] => Gospel
    [39] => Noise
    [40] => Alternative Rock
    [41] => Bass
    [42] => Soul
    [43] => Punk
    [44] => Space
    [45] => Meditative
    [46] => Instrumental Pop
    [47] => Instrumental Rock
    [48] => Ethnic
    [49] => Gothic
    [50] => Darkwave
    [51] => Techno-Industrial
    [52] => Electronic
    [53] => Pop-Folk
    [54] => Eurodance
    [55] => Dream
    [56] => Southern Rock
    [57] => Comedy
    [58] => Cult
    [59] => Gangsta
    [60] => Top 40
    [61] => Christian Rap
    [62] => Pop/Funk
    [63] => Jungle
    [64] => Native US
    [65] => Cabaret
    [66] => New Wave
    [67] => Psychadelic
    [68] => Rave
    [69] => Showtunes
    [70] => Trailer
    [71] => Lo-Fi
    [72] => Tribal
    [73] => Acid Punk
    [74] => Acid Jazz
    [75] => Polka
    [76] => Retro
    [77] => Musical
    [78] => Rock & Roll
    [79] => Hard Rock
    [80] => Folk
    [81] => Folk-Rock
    [82] => National Folk
    [83] => Swing
    [84] => Fast Fusion
    [85] => Bebob
    [86] => Latin
    [87] => Revival
    [88] => Celtic
    [89] => Bluegrass
    [90] => Avantgarde
    [91] => Gothic Rock
    [92] => Progressive Rock
    [93] => Psychedelic Rock
    [94] => Symphonic Rock
    [95] => Slow Rock
    [96] => Big Band
    [97] => Chorus
    [98] => Easy Listening
    [99] => Acoustic
    [100] => Humour
    [101] => Speech
    [102] => Chanson
    [103] => Opera
    [104] => Chamber Music
    [105] => Sonata
    [106] => Symphony
    [107] => Booty Bass
    [108] => Primus
    [109] => Porn Groove
    [110] => Satire
    [111] => Slow Jam
    [112] => Club
    [113] => Tango
    [114] => Samba
    [115] => Folklore
    [116] => Ballad
    [117] => Power Ballad
    [118] => Rhytmic Soul
    [119] => Freestyle
    [120] => Duet
    [121] => Punk Rock
    [122] => Drum Solo
    [123] => Acapella
    [124] => Euro-House
    [125] => Dance Hall
    [126] => Goa
    [127] => Drum & Bass
    [128] => Club-House
    [129] => Hardcore
    [130] => Terror
    [131] => Indie
    [132] => BritPop
    [133] => Negerpunk
    [134] => Polsk Punk
    [135] => Beat
    [136] => Christian Gangsta
    [137] => Heavy Metal
    [138] => Black Metal
    [139] => Crossover
    [140] => Contemporary C
    [141] => Christian Rock
    [142] => Merengue
    [143] => Salsa
    [144] => Thrash Metal
    [145] => Anime
    [146] => JPop
    [147] => SynthPop
)

See also id3_get_genre_name() and id3_get_genre_id().

id3_get_genre_name

(PECL)

id3_get_genre_name -- Get the name for a genre id

Description

string id3_get_genre_name ( int 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.

Esempio 1. id3_get_genre_name() example

<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>

This will output:

Alternative

See also id3_get_genre_list() and id3_get_genre_id().

id3_get_tag

(PECL)

id3_get_tag -- Get all information stored in an ID3 tag

Description

array id3_get_tag ( string filename [, int version] )

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.

Esempio 1. id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>

This will output something like:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

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

<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>

This will output something like:

Array
(
    [copyright] => Dirty Mac
    [originalArtist] => Dirty Mac
    [composer] => Marcus Götze
    [artist] => Dirty Mac
    [title] => Little Big Man
    [album] => Demo-Tape
    [track] => 5/12
    [genre] => (17)Rock
    [year] => 2001
)

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

(PECL)

id3_get_version -- Get version of an ID3 tag

Description

int id3_get_version ( string filename )

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

<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
    echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
    echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
    echo "Contains a 2.x tag\n";
}
?>

This will output something like:

Contains a 1.x tag
Contains a 1.1 tag

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

(PECL)

id3_remove_tag -- Remove an existing ID3 tag

Description

bool id3_remove_tag ( string filename [, int version] )

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.

Esempio 1. id3_remove_tag() example

<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
    echo "Tag succesfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag succesfully removed

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

(PECL)

id3_set_tag -- Update information stored in an ID3 tag

Description

bool id3_set_tag ( string filename, array tag [, int 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

<?php
$data = array(
              "title" => "Re:Start",
              "artist" => "Re:\Legion",
              "comment" => "A nice track"
             );
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
    echo "Tag succesfully updated\n";
}
?>

If the file is writable, this will output:

Tag succesfully updated

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

keypossible valueavailable in version
titlestring with maximum of 30 charactersv1.0, v1.1
artiststring with maximum of 30 charactersv1.0, v1.1
albumstring with maximum of 30 charactersv1.0, v1.1
year4 digitsv1.0, v1.1
genreinteger value between 0 and 147v1.0, v1.1
commentstring with maximum of 30 characters (28 in v1.1)v1.0, v1.1
trackinteger between 0 and 255v1.1

See also id3_get_tag(), id3_remove_tag() and id3_get_version().

LV. Funzioni di Amministrazione IIS

Introduzione

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


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
iis_add_server -- Crea un nuovo web server virtuale
iis_get_dir_security -- Riceve informazioni sulla sicurezza della cartella
iis_get_script_map -- Riceve informazioni sul mapping dello script sulla cartella virtuale per una specifica estensioneo
iis_get_server_by_comment -- Restituisce il numero d'istanza associato con il commento
iis_get_server_by_path -- Restituisce il numero di istanza associato alla Path
iis_get_server_rights -- Riceve informaizoni sui diritti del server
iis_get_service_state -- Avvia il servizio definito da service_id
iis_remove_server -- Rimuove il web server virtuale indicato da Server_instance
iis_set_app_settings -- Crea application scope per una cartella virtuale
iis_set_dir_security -- Imposta la sicurezza nella cartella
iis_set_script_map -- Imposta il mapping dello script sulla cartella virtuale
iis_set_server_rights -- Imposta i diritti del server
iis_start_server -- Avvia il web server virtuale
iis_start_service -- Avvia il servizio definito da service_id
iis_stop_server -- Ferma il web server virtuale
iis_stop_service -- Ferma il servizio definito da service_id

iis_add_server

(PECL)

iis_add_server -- Crea un nuovo web server virtuale

Descrizione

int iis_add_server ( string path, string comment, string server_ip, int port, string host_name, int rights, int start_server )

iis_get_dir_security

(PECL)

iis_get_dir_security -- Riceve informazioni sulla sicurezza della cartella

Descrizione

int iis_get_dir_security ( int server_instance, string virtual_path )

iis_get_script_map

(PECL)

iis_get_script_map -- Riceve informazioni sul mapping dello script sulla cartella virtuale per una specifica estensioneo

Descrizione

int iis_get_script_map ( int server_instance, string virtual_path, string script_extension )

iis_get_server_by_comment

(PECL)

iis_get_server_by_comment -- Restituisce il numero d'istanza associato con il commento

Descrizione

int iis_get_server_by_comment ( string comment )

iis_get_server_by_path

(PECL)

iis_get_server_by_path -- Restituisce il numero di istanza associato alla Path

Descrizione

int iis_get_server_by_path ( string path )

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.

iis_get_server_rights

(PECL)

iis_get_server_rights -- Riceve informaizoni sui diritti del server

Descrizione

int iis_get_server_rights ( int server_instance, string virtual_path )

iis_get_service_state

(PECL)

iis_get_service_state -- Avvia il servizio definito da service_id

Descrizione

int iis_get_service_state ( string service_id )

iis_remove_server

(PECL)

iis_remove_server -- Rimuove il web server virtuale indicato da Server_instance

Descrizione

int iis_remove_server ( int server_instance )

iis_set_app_settings

(PECL)

iis_set_app_settings -- Crea application scope per una cartella virtuale

Descrizione

int iis_set_app_settings ( int server_instance, string virtual_path, string application_scope )

iis_set_dir_security

(PECL)

iis_set_dir_security -- Imposta la sicurezza nella cartella

Descrizione

int iis_set_dir_security ( int server_instance, string virtual_path, int directory_flags )

iis_set_script_map

(PECL)

iis_set_script_map -- Imposta il mapping dello script sulla cartella virtuale

Descrizione

int iis_set_script_map ( int server_instance, string virtual_path, string script_extension, string engine_path, int allow_scripting )

iis_set_server_rights

(PECL)

iis_set_server_rights -- Imposta i diritti del server

Descrizione

int iis_set_server_rights ( int server_instance, string virtual_path, int directory_flags )

iis_start_server

(PECL)

iis_start_server -- Avvia il web server virtuale

Descrizione

int iis_start_server ( int server_instance )

iis_start_service

(PECL)

iis_start_service -- Avvia il servizio definito da service_id

Descrizione

int iis_start_service ( string service_id )

iis_stop_server

(PECL)

iis_stop_server -- Ferma il web server virtuale

Descrizione

int iis_stop_server ( int server_instance )

iis_stop_service

(PECL)

iis_stop_service -- Ferma il servizio definito da service_id

Descrizione

int iis_stop_service ( string service_id )

LVI. Funzioni per le immagini

Introduzione

In PHP puoi usare delle funzioni specifiche per sapere la dimensione di un'immagine JPEG, GIF, PNG, SWF, TIFF e JPEG2000.


Requisiti

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.


Installazione

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


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

IMG_GIF (integer)

IMG_JPG (integer)

IMG_JPEG (integer)

IMG_PNG (integer)

IMG_WBMP (integer)

IMG_XPM (integer)

IMG_COLOR_TILED (integer)

IMG_COLOR_STYLED (integer)

IMG_COLOR_BRUSHED (integer)

IMG_COLOR_STYLEDBRUSHED (integer)

IMG_COLOR_TRANSPARENT (integer)

IMG_ARC_ROUNDED (integer)

IMG_ARC_PIE (integer)

IMG_ARC_CHORD (integer)

IMG_ARC_NOFILL (integer)

IMG_ARC_EDGED (integer)

IMAGETYPE_GIF (integer)

IMAGETYPE_JPEG (integer)

IMAGETYPE_PNG (integer)

IMAGETYPE_SWF (integer)

IMAGETYPE_PSD (integer)

IMAGETYPE_BMP (integer)

IMAGETYPE_WBMP (integer)

IMAGETYPE_XBM (integer)

IMAGETYPE_TIFF_II (integer)

IMAGETYPE_TIFF_MM (integer)

IMAGETYPE_IFF (integer)

IMAGETYPE_JB2 (integer)

IMAGETYPE_JPC (integer)

IMAGETYPE_JP2 (integer)

IMAGETYPE_JPX (integer)

IMAGETYPE_SWC (integer)

Sommario
gd_info -- Retrieve information about the currently installed GD library
getimagesize -- Get the size of an image
image_type_to_extension --  Get file extension for image type
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp -- Rende disponibile l'immagine per il browser o la salva in un file
imagealphablending -- Set the blending mode for an image
imageantialias --  Should antialias functions be used or not
imagearc -- Draw a partial ellipse
imagechar -- Draw a character horizontally
imagecharup -- Draw a character vertically
imagecolorallocate -- Allocate a color for an image
imagecolorallocatealpha -- Allocate a color for an image
imagecolorat -- Get the index of the color of a pixel
imagecolorclosest -- Get the index of the closest color to the specified color
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha
imagecolorclosesthwb --  Get the index of the color which has the hue, white and blackness nearest to the given color
imagecolordeallocate -- De-allocate a color for an image
imagecolorexact -- Get the index of the specified color
imagecolorexactalpha -- Get the index of the specified color + alpha
imagecolormatch --  Makes the colors of the palette version of an image more closely match the true color version
imagecolorresolve --  Get the index of the specified color or its closest possible alternative
imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative
imagecolorset -- Set the color for the specified palette index
imagecolorsforindex -- Get the colors for an index
imagecolorstotal -- Find out the number of colors in an image's palette
imagecolortransparent -- Define a color as transparent
imageconvolution --  Apply a 3x3 convolution matrix, using coefficient div and offset
imagecopy -- Copy part of an image
imagecopymerge -- Copy and merge part of an image
imagecopymergegray -- Copy and merge part of an image with gray scale
imagecopyresampled -- Copy and resize part of an image with resampling
imagecopyresized -- Copy and resize part of an image
imagecreate -- Create a new palette based image
imagecreatefromgd2 -- Create a new image from GD2 file or URL
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
imagecreatefromgd -- Create a new image from GD file or URL
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL
imagecreatetruecolor -- Create a new true color image
imagedashedline -- Draw a dashed line
imagedestroy -- Destroy an image
imageellipse -- Draw an ellipse
imagefill -- Flood fill
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
imagefilledpolygon -- Draw a filled polygon
imagefilledrectangle -- Draw a filled rectangle
imagefilltoborder -- Flood fill to specific color
imagefilter --  Applies a filter to an image
imagefontheight -- Get font height
imagefontwidth -- Get font width
imageftbbox -- Give the bounding box of a text using fonts via freetype2
imagefttext -- Write text to the image using fonts using FreeType 2
imagegammacorrect -- Apply a gamma correction to a GD image
imagegd2 -- Output GD2 image to browser or file
imagegd -- Output GD image to browser or file
imagegif -- Output image to browser or file
imageinterlace -- Enable or disable interlace
imageistruecolor -- Finds whether an image is a truecolor image
imagejpeg -- Output image to browser or file
imagelayereffect --  Set the alpha blending flag to use the bundled libgd layering effects
imageline -- Draw a line
imageloadfont -- Load a new font
imagepalettecopy -- Copy the palette from one image to another
imagepng -- Output a PNG image to either the browser or a file
imagepolygon -- Draw a polygon
imagepsbbox --  Give the bounding box of a text rectangle using PostScript Type1 fonts
imagepscopyfont --  Make a copy of an already loaded font for further modification
imagepsencodefont -- Change the character encoding vector of a font
imagepsextendfont -- Extend or condense a font
imagepsfreefont -- Free memory used by a PostScript Type 1 font
imagepsloadfont -- Load a PostScript Type 1 font from file
imagepsslantfont -- Slant a font
imagepstext -- To draw a text string over an image using PostScript Type1 fonts
imagerectangle -- Draw a rectangle
imagerotate -- Rotate an image with a given angle
imagesavealpha --  Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
imagesetbrush -- Set the brush image for line drawing
imagesetpixel -- Set a single pixel
imagesetstyle -- Set the style for line drawing
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling
imagestring -- Draw a string horizontally
imagestringup -- Draw a string vertically
imagesx -- Get image width
imagesy -- Get image height
imagetruecolortopalette -- Convert a true color image to a palette image
imagettfbbox -- Give the bounding box of a text using TrueType fonts
imagettftext -- Write text to the image using TrueType fonts
imagetypes -- Return the image types supported by this PHP build
imagewbmp -- Output image to browser or file
imagexbm --  Output XBM image to browser or file
iptcembed -- Embed binary IPTC data into a JPEG image
iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.
jpeg2wbmp -- Convert JPEG image file to WBMP image file
png2wbmp -- Convert PNG image file to WBMP image file

gd_info

(PHP 4 >= 4.3.0, PHP 5)

gd_info -- Retrieve information about the currently installed GD library

Description

array gd_info ( void )

Returns an associative array describing the version and capabilities of the installed GD library.

Tabella 1. Elements of array returned by gd_info()

AttributeMeaning
GD Versionstring value describing the installed libgd version.
Freetype Supportboolean value. TRUE if Freetype Support is installed.
Freetype Linkagestring 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 Supportboolean value. TRUE if T1Lib support is included.
GIF Read Supportboolean value. TRUE if support for reading GIF images is included.
GIF Create Supportboolean value. TRUE if support for creating GIF images is included.
JPG Supportboolean value. TRUE if JPG support is included.
PNG Supportboolean value. TRUE if PNG support is included.
WBMP Supportboolean value. TRUE if WBMP support is included.
XBM Supportboolean value. TRUE if XBM support is included.

Esempio 1. Using gd_info()

<?php
var_dump(gd_info());
?>

The typical output is :

array(9) {
  ["GD Version"]=>
  string(24) "bundled (2.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["T1Lib Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

See also imagepng(), imagejpeg(), imagegif(), imagewbmp(), and imagetypes().

getimagesize

(PHP 3, PHP 4, PHP 5)

getimagesize -- Get the size of an image

Description

array getimagesize ( string filename [, array &imageinfo] )

The getimagesize() function will determine the size of any GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP, 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.

Esempio 1. getimagesize (file)

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

URL support was added in PHP 4.0.5

Esempio 2. getimagesize (URL)

<?php 
$size = getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

With JPG images, two extra indexes are returned: channels and bits. channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color.

Beginning with PHP 4.3.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:

Esempio 3. getimagesize() and MIME types

<?php
$size = getimagesize($filename);
$fp=fopen($filename, "rb");
if ($size && $fp) {
  header("Content-type: {$size['mime']}");
  fpassthru($fp);
  exit;
} else {
  // error
}
?>

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.

Esempio 4. getimagesize() returning IPTC

<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]);
    var_dump($iptc);
}
?>

See also image_type_to_mime_type(), exif_imagetype(), exif_read_data(), and exif_thumbnail().

image_type_to_extension

(no version information, might be only in CVS)

image_type_to_extension --  Get file extension for image type

Description

string image_type_to_extension ( int imagetype [, bool include_dot] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

image_type_to_mime_type

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

Description

string image_type_to_mime_type ( int imagetype )

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Esempio 1. image_type_to_mime_type (file)

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

The returned values are as follows

Tabella 1. Returned values Constants

imagetypeReturned value
IMAGETYPE_GIFimage/gif
IMAGETYPE_JPEGimage/jpeg
IMAGETYPE_PNGimage/png
IMAGETYPE_SWFapplication/x-shockwave-flash
IMAGETYPE_PSDimage/psd
IMAGETYPE_BMPimage/bmp
IMAGETYPE_TIFF_II (intel byte order)image/tiff
IMAGETYPE_TIFF_MM (motorola byte order) image/tiff
IMAGETYPE_JPCapplication/octet-stream
IMAGETYPE_JP2image/jp2
IMAGETYPE_JPXapplication/octet-stream
IMAGETYPE_JB2application/octet-stream
IMAGETYPE_SWCapplication/x-shockwave-flash
IMAGETYPE_IFFimage/iff
IMAGETYPE_WBMPimage/vnd.wap.wbmp
IMAGETYPE_XBMimage/xbm

Nota: This function does not require the GD image library.

See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().

image2wbmp

(PHP 4 >= 4.0.5, PHP 5)

image2wbmp -- Rende disponibile l'immagine per il browser o la salva in un file

Descrizione

int image2wbmp ( resource image [, string filename [, int threshold]] )

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

(PHP 4 >= 4.0.6, PHP 5)

imagealphablending -- Set the blending mode for an image

Description

bool imagealphablending ( resource image, bool blendmode )

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. If blendmode is TRUE, then blending mode is enabled, otherwise disabled. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: This function requires GD 2.0.1 or later.

imageantialias

(PHP 4 >= 4.3.2, PHP 5)

imageantialias --  Should antialias functions be used or not

Description

bool imageantialias ( resource im, bool on )

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

(PHP 3, PHP 4, PHP 5)

imagearc -- Draw a partial ellipse

Description

bool imagearc ( resource image, int cx, int cy, int w, int h, int s, int e, int color )

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

<?php

// create a 200*200 image
$img = imagecreatetruecolor(200, 200);

// allocate some colors
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
   
// draw a black circle 
imagearc($img, 100, 100, 150, 150, 0, 360, $black);

// output image in the browser
header("Content-type: image/png");
imagepng($img);
   
// free memory
imagedestroy($img);

?>

See also imageellipse(), imagefilledellipse(), and imagefilledarc().

imagechar

(PHP 3, PHP 4, PHP 5)

imagechar -- Draw a character horizontally

Description

bool imagechar ( resource image, int font, int x, int y, string c, int color )

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

<?php

$im = imagecreatetruecolor(100, 100);

$string = 'PHP';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "P" in the top left corner
imagechar($im, 1, 0, 0, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

See also imagecharup() and imageloadfont().

imagecharup

(PHP 3, PHP 4, PHP 5)

imagecharup -- Draw a character vertically

Description

bool imagecharup ( resource image, int font, int x, int y, string c, int color )

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

<?php

$im = imagecreatetruecolor(100, 100);

$string = 'Note that the first letter is a N';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "Z" on a white background
imagecharup($im, 3, 10, 10, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

See also imagechar() and imageloadfont().

imagecolorallocate

(PHP 3, PHP 4, PHP 5)

imagecolorallocate -- Allocate a color for an image

Description

int imagecolorallocate ( resource image, int red, int green, int blue )

imagecolorallocate() returns a color identifier representing the color composed of the given RGB components. The 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

(PHP 4 >= 4.3.2, PHP 5)

imagecolorallocatealpha -- Allocate a color for an image

Description

int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha )

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Returns FALSE if the allocation failed.

Esempio 1. Example of using imagecolorallocatealpha()

<?php
$size = 300;
$image=imagecreatetruecolor($size, $size);

// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);

$yellow_x = 100;
$yellow_y = 75;
$red_x    = 120;
$red_y    = 165; 
$blue_x   = 187;
$blue_y   = 125; 
$radius   = 150;

// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red    = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue   = imagecolorallocatealpha($image, 0, 0, 255, 75);

// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);   
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);

// don't forget to output a correct header!
header('Content-type: image/png');

// and finally, output the result
imagepng($image);
imagedestroy($image);
?>

Nota: This function requires GD 2.0.1 or later.

See also imagecolorallocate() and imagecolordeallocate().

imagecolorat

(PHP 3, PHP 4, PHP 5)

imagecolorat -- Get the index of the color of a pixel

Description

int imagecolorat ( resource image, int x, int y )

Returns the index of the color of the pixel at the specified location in the image specified by image.

If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:

Esempio 1. Access distinct RGB values

<?php
$im = ImageCreateFromPng("rockym.png");
$rgb = ImageColorAt($im, 100, 100);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
?>

See also imagecolorset() and imagecolorsforindex().

imagecolorclosest

(PHP 3, PHP 4, PHP 5)

imagecolorclosest -- Get the index of the closest color to the specified color

Description

int imagecolorclosest ( resource image, int red, int green, int blue )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

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

imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha

Description

int imagecolorclosestalpha ( resource image, int red, int green, int blue, int alpha )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

Nota: This function requires GD 2.0.1 or later.

See also imagecolorexactalpha().

imagecolorclosesthwb

(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

Description

int imagecolorclosesthwb ( resource image, int red, int green, int blue )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

imagecolordeallocate

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

imagecolordeallocate -- De-allocate a color for an image

Description

bool imagecolordeallocate ( resource image, int color )

The imagecolordeallocate() function de-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>

See also imagecolorallocate() and imagecolorallocatealpha().

imagecolorexact

(PHP 3, PHP 4, PHP 5)

imagecolorexact -- Get the index of the specified color

Description

int imagecolorexact ( resource image, int red, int green, int blue )

Returns the index of the specified color in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

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

imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorexactalpha -- Get the index of the specified color + alpha

Description

int imagecolorexactalpha ( resource image, int red, int green, int blue, int alpha )

Returns the index of the specified color+alpha in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

Nota: This function requires GD 2.0.1 or later.

See also imagecolorclosestalpha().

imagecolormatch

(PHP 4 >= 4.3.0, PHP 5)

imagecolormatch --  Makes the colors of the palette version of an image more closely match the true color version

Description

bool imagecolormatch ( resource image1, resource image2 )

Avvertimento

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

imagecolorresolve

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imagecolorresolve --  Get the index of the specified color or its closest possible alternative

Description

int imagecolorresolve ( resource image, int red, int green, int blue )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

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

imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative

Description

int imagecolorresolvealpha ( resource image, int red, int green, int blue, int alpha )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

Nota: This function requires GD 2.0.1 or later.

See also imagecolorclosestalpha().

imagecolorset

(PHP 3, PHP 4, PHP 5)

imagecolorset -- Set the color for the specified palette index

Description

void imagecolorset ( resource image, int index, int red, int green, int blue )

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.

See also imagecolorat().

imagecolorsforindex

(PHP 3, PHP 4, PHP 5)

imagecolorsforindex -- Get the colors for an index

Description

array imagecolorsforindex ( resource image, int index )

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

<?php

// open an image
$im = imagecreatefrompng('nexen.png');

// get a color
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// make it human readable
$color_tran = imagecolorsforindex($im, $color_index);

// what is it ?
echo '<pre>';
print_r($color_tran);
echo '</pre>';

?>

This example will output :

Array
(
    [red] => 226
    [green] => 222
    [blue] => 252
    [alpha] => 0
)

See also imagecolorat() and imagecolorexact().

imagecolorstotal

(PHP 3, PHP 4, PHP 5)

imagecolorstotal -- Find out the number of colors in an image's palette

Description

int imagecolorstotal ( resource image )

This returns the number of colors in the specified image's palette.

See also imagecolorat() and imagecolorsforindex().

imagecolortransparent

(PHP 3, PHP 4, PHP 5)

imagecolortransparent -- Define a color as transparent

Description

int imagecolortransparent ( resource image [, int color] )

imagecolortransparent() sets the transparent color in the image image to color. image is the image identifier returned by 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.

imageconvolution

(PHP 5 >= 5.1.0RC1)

imageconvolution --  Apply a 3x3 convolution matrix, using coefficient div and offset

Description

bool imageconvolution ( resource image, array matrix3x3, float div, float offset )

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

imagecopy

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

imagecopy -- Copy part of an image

Description

bool imagecopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5)

imagecopymerge -- Copy and merge part of an image

Description

bool imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Nota: This function was added in PHP 4.0.6

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5)

imagecopymergegray -- Copy and merge part of an image with gray scale

Description

bool imagecopymergegray ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

This function is identical to imagecopymerge() except that when merging it 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

(PHP 4 >= 4.0.6, PHP 5)

imagecopyresampled -- Copy and resize part of an image with resampling

Description

bool imagecopyresampled ( resource dst_image, resource src_image, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h )

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.

Esempi

Esempio 1. Simple example

This example will resample an image to half its original size.

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

Esempio 2. Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

<?php
// The file
$filename = 'test.jpg';

// Set a maximum height and width
$width = 200;
$height = 200;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

if ($width && ($width_orig < $height_orig)) {
    $width = ($height / $height_orig) * $width_orig;
} else {
    $height = ($width / $width_orig) * $height_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>

Vedere anche:

imagecopyresized()

imagecopyresized

(PHP 3, PHP 4, PHP 5)

imagecopyresized -- Copy and resize part of an image

Description

bool imagecopyresized ( resource dst_image, resource src_image, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h )

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

Esempi

Esempio 1. Resizing an image

This example will display the image at half size.

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?>

The image will be output at half size, though better quality could be obtained using imagecopyresampled().

Vedere anche:

imagecopyresampled()

imagecreate

(PHP 3, PHP 4, PHP 5)

imagecreate -- Create a new palette based image

Description

resource imagecreate ( int x_size, int y_size )

imagecreate() returns an image identifier representing a blank image of size x_size by y_size.

We recommend the use of imagecreatetruecolor().

Esempio 1. Creating a new GD image stream and outputting an image.

<?php
header("Content-type: image/png");
$im = @imagecreate(100, 50)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

See also imagedestroy() and imagecreatetruecolor().

imagecreatefromgd2

(PHP 4 >= 4.1.0, PHP 5)

imagecreatefromgd2 -- Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string filename )

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.

imagecreatefromgd2part

(PHP 4 >= 4.1.0, PHP 5)

imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL

Description

resource imagecreatefromgd2part ( string filename, int srcX, int srcY, int width, int height )

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.

imagecreatefromgd

(PHP 4 >= 4.1.0, PHP 5)

imagecreatefromgd -- Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string filename )

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

(PHP 3, PHP 4, PHP 5)

imagecreatefromgif -- Create a new image from file or URL

Description

resource imagecreatefromgif ( string filename )

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

imagecreatefromgif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:

Esempio 1. Example to handle an error during creation

<?php
function LoadGif ($imgname) 
{
    $im = @imagecreatefromgif ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = imagecreatetruecolor (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

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

(PHP 3 >= 3.0.16, PHP 4, PHP 5)

imagecreatefromjpeg -- Create a new image from file or URL

Description

resource imagecreatefromjpeg ( string filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:

Esempio 1. Example to handle an error during creation

<?php
function LoadJpeg($imgname) 
{
    $im = @imagecreatefromjpeg($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreatetruecolor(150, 30); /* Create a black image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

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

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imagecreatefrompng -- Create a new image from file or URL

Description

resource imagecreatefrompng ( string filename )

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

imagecreatefrompng() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:

Esempio 1. Example to handle an error during creation

<?php
function LoadPNG($imgname) 
{
    $im = @imagecreatefrompng($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreatetruecolor(150, 30); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

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.

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5)

imagecreatefromstring -- Create a new image from the image stream in the string

Descrizione

resource imagecreatefromstring ( string image )

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

Valori restituiti

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.

Esempi

Esempio 1. imagecreatefromstring() example

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
}
else {
    echo 'An error occured.';
}
?>

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromwbmp -- Create a new image from file or URL

Description

resource imagecreatefromwbmp ( string filename )

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:

Esempio 1. Example to handle an error during creation

<?php
function LoadWBMP($imgname) 
{
    $im = @imagecreatefromwbmp($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreatetruecolor (20, 20); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

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

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxbm -- Create a new image from file or URL

Description

resource imagecreatefromxbm ( string filename )

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

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

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxpm -- Create a new image from file or URL

Description

resource imagecreatefromxpm ( string filename )

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

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

(PHP 4 >= 4.0.6, PHP 5)

imagecreatetruecolor -- Create a new true color image

Description

resource imagecreatetruecolor ( int x_size, int y_size )

imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.

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.

<?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(50, 100)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

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

imagedashedline

(PHP 3, PHP 4, PHP 5)

imagedashedline -- Draw a dashed line

Description

bool imagedashedline ( resource image, int x1, int y1, int x2, int y2, int color )

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

imagedestroy

(PHP 3, PHP 4, PHP 5)

imagedestroy -- Destroy an image

Description

bool imagedestroy ( resource image )

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

(PHP 4 >= 4.0.6, PHP 5)

imageellipse -- Draw an ellipse

Description

bool imageellipse ( resource image, int cx, int cy, int w, int h, int color )

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

<?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the ellipse
imageellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

See also imagefilledellipse() and imagearc().

imagefill

(PHP 3, PHP 4, PHP 5)

imagefill -- Flood fill

Description

bool imagefill ( resource image, int x, int y, int color )

imagefill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color color in the image image.

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5)

imagefilledarc -- Draw a partial ellipse and fill it

Description

bool imagefilledarc ( resource image, int cx, int cy, int w, int h, int s, int e, int color, int style )

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:

  1. IMG_ARC_PIE

  2. IMG_ARC_CHORD

  3. IMG_ARC_NOFILL

  4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

Esempio 1. Creating a 3D looking pie

<?php

// create image
$image = imagecreatetruecolor(100, 100);

// allocate some solors
$white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred  = imagecolorallocate($image, 0x90, 0x00, 0x00);

// make the 3D effect
for ($i = 60; $i > 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
  imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
  imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);
}

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);


// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

Nota: This function requires GD 2.0.1 or later.

imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5)

imagefilledellipse -- Draw a filled ellipse

Description

bool imagefilledellipse ( resource image, int cx, int cy, int w, int h, int color )

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

<?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the white ellipse
imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

Nota: This function requires GD 2.0.1 or later.

See also imageellipse() and imagefilledarc().

imagefilledpolygon

(PHP 3, PHP 4, PHP 5)

imagefilledpolygon -- Draw a filled polygon

Description

bool imagefilledpolygon ( resource image, array points, int num_points, int color )

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

<?php
// set up array of points for polygon
$values = array(
            40,  50,  // Point 1 (x, y)
            20,  240, // Point 2 (x, y)
            60,  60,  // Point 3 (x, y)
            240, 20,  // Point 4 (x, y)
            50,  40,  // Point 5 (x, y)
            10,  10   // Point 6 (x, y)
            );

// create image
$image = imagecreatetruecolor(250, 250);

// some colors
$bg   = imagecolorallocate($image, 200, 200, 200);
$blue = imagecolorallocate($image, 0, 0, 255);

// draw a polygon
imagefilledpolygon($image, $values, 6, $blue);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

imagefilledrectangle

(PHP 3, PHP 4, PHP 5)

imagefilledrectangle -- Draw a filled rectangle

Description

bool imagefilledrectangle ( resource image, int x1, int y1, int x2, int y2, int color )

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

(PHP 3, PHP 4, PHP 5)

imagefilltoborder -- Flood fill to specific color

Description

bool imagefilltoborder ( resource image, int x, int y, int border, int color )

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

(PHP 5)

imagefilter --  Applies a filter to an image

Description

bool imagefilter ( resource src_im, int filtertype [, int arg1 [, int arg2 [, int arg3]]] )

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 1. imagefilter() grayscale example

<?php
$im = imagecreatefrompng('dave.png');
if ($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {
    echo 'Image converted to grayscale.';
    imagepng($im, 'dave.png');
} else {
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

Esempio 2. imagefilter() brightness example

<?php
$im = imagecreatefrompng('sean.png');
if ($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
    echo 'Image brightness changed.';
    imagepng($im, 'sean.png');
} else {
    echo 'Image brightness change failed.';
}

imagedestroy($im);
?>

Esempio 3. imagefilter() colorize example

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
    echo 'Image successfully shaded green.';
    imagepng($im, 'philip.png');
} else {
    echo 'Green shading failed.';
}

imagedestroy($im);
?>

imagefontheight

(PHP 3, PHP 4, PHP 5)

imagefontheight -- Get font height

Description

int imagefontheight ( int font )

Returns the pixel height of a character in the specified font.

See also imagefontwidth() and imageloadfont().

imagefontwidth

(PHP 3, PHP 4, PHP 5)

imagefontwidth -- Get font width

Description

int imagefontwidth ( int font )

Returns the pixel width of a character in font.

See also imagefontheight() and imageloadfont().

imageftbbox

(PHP 4 >= 4.1.0, PHP 5)

imageftbbox -- Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( float size, float angle, string font_file, string text [, array extrainfo] )

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.

imagefttext

(PHP 4 >= 4.1.0, PHP 5)

imagefttext -- Write text to the image using fonts using FreeType 2

Description

array imagefttext ( resource image, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo] )

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.

imagegammacorrect

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imagegammacorrect -- Apply a gamma correction to a GD image

Description

bool imagegammacorrect ( resource image, float inputgamma, float outputgamma )

The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.

imagegd2

(PHP 4 >= 4.1.0, PHP 5)

imagegd2 -- Output GD2 image to browser or file

Description

bool imagegd2 ( resource image [, string filename [, int chunk_size [, int type]]] )

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

(PHP 4 >= 4.1.0, PHP 5)

imagegd -- Output GD image to browser or file

Description

bool imagegd ( resource image [, string filename] )

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

(PHP 3, PHP 4, PHP 5)

imagegif -- Output image to browser or file

Description

bool imagegif ( resource image [, string filename] )

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:

<?php
if (imagetypes() & IMG_GIF) {
    header ("Content-type: image/gif");
    imagegif ($im);
} elseif (imagetypes() & IMG_JPG) {
    /* ... etc. */
}
?>

See also imagepng(), imagewbmp(), imagejpeg() and imagetypes().

imageinterlace

(PHP 3, PHP 4, PHP 5)

imageinterlace -- Enable or disable interlace

Description

int imageinterlace ( resource image [, int interlace] )

imageinterlace() turns the interlace bit on or off. If interlace is 1 the image will be interlaced, and if interlace is 0 the interlace bit is turned off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

This function returns whether the interlace bit is set for the image.

imageistruecolor

(PHP 4 >= 4.3.2, PHP 5)

imageistruecolor -- Finds whether an image is a truecolor image

Description

bool imageistruecolor ( resource 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

(PHP 3 >= 3.0.16, PHP 4, PHP 5)

imagejpeg -- Output image to browser or file

Description

bool imagejpeg ( resource image [, string filename [, int quality]] )

imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the 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().

imagelayereffect

(PHP 4 >= 4.3.0, PHP 5)

imagelayereffect --  Set the alpha blending flag to use the bundled libgd layering effects

Description

bool imagelayereffect ( resource image, int effect )

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.

Nota: This function requires GD 2.0.1 or later.

imageline

(PHP 3, PHP 4, PHP 5)

imageline -- Draw a line

Description

bool imageline ( resource image, int x1, int y1, int x2, int y2, int color )

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

<?php

function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1) 
{
    /* this way it works well only for orthogonal lines
    imagesetthickness($image, $thick);
    return imageline($image, $x1, $y1, $x2, $y2, $color);
    */
    if ($thick == 1) {
        return imageline($image, $x1, $y1, $x2, $y2, $color);
    }
    $t = $thick / 2 - 0.5;
    if ($x1 == $x2 || $y1 == $y2) {
        return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
    }
    $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
    $a = $t / sqrt(1 + pow($k, 2));
    $points = array(
        round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
        round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
        round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
        round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
    );    
    imagefilledpolygon($image, $points, 4, $color);
    return imagepolygon($image, $points, 4, $color);
}

?>

See also imagecreatetruecolor() and imagecolorallocate().

imageloadfont

(PHP 3, PHP 4, PHP 5)

imageloadfont -- Load a new font

Description

int imageloadfont ( string file )

imageloadfont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts). 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 positionC data typedescription
byte 0-3intnumber of characters in the font
byte 4-7int value of first character in the font (often 32 for space)
byte 8-11intpixel width of each character
byte 12-15intpixel 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

<?php
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 49, 19, $white);
$font = imageloadfont("04b.gdf");
imagestring($im, $font, 0, 0, "Hello", $black);
imagepng($im);
?>

See also imagefontwidth() and imagefontheight().

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5)

imagepalettecopy -- Copy the palette from one image to another

Description

void imagepalettecopy ( resource destination, resource source )

imagepalettecopy() copies the palette from the source image to the destination image.

imagepng

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imagepng -- Output a PNG image to either the browser or a file

Description

bool imagepng ( resource image [, string filename] )

The imagepng() outputs a GD image stream (image) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.

<?php
$im = imagecreatefrompng("test.png");
imagepng($im);
?>

See also imagegif(), imagewbmp(), imagejpeg(), imagetypes().

imagepolygon

(PHP 3, PHP 4, PHP 5)

imagepolygon -- Draw a polygon

Description

bool imagepolygon ( resource image, array points, int num_points, int color )

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

<?php
// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// draw the polygon
imagepolygon($image, 
             array (
                    0, 0,
                    100, 200,
                    300, 200
             ),
             3,
             $col_poly);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

See also imagecreate() and imagecreatetruecolor().

imagepsbbox

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsbbox --  Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string text, int font, int size [, int space, int tightness, float angle] )

size is expressed in pixels.

space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

angle is in degrees.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, and angle are optional.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.

This function returns an array containing the following elements:

0lower left x-coordinate
1lower left y-coordinate
2upper right x-coordinate
3upper right y-coordinate

See also imagepstext().

imagepscopyfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepscopyfont --  Make a copy of an already loaded font for further modification

Description

int imagepscopyfont ( resource fontindex )

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

imagepsencodefont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsencodefont -- Change the character encoding vector of a font

Description

bool imagepsencodefont ( resource font_index, string encodingfile )

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.

imagepsextendfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsextendfont -- Extend or condense a font

Description

bool imagepsextendfont ( int font_index, float extend )

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.

imagepsfreefont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsfreefont -- Free memory used by a PostScript Type 1 font

Description

bool imagepsfreefont ( resource fontindex )

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

imagepsloadfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsloadfont -- Load a PostScript Type 1 font from file

Description

resource imagepsloadfont ( string filename )

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.

Esempio 1. imagepsloadfont() example

<?php
header("Content-type: image/jpeg");
$im = imagecreatetruecolor(350, 45);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$font = imagepsloadfont("bchbi.pfb"); // or locate your .pfb files on your machine
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);
imagejpeg($im, "", 100); //for best quality...your mileage may vary
imagedestroy($im);
?>

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.

See also imagepsfreefont().

imagepsslantfont

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepsslantfont -- Slant a font

Description

bool imagepsslantfont ( resource font_index, float slant )

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.

imagepstext

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

imagepstext -- To draw a text string over an image using PostScript Type1 fonts

Description

array imagepstext ( resource image, string text, resource font, int size, int foreground, int background, int x, int y [, int space, int tightness, float angle, int antialias_steps] )

foreground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character. Refer to 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:

0lower left x-coordinate
1lower left y-coordinate
2upper right x-coordinate
3upper right y-coordinate

See also imagepsbbox().

imagerectangle

(PHP 3, PHP 4, PHP 5)

imagerectangle -- Draw a rectangle

Description

bool imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col )

imagerectangle() creates a rectangle of color col in image image starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.

imagerotate

(PHP 4 >= 4.3.0, PHP 5)

imagerotate -- Rotate an image with a given angle

Description

resource imagerotate ( resource src_im, float angle, int bgd_color [, int ignore_transparent] )

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.

// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.

imagesavealpha

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

Description

bool imagesavealpha ( resource image, bool saveflag )

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

(PHP 4 >= 4.0.6, PHP 5)

imagesetbrush -- Set the brush image for line drawing

Description

bool imagesetbrush ( resource image, resource brush )

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Nota: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

Nota: This function was added in PHP 4.0.6

imagesetpixel

(PHP 3, PHP 4, PHP 5)

imagesetpixel -- Set a single pixel

Description

bool imagesetpixel ( resource image, int x, int y, int color )

imagesetpixel() draws a pixel at x, y (top left is 0, 0) in image image of color color.

See also imagecreatetruecolor() and imagecolorallocate().

imagesetstyle

(PHP 4 >= 4.0.6, PHP 5)

imagesetstyle -- Set the style for line drawing

Description

bool imagesetstyle ( resource image, array style )

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED. 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

<?php
header("Content-type: image/jpeg");
$im  = imagecreatetruecolor(100, 100);
$w   = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red);
imagesetstyle($im, $style);

$brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg($im);
imagedestroy($im);
?>

See also imagesetbrush(), imageline().

Nota: This function was added in PHP 4.0.6

imagesetthickness

(PHP 4 >= 4.0.6, PHP 5)

imagesetthickness -- Set the thickness for line drawing

Description

bool imagesetthickness ( resource image, int thickness )

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

(PHP 4 >= 4.0.6, PHP 5)

imagesettile -- Set the tile image for filling

Description

bool imagesettile ( resource image, resource tile )

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Nota: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

imagestring

(PHP 3, PHP 4, PHP 5)

imagestring -- Draw a string horizontally

Description

bool imagestring ( resource image, int font, int x, int y, string s, int col )

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

<?php
// create a 100*30 image
$im = imagecreatetruecolor(100, 30);

// white background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// write the string at the top left
imagestring($im, 5, 0, 0, "Hello world!", $textcolor);

// output the image
header("Content-type: image/jpeg");
imagejpeg($im);
?>

See also imageloadfont(), and imagettftext().

imagestringup

(PHP 3, PHP 4, PHP 5)

imagestringup -- Draw a string vertically

Description

bool imagestringup ( resource image, int font, int x, int y, string s, int col )

imagestringup() draws the string s vertically in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

imagesx

(PHP 3, PHP 4, PHP 5)

imagesx -- Get image width

Description

int imagesx ( resource image )

imagesx() returns the width of the image identified by image.

Esempio 1. Using imagesx()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?>

See also imagecreatetruecolor(), getimagesize() and imagesy().

imagesy

(PHP 3, PHP 4, PHP 5)

imagesy -- Get image height

Description

int imagesy ( resource image )

imagesy() returns the height of the image identified by image.

Esempio 1. Using imagesy()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?>

See also imagecreatetruecolor(), getimagesize() and imagesx().

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5)

imagetruecolortopalette -- Convert a true color image to a palette image

Description

bool imagetruecolortopalette ( resource image, bool dither, int ncolors )

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors sets the maximum number of colors that should be retained in the palette.

Nota: This function requires GD 2.0.1 or later.

imagettfbbox

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

imagettfbbox -- Give the bounding box of a text using TrueType fonts

Description

array imagettfbbox ( float size, float angle, string fontfile, string text )

This function calculates and returns the bounding box in pixels for a TrueType text.

size

The font size in pixels.

angle

Angle in degrees in which text will be measured.

fontfile

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.

text

The string to be measured.

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0lower left corner, X position
1lower left corner, Y position
2lower right corner, X position
3lower right corner, Y position
4upper right corner, X position
5upper right corner, Y position
6upper left corner, X position
7upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.

This function requires both the GD library and the FreeType library.

See also imagettftext().

imagettftext

(PHP 3, PHP 4, PHP 5)

imagettftext -- Write text to the image using TrueType fonts

Description

array imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )

image

The image resource. See imagecreatetruecolor().

size

The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).

angle

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.

x

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.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().

fontfile

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

text

The text string.

May include decimal numeric character references (of the form: &#8364;) 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.

<?php
// Set the content-type
header("Content-type: image/png");

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

This function requires both the GD library and the FreeType library.

See also imagettfbbox().

imagetypes

(PHP 3 CVS only, PHP 4 >= 4.0.2, PHP 5)

imagetypes -- Return the image types supported by this PHP build

Description

int imagetypes ( void )

This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. To check for PNG support, for example, do this:

Esempio 1. imagetypes() example

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

imagewbmp

(PHP 3 >= 3.0.15, PHP 4 >= 4.0.1, PHP 5)

imagewbmp -- Output image to browser or file

Description

bool imagewbmp ( resource image [, string filename [, int foreground]] )

imagewbmp() creates the WBMP file in filename from the image image. The image argument is the return from the 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().

imagexbm

(PHP 5)

imagexbm --  Output XBM image to browser or file

Description

bool imagexbm ( resource image, string filename [, int foreground] )

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.

iptcembed

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

iptcembed -- Embed binary IPTC data into a JPEG image

Description

mixed iptcembed ( string iptcdata, string jpeg_file_name [, int spool] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

iptcparse

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.

Description

array iptcparse ( string iptcblock )

This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found. See getimagesize() for a sample.

jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5)

jpeg2wbmp -- Convert JPEG image file to WBMP image file

Description

int jpeg2wbmp ( string jpegname, string wbmpname, int d_height, int d_width, int threshold )

Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

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

png2wbmp

(PHP 4 >= 4.0.5, PHP 5)

png2wbmp -- Convert PNG image file to WBMP image file

Description

int png2wbmp ( string pngname, string wbmpname, int d_height, int d_width, int threshold )

Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also jpeg2wbmp().

LVII. IMAP, POP3 and NNTP Functions

Introduzione

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.


Requisiti

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.


Installazione

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.

Avvertimento

Il modulo IMAP non può essere utilizzato in congiunzione con i moduli recode, YAZ oppure Cyrus. Poichè questi moduli condividono i medesimi simboli interni.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

NIL (integer)

OP_DEBUG (integer)

OP_READONLY (integer)

Open mailbox read-only

OP_ANONYMOUS (integer)

Don't use or update a .newsrc for news (NNTP only)

OP_SHORTCACHE (integer)

OP_SILENT (integer)

OP_PROTOTYPE (integer)

OP_HALFOPEN (integer)

For IMAP and NNTP names, open a connection but don't open a mailbox.

OP_EXPUNGE (integer)

OP_SECURE (integer)

CL_EXPUNGE (integer)

silently expunge the mailbox before closing when calling imap_close()

FT_UID (integer)

The parameter is a UID

FT_PEEK (integer)

Do not set the \Seen flag if not already set

FT_NOT (integer)

FT_INTERNAL (integer)

The return string is in internal format, will not canonicalize to CRLF.

FT_PREFETCHTEXT (integer)

ST_UID (integer)

The sequence argument contains UIDs instead of sequence numbers

ST_SILENT (integer)

ST_SET (integer)

CP_UID (integer)

the sequence numbers contain UIDS

CP_MOVE (integer)

Delete the messages from the current mailbox after copying with imap_mail_copy()

SE_UID (integer)

Return UIDs instead of sequence numbers

SE_FREE (integer)

SE_NOPREFETCH (integer)

Don't prefetch searched messages

SO_FREE (integer)

SO_NOSERVER (integer)

SA_MESSAGES (integer)

SA_RECENT (integer)

SA_UNSEEN (integer)

SA_UIDNEXT (integer)

SA_UIDVALIDITY (integer)

SA_ALL (integer)

LATT_NOINFERIORS (integer)

This mailbox has no "children" (there are no mailboxes below this one).

LATT_NOSELECT (integer)

This is only a container, not a mailbox - you cannot open it.

LATT_MARKED (integer)

This mailbox is marked. Only used by UW-IMAPD.

LATT_UNMARKED (integer)

This mailbox is not marked. Only used by UW-IMAPD.

SORTDATE (integer)

Sort criteria for imap_sort(): message Date

SORTARRIVAL (integer)

Sort criteria for imap_sort(): arrival date

SORTFROM (integer)

Sort criteria for imap_sort(): mailbox in first From address

SORTSUBJECT (integer)

Sort criteria for imap_sort(): message subject

SORTTO (integer)

Sort criteria for imap_sort(): mailbox in first To address

SORTCC (integer)

Sort criteria for imap_sort(): mailbox in first cc address

SORTSIZE (integer)

Sort criteria for imap_sort(): size of message in octets

TYPETEXT (integer)

TYPEMULTIPART (integer)

TYPEMESSAGE (integer)

TYPEAPPLICATION (integer)

TYPEAUDIO (integer)

TYPEIMAGE (integer)

TYPEVIDEO (integer)

TYPEOTHER (integer)

ENC7BIT (integer)

ENC8BIT (integer)

ENCBINARY (integer)

ENCBASE64 (integer)

ENCQUOTEDPRINTABLE (integer)

ENCOTHER (integer)


Vedere anche:

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • RFC2821: Simple Mail Transfer Protocol (SMTP).

  • RFC2822: Standard for ARPA internet text messages.

  • RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.

  • RFC1939: Post Office Protocol Version 3 (POP3).

  • RFC977: Network News Transfer Protocol (NNTP).

  • RFC2076: Common Internet Message Headers.

  • RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books Programming Internet Email by David Wood and Managing IMAP by Dianna Mullet & Kevin Mullet.

Sommario
imap_8bit --  Convert an 8bit string to a quoted-printable string
imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset
imap_append --  Append a string message to a specified mailbox
imap_base64 -- Decode BASE64 encoded text
imap_binary --  Convert an 8bit string to a base64 string
imap_body -- Read the message body
imap_bodystruct --  Read the structure of a specified body section of a specific message
imap_check -- Check current mailbox
imap_clearflag_full -- Clears flags on messages
imap_close -- Close an IMAP stream
imap_createmailbox -- Create a new mailbox
imap_delete --  Mark a message for deletion from current mailbox
imap_deletemailbox -- Delete a mailbox
imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset
imap_expunge -- Delete all messages marked for deletion
imap_fetch_overview --  Read an overview of the information in the headers of the given message
imap_fetchbody --  Fetch a particular section of the body of the message
imap_fetchheader -- Returns header for a message
imap_fetchstructure --  Read the structure of a particular message
imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox
imap_get_quotaroot --  Retrieve the quota settings per user
imap_getacl --  Gets the ACL for a given mailbox
imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one
imap_getsubscribed -- List all the subscribed mailboxes
imap_header -- Alias di imap_headerinfo()
imap_headerinfo -- Read the header of the message
imap_headers --  Returns headers for all messages in a mailbox
imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request
imap_list -- Read the list of mailboxes
imap_listmailbox -- Alias di imap_list()
imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_listsubscribed -- Alias di imap_lsub()
imap_lsub -- List all the subscribed mailboxes
imap_mail_compose --  Create a MIME message based on given envelope and body sections
imap_mail_copy -- Copy specified messages to a mailbox
imap_mail_move -- Move specified messages to a mailbox
imap_mail --  Send an email message
imap_mailboxmsginfo -- Get information about the current mailbox
imap_mime_header_decode -- Decode MIME header elements
imap_msgno --  This function returns the message sequence number for the given UID
imap_num_msg --  Gives the number of messages in the current mailbox
imap_num_recent -- Gives the number of recent messages in current mailbox
imap_open -- Open an IMAP stream to a mailbox
imap_ping -- Check if the IMAP stream is still active
imap_qprint -- Convert a quoted-printable string to an 8 bit string
imap_renamemailbox -- Rename an old mailbox to new mailbox
imap_reopen -- Reopen IMAP stream to new mailbox
imap_rfc822_parse_adrlist -- Parses an address string
imap_rfc822_parse_headers -- Parse mail headers from a string
imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info
imap_scanmailbox -- Alias di imap_listscan()
imap_search --  This function returns an array of messages matching the given search criteria
imap_set_quota -- Sets a quota for a given mailbox
imap_setacl --  Sets the ACL for a giving mailbox
imap_setflag_full -- Sets flags on messages
imap_sort -- Sort an array of message headers
imap_status --  This function returns status information on a mailbox other than the current one
imap_subscribe -- Subscribe to a mailbox
imap_thread --  Returns a tree of threaded message
imap_timeout --  Set or fetch imap timeout
imap_uid --  This function returns the UID for the given message sequence number
imap_undelete --  Unmark the message which is marked deleted
imap_unsubscribe -- Unsubscribe from a mailbox
imap_utf7_decode --  Decodes a modified UTF-7 encoded string
imap_utf7_encode --  Converts ISO-8859-1 string to modified UTF-7 text
imap_utf8 --  Converts MIME-encoded text to UTF-8

imap_8bit

(PHP 3, PHP 4, PHP 5)

imap_8bit --  Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string string )

Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).

Returns a quoted-printable string.

See also imap_qprint().

imap_alerts

(PHP 3 >= 3.0.12, PHP 4, 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 reset

Description

array imap_alerts ( void )

This function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

imap_append

(PHP 3, PHP 4, PHP 5)

imap_append --  Append a string message to a specified mailbox

Description

bool imap_append ( resource imap_stream, string mbox, string message [, string options] )

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

<?php
$stream = imap_open("{your.imap.host}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check->Nmsgs . "\n";

imap_append($stream, "{your.imap.host}INBOX.Drafts"
                   , "From: me@example.com\r\n"
                   . "To: you@example.com\r\n"
                   . "Subject: test\r\n"
                   . "\r\n"
                   . "this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
echo "Msg Count after append : ". $check->Nmsgs . "\n";

imap_close($stream);
?>

imap_base64

(PHP 3, PHP 4, PHP 5)

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64 ( string text )

imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.

See also imap_binary(), base64_encode() and base64_decode().

imap_binary

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_binary --  Convert an 8bit string to a base64 string

Description

string imap_binary ( string string )

Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).

Returns a base64 string.

See also imap_base64().

imap_body

(PHP 3, PHP 4, PHP 5)

imap_body -- Read the message body

Description

string imap_body ( resource imap_stream, int msg_number [, int options] )

imap_body() returns the body of the message, numbered msg_number in the current mailbox.

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

imap_bodystruct

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_bodystruct --  Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( resource stream_id, int msg_no, string section )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

imap_check

(PHP 3, PHP 4, PHP 5)

imap_check -- Check current mailbox

Description

object imap_check ( resource imap_stream )

Returns information about the current mailbox. Returns FALSE on failure.

The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:

  • Date - 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

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

this will output :

object(stdClass)(5) {
  ["Date"]=>
  string(37) "Wed, 10 Dec 2003 17:56:54 +0100 (CET)"
  ["Driver"]=>
  string(4) "imap"
  ["Mailbox"]=>
  string(54)
  "{www.example.com:143/imap/user="foo@example.com"}INBOX"
  ["Nmsgs"]=>
  int(1)
  ["Recent"]=>
  int(0)
}

imap_clearflag_full

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_clearflag_full -- Clears flags on messages

Description

bool imap_clearflag_full ( resource stream, string sequence, string flag [, string options] )

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060). 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().

imap_close

(PHP 3, PHP 4, PHP 5)

imap_close -- Close an IMAP stream

Description

bool imap_close ( resource imap_stream [, int flag] )

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

(PHP 3, PHP 4, PHP 5)

imap_createmailbox -- Create a new mailbox

Description

bool imap_createmailbox ( resource imap_stream, string mbox )

imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()

Restituisce TRUE in caso di successo, FALSE in caso di fallimento..

Esempio 1. imap_createmailbox() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&ouml;x");

$newname = $name1;

echo "Newname will be '$name1'<br />\n";

// we will now create a new mailbox "phptestbox" in your inbox folder,
// check its status after creation and finaly remove it to restore
// your inbox to its initial state 

if (@imap_createmailbox($mbox, imap_utf7_encode("{your.imap.host}INBOX.$newname"))) {
    $status = @imap_status($mbox, "{your.imap.host}INBOX.$newname", SA_ALL);
    if ($status) {
        echo "your new mailbox '$name1' has the following status:<br />\n";
        echo "Messages:   " . $status->messages    . "<br />\n";
        echo "Recent:     " . $status->recent      . "<br />\n";
        echo "Unseen:     " . $status->unseen      . "<br />\n";
        echo "UIDnext:    " . $status->uidnext     . "<br />\n";
        echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";

        if (imap_renamemailbox($mbox, "{your.imap.host}INBOX.$newname", "{your.imap.host}INBOX.$name2")) {
            echo "renamed new mailbox from '$name1' to '$name2'<br />\n";
            $newname = $name2;
        } else {
            echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "<br />\n";
        }
    } else {
        echo "imap_status on new mailbox failed: " . imap_last_error() . "<br />\n";
    }
    
    if (@imap_deletemailbox($mbox, "{your.imap.host}INBOX.$newname")) {
        echo "new mailbox removed to restore initial state<br />\n";
    } else {
        echo "imap_deletemailbox on new mailbox failed: " . implode("<br />\n", imap_errors()) . "<br />\n";
    }

} else {
    echo "could not create new mailbox: " . implode("<br />\n", imap_errors()) . "<br />\n";
}

imap_close($mbox);
?>

See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.

imap_delete

(PHP 3, PHP 4, PHP 5)

imap_delete --  Mark a message for deletion from current mailbox

Description

bool imap_delete ( int imap_stream, int msg_number [, int options] )

Returns TRUE.

imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

Nota: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

Esempio 1. imap_delete() example

<?php

$mbox = imap_open("{your.imap.host}INBOX", "username", "password")
    or die("Can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";

imap_delete($mbox, 1);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";

imap_expunge($mbox);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";

imap_close($mbox);
?>

See also: imap_undelete(), imap_expunge(), and imap_close().

imap_deletemailbox

(PHP 3, PHP 4, PHP 5)

imap_deletemailbox -- Delete a mailbox

Description

bool imap_deletemailbox ( resource imap_stream, string mbox )

imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).

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.

imap_errors

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

Description

array imap_errors ( void )

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.

See also: imap_last_error().

imap_expunge

(PHP 3, PHP 4, PHP 5)

imap_expunge -- Delete all messages marked for deletion

Description

bool imap_expunge ( resource imap_stream )

imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Returns TRUE.

imap_fetch_overview

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_fetch_overview --  Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( resource imap_stream, string sequence [, int options] )

This function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:

  • subject - the messages subject

  • from - who sent it

  • 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

<?php
$mbox = imap_open("{your.imap.host:143}", "username", "password")
     or die("can't connect: " . imap_last_error());
 
$overview = imap_fetch_overview($mbox, "2,4:6", 0);
 
if (is_array($overview)) {
    foreach ($overview as $val) {
        echo "$val->msgno - $val->date - $val->subject\n";
    }
}
 
imap_close($mbox);
?>

imap_fetchbody

(PHP 3, PHP 4, PHP 5)

imap_fetchbody --  Fetch a particular section of the body of the message

Description

string imap_fetchbody ( resource imap_stream, int msg_number, string part_number [, int options] )

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

The options for imap_fetchbody() is a bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

See also: imap_fetchstructure().

imap_fetchheader

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_fetchheader -- Returns header for a message

Description

string imap_fetchheader ( resource imap_stream, int msgno [, int options] )

This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.

The options are:

  • FT_UID - The msgno argument is a UID

  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines

  • FT_PREFETCHTEXT - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)

imap_fetchstructure

(PHP 3, PHP 4, PHP 5)

imap_fetchstructure --  Read the structure of a particular message

Description

object imap_fetchstructure ( resource imap_stream, int msg_number [, int options] )

This function fetches all the structured information for a given message. The optional 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()

typePrimary body type
encodingBody transfer encoding
ifsubtypeTRUE if there is a subtype string
subtypeMIME subtype
ifdescriptionTRUE if there is a description string
descriptionContent description string
ifidTRUE if there is an identification string
idIdentification string
linesNumber of lines
bytesNumber of bytes
ifdispositionTRUE if there is a disposition string
dispositionDisposition string
ifdparametersTRUE if the dparameters array exists
dparametersAn array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
ifparametersTRUE if the parameters array exists
parametersAn array of objects where each object has an "attribute" and a "value" property.
partsAn array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Tabella 2. Primary body type

0text
1multipart
2message
3application
4audio
5image
6video
7other

Tabella 3. Transfer encodings

07BIT
18BIT
2BINARY
3BASE64
4QUOTED-PRINTABLE
5OTHER

See also: imap_fetchbody().

imap_get_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( resource imap_stream, string quota_root )

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

This function is currently only available to users of the c-client2000 or greater library.

NOTE: For this function to work, the mail stream is required to be opened as the mail-admin user. For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

imap_stream should be the value returned from an imap_open() call. NOTE: This stream is required to be opened as the mail admin user for the get_quota function to work. quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

Esempio 1. imap_get_quota() example

<?php
$mbox = imap_open("{your.imap.host}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$quota_value = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_value)) {
    echo "Usage level is: " . $quota_value['usage'];
    echo "Limit level is: " . $quota_value['limit'];
} 
 
imap_close($mbox); 
?>

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

<?php
$mbox = imap_open("{your.imap.host}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
       
$quota_values = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE']; 
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit is: " .  $message['limit'];

   /* ...  */ 
} 

imap_close($mbox); 
?>

See also imap_open(), imap_set_quota() and imap_get_quotaroot().

imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5)

imap_get_quotaroot --  Retrieve the quota settings per user

Description

array imap_get_quotaroot ( resource imap_stream, string quota_root )

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity. This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream should be the value returned from an imap_open() call. This stream should be opened as the user whose mailbox you wish to check. quota_root should normally be in the form of which mailbox (i.e. INBOX).

Esempio 1. imap_get_quotaroot() example

<?php
$mbox = imap_open("{your.imap.host}", "kalowsky", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE']; 
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */ 

} 
 
imap_close($mbox); 
?>

See also imap_open(), imap_set_quota() and imap_get_quota().

imap_getacl

(PHP 5)

imap_getacl --  Gets the ACL for a given mailbox

Description

array imap_getacl ( resource stream_id, string mailbox )

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

imap_getmailboxes

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( resource imap_stream, string ref, string pattern )

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.

  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().

ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Esempio 1. imap_getmailboxes() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$list = imap_getmailboxes($mbox, "{your.imap.host}", "*");
if (is_array($list)) {
    foreach ($list as $key => $val) {
        echo "($key) ";
        echo imap_utf7_decode($val->name) . ",";
        echo "'" . $val->delimiter . "',";
        echo $val->attributes . "<br />\n";
    }
} else {
    echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}
 
imap_close($mbox);
?>

See also imap_getsubscribed().

imap_getsubscribed

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_getsubscribed -- List all the subscribed mailboxes

Description

array imap_getsubscribed ( resource imap_stream, string ref, string pattern )

This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

imap_header

(PHP 3, PHP 4, PHP 5)

imap_header -- Alias di imap_headerinfo()

Descrizione

This function is an alias of: imap_headerinfo().

imap_headerinfo

(PHP 3, PHP 4, PHP 5)

imap_headerinfo -- Read the header of the message

Description

object imap_headerinfo ( resource imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]] )

This function returns an object of various header elements.


       remail, date, Date, subject, Subject, in_reply_to, message_id,
       newsgroups, followup_to, references

message flags:
   Recent -  'R' if recent and seen, 
             'N' if recent and not seen, 
             ' ' if not recent
   Unseen -  'U' if not seen AND not recent, 
             ' ' if seen OR not seen and recent
   Answered -'A' if answered, 
             ' ' if unanswered
   Deleted - 'D' if deleted, 
             ' ' if not deleted
   Draft -   'X' if draft, 
             ' ' if not draft
   Flagged - 'F' if flagged, 
             ' ' if not flagged

NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for

Unseen == 'U' || Recent == 'N'

toaddress (full to: line, up to 1024 characters)

to[] (returns an array of objects from the To line, containing):
   personal
   adl
   mailbox
   host

fromaddress (full from: line, up to 1024 characters)

from[] (returns an array of objects from the From line, containing):
   personal
   adl
   mailbox
   host

ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
   personal
   adl
   mailbox
   host

bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
   personal
   adl
   mailbox
   host

reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
   personal
   adl
   mailbox
   host

senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
   personal
   adl
   mailbox
   host

return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
   personal
   adl
   mailbox
   host

udate (mail message date in unix time)

fetchfrom (from line formatted to fit fromlength 
characters)

fetchsubject (subject line formatted to fit subjectlength characters)
      

imap_headers

(PHP 3, PHP 4, PHP 5)

imap_headers --  Returns headers for all messages in a mailbox

Description

array imap_headers ( resource imap_stream )

Returns an array of string formatted with header info. One element per mail message.

imap_last_error

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request

Description

string imap_last_error ( void )

This function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

See also: imap_errors().

imap_list

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_list -- Read the list of mailboxes

Description

array imap_list ( resource imap_stream, string ref, string pattern )

Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.

Esempio 1. imap_list() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$list = imap_list($mbox, "{your.imap.host}", "*");
if (is_array($list)) {
    foreach ($list as $val) {
        echo imap_utf7_decode($val) . "<br />\n";
    }
} else {
    echo "imap_list failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

See also: imap_getmailboxes().

imap_listmailbox

(PHP 3, PHP 4, PHP 5)

imap_listmailbox -- Alias di imap_list()

Descrizione

This function is an alias of: imap_list().

imap_listscan

(no version information, might be only in CVS)

imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox

Description

array imap_listscan ( resource imap_stream, string ref, string pattern, string content )

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.

See imap_getmailboxes() for a description of ref and pattern.

imap_listsubscribed

(PHP 3, PHP 4, PHP 5)

imap_listsubscribed -- Alias di imap_lsub()

Descrizione

This function is an alias of: imap_lsub().

imap_lsub

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_lsub -- List all the subscribed mailboxes

Description

array imap_lsub ( resource imap_stream, string ref, string pattern )

Returns an array of all the mailboxes that you have subscribed.

imap_mail_compose

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

imap_mail_compose --  Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array envelope, array body )

Esempio 1. imap_mail_compose() example

<?php

$envelope["from"]= "joe@example.com";
$envelope["to"]  = "foo@example.com";
$envelope["cc"]  = "bar@example.com";

$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";

$filename = "/tmp/imap.c.gz";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);

$part2["type"] = TYPEAPPLICATION;
$part2["encoding"] = ENCBINARY;
$part2["subtype"] = "octet-stream";
$part2["description"] = basename($filename);
$part2["contents.data"] = $contents;

$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = "contents.data3\n\n\n\t";

$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;

echo nl2br(imap_mail_compose($envelope, $body));

?>

imap_mail_copy

(PHP 3, PHP 4, PHP 5)

imap_mail_copy -- Copy specified messages to a mailbox

Description

bool imap_mail_copy ( resource imap_stream, string msglist, string mbox [, int options] )

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

imap_mail_move

(PHP 3, PHP 4, PHP 5)

imap_mail_move -- Move specified messages to a mailbox

Description

bool imap_mail_move ( resource imap_stream, string msglist, string mbox [, int options] )

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

imap_mail

(PHP 3 >= 3.0.14, PHP 4, PHP 5)

imap_mail --  Send an email message

Description

bool imap_mail ( string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]] )

This function allows sending of emails with correct handling of Cc and Bcc receivers. 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.

imap_mailboxmsginfo

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_mailboxmsginfo -- Get information about the current mailbox

Description

object imap_mailboxmsginfo ( resource imap_stream )

Returns information about the current mailbox. Returns FALSE on failure.

The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.

Tabella 1. Mailbox properties

Datedate of last change
Driverdriver
Mailboxname of the mailbox
Nmsgsnumber of messages
Recentnumber of recent messages
Unreadnumber of unread messages
Deletednumber of deleted messages
Sizemailbox size

Esempio 1. imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{your.imap.host}INBOX", "username", "password")
      or die("can't connect: " . imap_last_error());
 
$check = imap_mailboxmsginfo($mbox);
 
if ($check) {
    echo "Date: "     . $check->Date    . "<br />\n" ;
    echo "Driver: "   . $check->Driver  . "<br />\n" ;
    echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;
    echo "Messages: " . $check->Nmsgs   . "<br />\n" ;
    echo "Recent: "   . $check->Recent  . "<br />\n" ;
    echo "Unread: "   . $check->Unread  . "<br />\n" ;
    echo "Deleted: "  . $check->Deleted . "<br />\n" ;
    echo "Size: "     . $check->Size    . "<br />\n" ;
} else {
    echo "imap_check() failed: " . imap_last_error() . "<br />\n";
}
 
imap_close($mbox);

?>

imap_mime_header_decode

(PHP 3 >= 3.0.17, PHP 4, PHP 5)

imap_mime_header_decode -- Decode MIME header elements

Description

array imap_mime_header_decode ( string text )

imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047). The decoded elements are returned in an array of objects, where each object has two properties, "charset" 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".

Esempio 1. imap_mime_header_decode() example

<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";

$elements = imap_mime_header_decode($text);
for ($i=0; $i<count($elements); $i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}
?>

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

imap_msgno

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_msgno --  This function returns the message sequence number for the given UID

Description

int imap_msgno ( resource imap_stream, int uid )

This function returns the message sequence number for the given uid. It is the inverse of imap_uid().

See also imap_uid().

imap_num_msg

(PHP 3, PHP 4, PHP 5)

imap_num_msg --  Gives the number of messages in the current mailbox

Description

int imap_num_msg ( resource imap_stream )

Return the number of messages in the current mailbox.

See also: imap_num_recent() and imap_status().

imap_num_recent

(PHP 3, PHP 4, PHP 5)

imap_num_recent -- Gives the number of recent messages in current mailbox

Description

int imap_num_recent ( resource imap_stream )

Returns the number of recent messages in the current mailbox.

See also: imap_num_msg() and imap_status().

imap_open

(PHP 3, PHP 4, PHP 5)

imap_open -- Open an IMAP stream to a mailbox

Description

resource imap_open ( string mailbox, string username, string password [, int options] )

Returns an IMAP stream on success and FALSE on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/'). The server part is mandatory in all mailbox parameters. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

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

FlagDescription
/service=servicemailbox access service, default is "imap"
/user=userremote user name for login on the server
/authuser=userremote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymousremote access as anonymous user
/debugrecord protocol telemetry in application's debug log
/securedo not transmit a plaintext password over the network
/imap, /imap2, /imap2bis, /imap4, /imap4rev1equivalent to /service=imap
/pop3equivalent to /service=pop3
/nntpequivalent to /service=nntp
/norshdo not use rsh or ssh to establish a preauthenticated IMAP session
/ssluse the Secure Socket Layer to encrypt the session
/validate-certvalidate certificates from TLS/SSL server (this is the default behavior)
/novalidate-certdo not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
/tlsforce use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notlsdo not do start-TLS to encrypt the session, even with servers that support it
/readonlyrequest 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()

<?php
// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.
?>

Esempio 2. imap_open() example

<?php
$mbox = imap_open("{your.imap.host:143}", "username", "password");

echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{your.imap.host:143}", "*");

if ($folders == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($folders as $val) {
        echo $val . "<br />\n";
    }
}

echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($headers as $val) {
        echo $val . "<br />\n";
    }
}

imap_close($mbox);
?>

imap_ping

(PHP 3, PHP 4, PHP 5)

imap_ping -- Check if the IMAP stream is still active

Description

bool imap_ping ( resource imap_stream )

Returns TRUE if the stream is still alive, FALSE otherwise.

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

Esempio 1. imap_ping() Example

<?php

$imap = imap_open("{your.imap.host}", "mailadmin", "password");

// after some sleeping
if (!imap_ping($imap)) {
    // do some stuff to reconnect
}

?>

imap_qprint

(PHP 3, PHP 4, PHP 5)

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string string )

Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).

See also imap_8bit().

imap_renamemailbox

(PHP 3, PHP 4, PHP 5)

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

bool imap_renamemailbox ( resource imap_stream, string old_mbox, string new_mbox )

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

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.

imap_reopen

(PHP 3, PHP 4, PHP 5)

imap_reopen -- Reopen IMAP stream to new mailbox

Description

bool imap_reopen ( resource imap_stream, string mailbox [, string options] )

This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

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

imap_rfc822_parse_adrlist

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_rfc822_parse_adrlist -- Parses an address string

Description

array imap_rfc822_parse_adrlist ( string address, string default_host )

This function parses the address string as defined in RFC2822 and for each address, returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)

  • host - the host name

  • personal - the personal name

  • adl - at domain source route

Esempio 1. imap_rfc822_parse_adrlist() example

<?php

$address_string = "Joe Doe <doe@example.com>, postmaster@example.com, root";
$address_array  = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) < 1) {
    die("something is wrong\n");
}
 
foreach ($address_array as $val) {
  echo "mailbox : " . $val->mailbox . "<br />\n";
  echo "host    : " . $val->host . "<br />\n";
  echo "personal: " . $val->personal . "<br />\n";
  echo "adl     : " . $val->adl . "<br />\n";
} 
?>

imap_rfc822_parse_headers

(PHP 4, PHP 5)

imap_rfc822_parse_headers -- Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string headers [, string defaulthost] )

This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.

imap_rfc822_write_address

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info

Description

string imap_rfc822_write_address ( string mailbox, string host, string personal )

Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.

Esempio 1. imap_rfc822_write_address() example

<?php
echo imap_rfc822_write_address("hartmut", "cvs.php.net", "Hartmut Holzgraefe") . "\n";      
?>

imap_scanmailbox

(PHP 3, PHP 4, PHP 5)

imap_scanmailbox -- Alias di imap_listscan()

Descrizione

This function is an alias of: imap_listscan().

imap_search

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

imap_search --  This function returns an array of messages matching the given search criteria

Description

array imap_search ( resource imap_stream, string criteria [, int options [, string charset]] )

This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (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.

imap_set_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_set_quota -- Sets a quota for a given mailbox

Description

bool imap_set_quota ( resource imap_stream, string quota_root, int quota_limit )

Sets an upper limit quota on a per mailbox basis. This function requires the imap_stream to have been opened as the mail administrator account. It will not work if opened as any other user.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.

Returns TRUE on success and FALSE on error.

Esempio 1. imap_set_quota() example

<?php
$mbox = imap_open("{your.imap.host:143}", "mailadmin", "password");

if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    echo "Error in setting quota\n";
    return;
}

imap_close($mbox);
?>

See also imap_open() and imap_get_quota().

imap_setacl

(PHP 4 >= 4.1.0, PHP 5)

imap_setacl --  Sets the ACL for a giving mailbox

Description

bool imap_setacl ( resource stream_id, string mailbox, string id, string rights )

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

imap_setflag_full

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_setflag_full -- Sets flags on messages

Description

bool imap_setflag_full ( resource stream, string sequence, string flag [, string options] )

This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.

The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

options are a bit mask and may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Esempio 1. imap_setflag_full() example

<?php
$mbox = imap_open("{your.imap.host:143}", "username", "password")
     or die("can't connect: " . imap_last_error());
 
$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");
 
echo gettype($status) . "\n";
echo $status . "\n";
 
imap_close($mbox);
?>

See also: imap_clearflag_full().

imap_sort

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_sort -- Sort an array of message headers

Description

array imap_sort ( resource stream, int criteria, int reverse [, int options [, string search_criteria [, string charset]]] )

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.

imap_status

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

imap_status --  This function returns status information on a mailbox other than the current one

Description

object imap_status ( resource imap_stream, string mailbox, int options )

This function returns an object containing status information. Valid flags are:

  • SA_MESSAGES - set status->messages to the number of messages in the mailbox

  • SA_RECENT - set status->recent to the number of recent messages in the mailbox

  • SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox

  • SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox

  • SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid

  • SA_ALL - set all of the above

status->flags is also set, which contains a bitmask which can be checked against any of the above constants.

Esempio 1. imap_status() example

<?php
$mbox = imap_open("{your.imap.host}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());
 
$status = imap_status($mbox, "{your.imap.host}INBOX", SA_ALL);
if ($status) {
  echo "Messages:   " . $status->messages    . "<br />\n";
  echo "Recent:     " . $status->recent      . "<br />\n";
  echo "Unseen:     " . $status->unseen      . "<br />\n";
  echo "UIDnext:    " . $status->uidnext     . "<br />\n";
  echo "UIDvalidity:" . $status->uidvalidity . "<br />\n"; 
} else {
  echo "imap_status failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

imap_subscribe

(PHP 3, PHP 4, PHP 5)

imap_subscribe -- Subscribe to a mailbox

Description

bool imap_subscribe ( resource imap_stream, string mbox )

Subscribe to a new mailbox.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also: imap_unsubscribe().

imap_thread

(PHP 4 >= 4.1.0, PHP 5)

imap_thread --  Returns a tree of threaded message

Description

array imap_thread ( resource stream_id [, int options] )

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

<?php

// Here we're outputting the threads of a newsgroup, in HTML

$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);

foreach ($thread as $key => $val) {
  $tree = explode('.', $key);
  if ($tree[1] == 'num') {
    $header = imap_headerinfo($nntp, $val);
    echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
  } elseif ($tree[1] == 'branch') {
    echo "\t</li>\n</ul>\n";
  }
}

imap_close($nntp);

?>

imap_timeout

(PHP 4 >= 4.3.3, PHP 5)

imap_timeout --  Set or fetch imap timeout

Description

mixed imap_timeout ( int timeout_type [, int timeout] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

imap_uid

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

imap_uid --  This function returns the UID for the given message sequence number

Description

int imap_uid ( resource imap_stream, int msgno )

This function returns the UID for the given message sequence number. An UID is 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().

imap_undelete

(PHP 3, PHP 4, PHP 5)

imap_undelete --  Unmark the message which is marked deleted

Description

bool imap_undelete ( resource imap_stream, int msg_number [, int flags] )

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

imap_unsubscribe

(PHP 3, PHP 4, PHP 5)

imap_unsubscribe -- Unsubscribe from a mailbox

Description

bool imap_unsubscribe ( string imap_stream, string mbox )

Unsubscribe from a specified mailbox.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also: imap_subscribe().

imap_utf7_decode

(PHP 3 >= 3.0.15, PHP 4, PHP 5)

imap_utf7_decode --  Decodes a modified UTF-7 encoded string

Description

string imap_utf7_decode ( string text )

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

imap_utf7_encode

(PHP 3 >= 3.0.15, PHP 4, PHP 5)

imap_utf7_encode --  Converts ISO-8859-1 string to modified UTF-7 text

Description

string imap_utf7_encode ( string data )

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

imap_utf8

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

imap_utf8 --  Converts MIME-encoded text to UTF-8

Description

string imap_utf8 ( string mime_encoded_text )

Converts the given mime_encoded_text to UTF-8. MIME encoding method and the UTF-8 specification are described in RFC2047 and RFC2044 respectively.

LVIII. Informix Functions

Introduzione

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.


Requisiti

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.


Installazione

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.


Configurazione di Runtime

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

NameDefaultChangeableChangelog
ifx.allow_persistent"1"PHP_INI_SYSTEM 
ifx.max_persistent"-1"PHP_INI_SYSTEM 
ifx.max_links"-1"PHP_INI_SYSTEM 
ifx.default_hostNULLPHP_INI_SYSTEM 
ifx.default_userNULLPHP_INI_SYSTEM 
ifx.default_passwordNULLPHP_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 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

The maximum number of Informix connections per process, including persistent connections.

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
ifx_affected_rows -- Get number of rows affected by a query
ifx_blobinfile_mode -- Set the default blob mode for all select queries
ifx_byteasvarchar -- Set the default byte mode
ifx_close -- Close Informix connection
ifx_connect -- Open Informix server connection
ifx_copy_blob -- Duplicates the given blob object
ifx_create_blob -- Creates an blob object
ifx_create_char -- Creates an char object
ifx_do --  Execute a previously prepared SQL-statement
ifx_error -- Returns error code of last Informix call
ifx_errormsg -- Returns error message of last Informix call
ifx_fetch_row -- Get row as enumerated array
ifx_fieldproperties -- List of SQL fieldproperties
ifx_fieldtypes -- List of Informix SQL fields
ifx_free_blob -- Deletes the blob object
ifx_free_char -- Deletes the char object
ifx_free_result -- Releases resources for the query
ifx_get_blob -- Return the content of a blob object
ifx_get_char -- Return the content of the char object
ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query
ifx_htmltbl_result --  Formats all rows of a query into a HTML table
ifx_nullformat --  Sets the default return value on a fetch row
ifx_num_fields -- Returns the number of columns in the query
ifx_num_rows -- Count the rows already fetched from a query
ifx_pconnect -- Open persistent Informix connection
ifx_prepare -- Prepare an SQL-statement for execution
ifx_query -- Send Informix query
ifx_textasvarchar -- Set the default text mode
ifx_update_blob -- Updates the content of the blob object
ifx_update_char -- Updates the content of the char object
ifxus_close_slob -- Deletes the slob object
ifxus_create_slob -- Creates an slob object and opens it
ifxus_free_slob -- Deletes the slob object
ifxus_open_slob -- Opens an slob object
ifxus_read_slob -- Reads nbytes of the slob object
ifxus_seek_slob -- Sets the current file or seek position
ifxus_tell_slob -- Returns the current file or seek position
ifxus_write_slob -- Writes a string into the slob object

ifx_affected_rows

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_affected_rows -- Get number of rows affected by a query

Description

int ifx_affected_rows ( int result_id )

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

Esempio 1. Informix affected rows

<?php
$rid = ifx_prepare("select * from emp 
                     where name like " . $name, $connid);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
?>

See also ifx_num_rows().

ifx_blobinfile_mode

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_blobinfile_mode -- Set the default blob mode for all select queries

Description

void ifx_blobinfile_mode ( int mode )

Set the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

ifx_byteasvarchar

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_byteasvarchar -- Set the default byte mode

Description

void ifx_byteasvarchar ( int mode )

Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_close

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_close -- Close Informix connection

Description

int ifx_close ( [int link_identifier] )

Returns: always TRUE.

ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

Esempio 1. Closing a Informix connection

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

See also ifx_connect() and ifx_pconnect().

ifx_connect

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_connect -- Open Informix server connection

Description

int ifx_connect ( [string database [, string userid [, string password]]] )

Returns a connection identifier on success, or FALSE on error.

ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().

Esempio 1. Connect to a Informix database

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

See also ifx_pconnect() and ifx_close().

ifx_copy_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_copy_blob -- Duplicates the given blob object

Description

int ifx_copy_blob ( int bid )

Duplicates the given blob object. bid is the ID of the blob object.

Returns FALSE on error otherwise the new blob object-id.

ifx_create_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_create_blob -- Creates an blob object

Description

int ifx_create_blob ( int type, int mode, string param )

Creates an blob object.

type: 1 = TEXT, 0 = BYTE

mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return FALSE on error, otherwise the new blob object-id.

ifx_create_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_create_char -- Creates an char object

Description

int ifx_create_char ( string param )

Creates an char object. param should be the char content.

ifx_do

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_do --  Execute a previously prepared SQL-statement

Description

int ifx_do ( int result_id )

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

ifx_error

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_error -- Returns error code of last Informix call

Description

string ifx_error ( void )

The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :

x [SQLSTATE = aa bbb SQLCODE=cccc]

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).

See also: ifx_errormsg()

ifx_errormsg

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_errormsg -- Returns error message of last Informix call

Description

string ifx_errormsg ( [int errorcode] )

Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" parameter is present, the error message corresponding to "errorcode".

Esempio 1. ifx_errormsg() example

printf("%s\n&lt;br>", ifx_errormsg(-201));

See also ifx_error().

ifx_fetch_row

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_fetch_row -- Get row as enumerated array

Description

array ifx_fetch_row ( int result_id [, mixed position] )

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

ifx_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0, with the column name as key.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Esempio 1. Informix fetch rows

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do ($rid)) {
   /* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for (reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br />");
    $row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?>

ifx_fieldproperties

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_fieldproperties -- List of SQL fieldproperties

Description

array ifx_fieldproperties ( int result_id )

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Esempio 1. Informix SQL fieldproperties

<?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname => $val) {
    echo "$fname:\t property = $val\n";
}
?>

ifx_fieldtypes

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_fieldtypes -- List of Informix SQL fields

Description

array ifx_fieldtypes ( int result_id )

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Esempio 1. Fieldnames and SQL fieldtypes

<?php
$types = ifx_fieldtypes($resultid);
if (!isset($types)) {
    /* ... error ... */
}
foreach ($types as $fname => $val) {
    echo "$fname:\t type = $val\n";
}
?>

ifx_free_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_free_blob -- Deletes the blob object

Description

int ifx_free_blob ( int bid )

Deletes the blobobject for the given blob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifx_free_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_free_char -- Deletes the char object

Description

int ifx_free_char ( int bid )

Deletes the charobject for the given char object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifx_free_result

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_free_result -- Releases resources for the query

Description

int ifx_free_result ( int result_id )

Releases resources for the query associated with result_id. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifx_get_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_get_blob -- Return the content of a blob object

Description

int ifx_get_blob ( int bid )

Returns the content of the blob object for the given blob object-id bid.

ifx_get_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_get_char -- Return the content of the char object

Description

int ifx_get_char ( int bid )

Returns the content of the char object for the given char object-id bid.

ifx_getsqlca

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

ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( int result_id )

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns a pseudo-row (associative array) with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Esempio 1. Retrieve Informix sqlca.sqlerrd[x] values

<?php
/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable 
                  values (0, '2nd column', 'another column') ", $connid);
if (!$qid) {
    /* ... error ... */
}
$sqlca = ifx_getsqlca($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : $serial_value<br />\n"; 
?>

ifx_htmltbl_result

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_htmltbl_result --  Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( int result_id [, string html_table_options] )

Returns the number of rows fetched or FALSE on error.

Formats all rows of the result_id query into a HTML table. The optional second argument is a string of <table> tag options

Esempio 1. Informix results as HTML table

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do($rid)) {
    /* ... error ... */
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);
?>

ifx_nullformat

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_nullformat --  Sets the default return value on a fetch row

Description

void ifx_nullformat ( int mode )

Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".

ifx_num_fields

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_num_fields -- Returns the number of columns in the query

Description

int ifx_num_fields ( int result_id )

Returns the number of columns in query for result_id or FALSE on error

After preparing or executing a query, this call gives you the number of columns in the query.

ifx_num_rows

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_num_rows -- Count the rows already fetched from a query

Description

int ifx_num_rows ( int result_id )

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

ifx_pconnect

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_pconnect -- Open persistent Informix connection

Description

int ifx_pconnect ( [string database [, string userid [, string password]]] )

Returns: A positive Informix persistent link identifier on success, or FALSE on error

ifx_pconnect() acts very much like ifx_connect() with two major differences.

This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

See also: ifx_connect().

ifx_prepare

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_prepare -- Prepare an SQL-statement for execution

Description

int ifx_prepare ( string query, int conn_id [, int cursor_def, mixed blobidarray] )

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

ifx_query

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ifx_query -- Send Informix query

Description

int ifx_query ( string query, int link_identifier [, int cursor_type [, mixed blobidarray]] )

Returns a positive Informix result identifier on success, or FALSE on error.

A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.

ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Esempio 1. Show all rows of the "orders" table as a HTML table

<?php
ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br />%s<br />\n", ifx_error());
    ifx_errormsg();
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?>

Esempio 2. Insert some values into the "catalog" table

<?php

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");

// store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;

// launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
    /* ... error ... */
}

// free result id
ifx_free_result($res_id);
?>

See also ifx_connect().

ifx_textasvarchar

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_textasvarchar -- Set the default text mode

Description

void ifx_textasvarchar ( int mode )

Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_update_blob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifx_update_blob -- Updates the content of the blob object

Description

bool ifx_update_blob ( int bid, string content )

Updates the content of the blob object for the given blob object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifx_update_char

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

ifx_update_char -- Updates the content of the char object

Description

int ifx_update_char ( int bid, string content )

Updates the content of the char object for the given char object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifxus_close_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_close_slob -- Deletes the slob object

Description

int ifxus_close_slob ( int bid )

Deletes the slob object on the given slob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifxus_create_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_create_slob -- Creates an slob object and opens it

Description

int ifxus_create_slob ( int mode )

Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.

ifxus_free_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_free_slob -- Deletes the slob object

Description

int ifxus_free_slob ( int bid )

Deletes the slob object. bid is the Id of the slob object. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ifxus_open_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_open_slob -- Opens an slob object

Description

int ifxus_open_slob ( int bid, int mode )

Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.

ifxus_read_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_read_slob -- Reads nbytes of the slob object

Description

int ifxus_read_slob ( int bid, int nbytes )

Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.

ifxus_seek_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( int bid, int mode, int offset )

Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.

ifxus_tell_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( int bid )

Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.

ifxus_write_slob

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( int bid, string content )

Writes a string into the slob object. bid is an existing slob id and content the content to write. Return FALSE on error otherwise bytes written.

LIX. Ingres II Functions

Introduzione

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


Requisiti

To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Ingres configuration options

NameDefaultChangeableChangelog
ingres.allow_persistent"1"PHP_INI_SYSTEMAvailable since PHP 4.0.2.
ingres.max_persistent"-1"PHP_INI_SYSTEMAvailable since PHP 4.0.2.
ingres.max_links"-1"PHP_INI_SYSTEMAvailable since PHP 4.0.2.
ingres.default_databaseNULLPHP_INI_ALLAvailable since PHP 4.0.2.
ingres.default_userNULLPHP_INI_ALLAvailable since PHP 4.0.2.
ingres.default_passwordNULLPHP_INI_ALLAvailable since PHP 4.0.2.
ingres.report_db_warnings"1"PHP_INI_ALLAvailable since version 1.1.0 of the PECL extension.
ingres.cursor_mode"0"PHP_INI_ALLAvailable since version 1.1.0 of the PECL extension.
ingres.blob_segment_length"4096"PHP_INI_ALLAvailable since version 1.2.0 of the PECL extension.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

INGRES_ASSOC (integer)

Columns are returned into the array having the fieldname as the array index.

INGRES_NUM (integer)

Columns are returned into the array having a numerical index to the fields. This index starts with 1, the first field in the result.

INGRES_BOTH (integer)

Columns are returned into the array having both a numerical index and the fieldname as the array index.

INGRES_EXT_VERSION (string)

Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.

INGRES_API_VERSION (integer)

Specifies the version of Ingres OpenAPI the extension was built against. Available since version 1.2.0 of the PECL extension.

INGRES_CURSOR_READONLY (integer)

Specifies that Ingres cursors should be opened in 'readonly' mode. Available since version 1.2.0 of the PECL extension.

INGRES_CURSOR_UPDATE (integer)

Specifies that Ingres cursors should be opened 'for update'. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_MULTINATIONAL (integer)

Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_MULTINATIONAL4 (integer)

Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_FINNISH (integer)

Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_ISO (integer)

Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_ISO4 (integer)

Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_GERMAN (integer)

Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_MDY (integer)

Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_DMY (integer)

Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.

INGRES_DATE_YMD (integer)

Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.

INGRES_MONEY_LEADING (integer)

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.

INGRES_MONEY_TRAILING (integer)

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.

Sommario
ingres_autocommit -- Switch autocommit on or off
ingres_close -- Close an Ingres II database connection
ingres_commit -- Commit a transaction
ingres_connect --  Open a connection to an Ingres II database
ingres_cursor -- Gets a cursor name for a given link resource
ingres_errno -- Gets the last ingres error number generated
ingres_error -- Gets a meaningful error message for the last error generated
ingres_errsqlstate -- Gets the last SQLSTATE error code generated
ingres_fetch_array -- Fetch a row of result into an array
ingres_fetch_object -- Fetch a row of result into an object
ingres_fetch_row --  Fetch a row of result into an enumerated array
ingres_field_length -- Get the length of a field
ingres_field_name -- Get the name of a field in a query result
ingres_field_nullable -- Test if a field is nullable
ingres_field_precision -- Get the precision of a field
ingres_field_scale -- Get the scale of a field
ingres_field_type --  Get the type of a field in a query result
ingres_num_fields --  Get the number of fields returned by the last query
ingres_num_rows --  Get the number of rows affected or returned by the last query
ingres_pconnect --  Open a persistent connection to an Ingres II database
ingres_query -- Send a SQL query to Ingres II
ingres_rollback -- Roll back a transaction

ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link] )

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

ingres_close

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link] )

Returns TRUE on success, or FALSE on failure.

ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.

ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.

See also ingres_connect() and ingres_pconnect().

ingres_commit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link] )

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

ingres_connect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_connect --  Open a connection to an Ingres II database

Description

resource ingres_connect ( [string database [, string username [, string password]]] )

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.

Esempio 1. ingres_connect() example

<?php
    $link = ingres_connect("mydb", "user", "pass")
        or die("Could not connect");
    echo "Connected successfully";
    ingres_close($link);
?>

Esempio 2. ingres_connect() example using default link

<?php
    ingres_connect("mydb", "user", "pass")
        or die("Could not connect");
    echo "Connected successfully";
    ingres_close();
?>

See also ingres_pconnect() and ingres_close().

ingres_cursor

(PECL)

ingres_cursor -- Gets a cursor name for a given link resource

Description

string ingres_cursor ( [resource link] )

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.

Esempio 1. ingres_cursor() example

<?php
$link = ingres_connect($database, $user, $password);

ingres_prepare("select * from table", $link);

$cursor_name = ingres_cursor($link);

echo $cursor_name;

?>

See also ingres_prepare() and ingres_execute().

ingres_errno

(PECL)

ingres_errno -- Gets the last ingres error number generated

Description

int ingres_errno ( [resource link] )

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

<?php
$link = ingres_connect($database, $user, $password);

ingres_query("select * from table", $link);

$error_code = ingres_errno($link);

if ( $error_code != 0 ) {
   echo "An error occured - " . $error_code;
}
?>

See also ingres_error() and ingres_errsqlstate().

ingres_error

(PECL)

ingres_error -- Gets a meaningful error message for the last error generated

Description

string ingres_error ( [resource link] )

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.

Esempio 1. ingres_error() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");

$error_text = ingres_error();

if ( is_null($error_text) ) {
   echo "An error occured - " . $error_text;
}
?>

See also ingres_errno() and ingres_errsqlstate().

ingres_errsqlstate

(PECL)

ingres_errsqlstate -- Gets the last SQLSTATE error code generated

Description

string ingres_errsqlstate ( [resource link] )

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.

Esempio 1. ingres_errsqlstate() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");

$error_sqlstate = ingres_errsqlstate();

if ( is_null($error_sqlstate) ) {
   echo "An error occured - " . $error_sqlstate;
}
?>

See also ingres_errno() and ingres_errsqlstate().

ingres_fetch_array

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]] )

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

Esempio 1. ingres_fetch_array() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_array()) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().

ingres_fetch_object

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_fetch_object -- Fetch a row of result into an object

Description

object ingres_fetch_object ( [int result_type [, resource link]] )

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

Esempio 1. ingres_fetch_object() example

<?php
ingres_connect($database, $user, $password);
ingres_query("select * from table");
while ($row = ingres_fetch_object()) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().

ingres_fetch_row

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_fetch_row --  Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link] )

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.

Esempio 1. ingres_fetch_row() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().

ingres_field_length

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link] )

ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_name -- Get the name of a field in a query result

Description

string ingres_field_name ( int index [, resource link] )

ingres_field_name() returns the name of a field in a query result, or FALSE on failure.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().

ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link] )

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_precision

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link] )

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_scale

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link] )

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_type

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_field_type --  Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link] )

ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE", "IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_num_fields --  Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link] )

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_rows

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_num_rows --  Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link] )

For delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

Nota: This function is mainly meant to get the number of rows modified in the database. If this function is called before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's data and the script won't be able to get them.

You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_pconnect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_pconnect --  Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]] )

Returns a Ingres II link resource on success, or FALSE on failure.

See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.

See also ingres_connect() and ingres_close().

ingres_query

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link] )

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:

Esempio 1. ingres_query() example

<?php
ingres_connect($database, $user, $password);

ingres_query("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().

ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link] )

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

LX. IRC Gateway Functions

Introduzione

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.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
ircg_channel_mode --  Set channel mode flags for user
ircg_disconnect --  Close connection to server
ircg_eval_ecmascript_params -- Decodes a list of JS-encoded parameters
ircg_fetch_error_msg --  Returns the error from previous IRCG operation
ircg_get_username --  Get username for connection
ircg_html_encode --  Encodes HTML preserving output
ircg_ignore_add --  Add a user to your ignore list on a server
ircg_ignore_del --  Remove a user from your ignore list on a server
ircg_invite -- Invites nickname to channel
ircg_is_conn_alive --  Check connection status
ircg_join --  Join a channel on a connected server
ircg_kick --  Kick a user out of a channel on server
ircg_list -- List topic/user count of channel(s)
ircg_lookup_format_messages --  Check for the existence of a format message set
ircg_lusers -- IRC network statistics
ircg_msg --  Send message to channel or user on server
ircg_names -- Query visible usernames
ircg_nick --  Change nickname on server
ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant
ircg_nickname_unescape --  Decodes encoded nickname
ircg_notice --  Send a notice to a user on server
ircg_oper -- Elevates privileges to IRC OPER
ircg_part --  Leave a channel on server
ircg_pconnect --  Connect to an IRC server
ircg_register_format_messages --  Register a format message set
ircg_set_current --  Set current connection for output
ircg_set_file --  Set logfile for connection
ircg_set_on_die --  Set action to be executed when connection dies
ircg_topic --  Set topic for channel on server
ircg_who -- Queries server for WHO information
ircg_whois --  Query server for user information

ircg_channel_mode

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_channel_mode --  Set channel mode flags for user

Description

bool ircg_channel_mode ( resource connection, string channel, string mode_spec, string nick )

Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.

Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively. E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.

ircg_disconnect

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_disconnect --  Close connection to server

Description

bool ircg_disconnect ( resource connection, string reason )

ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().

See also: ircg_pconnect().

ircg_eval_ecmascript_params

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)

ircg_eval_ecmascript_params -- Decodes a list of JS-encoded parameters

Description

array ircg_eval_ecmascript_params ( string params )

Avvertimento

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

ircg_fetch_error_msg

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

ircg_fetch_error_msg --  Returns the error from previous IRCG operation

Description

array ircg_fetch_error_msg ( resource connection )

ircg_fetch_error_msg() returns the error from a failed connection.

Nota: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply codes as defined by RFC 2812.

Esempio 1. ircg_fetch_error_msg() example

<?php
if (!ircg_join ($id, "#php")) {
    $error = ircg_fetch_error_msg($id);
    echo "Can't join channel #php. Error code: 
          $error[0] Description: $error[1]";
}
?>

ircg_get_username

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)

ircg_get_username --  Get username for connection

Description

string ircg_get_username ( resource connection )

Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.

ircg_html_encode

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_html_encode --  Encodes HTML preserving output

Description

string ircg_html_encode ( string html_string [, bool auto_links [, bool conv_br]] )

Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.

ircg_ignore_add

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_ignore_add --  Add a user to your ignore list on a server

Description

void ircg_ignore_add ( resource connection, string nick )

This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from this user through the associated connection.

See also: ircg_ignore_del().

ircg_ignore_del

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_ignore_del --  Remove a user from your ignore list on a server

Description

bool ircg_ignore_del ( resource connection, string nick )

This function removes user nick from the IRCG ignore list associated with connection.

See also: ircg_ignore_add().

ircg_invite

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_invite -- Invites nickname to channel

Description

bool ircg_invite ( resource connection, string channel, string nickname )

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

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_is_conn_alive --  Check connection status

Description

bool ircg_is_conn_alive ( resource connection )

ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.

ircg_join

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_join --  Join a channel on a connected server

Description

bool ircg_join ( resource connection, string channel [, string key] )

Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.

ircg_kick

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_kick --  Kick a user out of a channel on server

Description

bool ircg_kick ( resource connection, string channel, string nick, string reason )

Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.

ircg_list

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_list -- List topic/user count of channel(s)

Description

bool ircg_list ( resource connection, string channel )

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

<?php

// connect to server
$id = ircg_pconnect($nickname, $ip, $port);

// set to output to a file
ircg_set_file($id, 'irc_output.html');

// try to join a channel
if (!ircg_join($id, $channel)) {
    echo "Cannot /join $channel<br />";
}

// send list command
ircg_list($id, $channel);

// wait for output to arrive
sleep(5);

// disconnect
ircg_disconnect($id,'Bye World');

// output everything
readfile('irc_output.html');

?>

This example will output something similar to:

...
Channel #channel has n users and the topic is 'Topic'
End of LIST
...

See also: ircg_set_file(), ircg_set_current(), and ircg_who().

ircg_lookup_format_messages

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_lookup_format_messages --  Check for the existence of a format message set

Description

bool ircg_lookup_format_messages ( string name )

Check for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.

See also: ircg_register_format_messages()

ircg_lusers

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_lusers -- IRC network statistics

Description

bool ircg_lusers ( resource connection )

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

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_msg --  Send message to channel or user on server

Description

bool ircg_msg ( resource connection, string recipient, string message [, bool suppress] )

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.

ircg_names

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_names -- Query visible usernames

Description

bool ircg_names ( int connection, string channel [, string target] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

See also ircg_get_username() and ircg_lusers().

ircg_nick

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_nick --  Change nickname on server

Description

bool ircg_nick ( resource connection, string nick )

Change your nickname on the given connection to the one given in nick, if possible.

Will return TRUE on success and FALSE on failure.

ircg_nickname_escape

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant

Description

string ircg_nickname_escape ( string nick )

Function ircg_nickname_escape() returns an encoded nickname specified by nick which is IRC-compliant.

See also: ircg_nickname_unescape()

ircg_nickname_unescape

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

ircg_nickname_unescape --  Decodes encoded nickname

Description

string ircg_nickname_unescape ( string nick )

Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.

See also: ircg_nickname_escape()

ircg_notice

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_notice --  Send a notice to a user on server

Description

bool ircg_notice ( resource connection, string recipient, string message )

This function will send the message text to the user nick on the server connected to by connection. IRC servers and other software will not automatically generate replies to NOTICEs in contrast to other message types.

ircg_oper

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_oper -- Elevates privileges to IRC OPER

Description

bool ircg_oper ( resource connection, string name, string password )

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.

ircg_part

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_part --  Leave a channel on server

Description

bool ircg_part ( resource connection, string channel )

Leave the channel channel on the server connected to by connection.

ircg_pconnect

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_pconnect --  Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings [, bool bailout_on_trivial]]]]]] )

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

Nota: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.

You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.

If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.

You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.

See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().

ircg_register_format_messages

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_register_format_messages --  Register a format message set

Description

bool ircg_register_format_messages ( string name, array messages )

With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions are invoked on the client side.

  • Plain channel message

  • Private message received

  • Private message sent

  • Some user leaves channel

  • Some user enters channel

  • Some user was kicked from the channel

  • Topic has been changed

  • Error

  • Fatal error

  • Join list end(?)

  • Self part(?)

  • Some user changes his nick

  • Some user quits his connection

  • Mass join begin

  • Mass join element

  • Mass join end

  • Whois user

  • Whois server

  • Whois idle

  • Whois channel

  • Whois end

  • Voice status change on user

  • Operator status change on user

  • Banlist

  • Banlist end

  • %f - from

  • %t - to

  • %c - channel

  • %r - plain message

  • %m - encoded message

  • %j - js encoded message

  • 1 - mod encode

  • 2 - nickname decode

See also: ircg_lookup_format_messages().

ircg_set_current

(PHP 4 >= 4.0.4, PHP 5 <= 5.0.4)

ircg_set_current --  Set current connection for output

Description

bool ircg_set_current ( resource connection )

Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().

See also: ircg_register_format_messages().

ircg_set_file

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

ircg_set_file --  Set logfile for connection

Description

bool ircg_set_file ( resource connection, string path )

Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.

ircg_set_on_die

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

ircg_set_on_die --  Set action to be executed when connection dies

Description

bool ircg_set_on_die ( resource connection, string host, int port, string data )

In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.

This feature requires IRCG 3.

ircg_topic

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_topic --  Set topic for channel on server

Description

bool ircg_topic ( resource connection, string channel, string new_topic )

Change the topic for channel channel on the server connected to by connection to new_topic.

ircg_who

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

ircg_who -- Queries server for WHO information

Description

bool ircg_who ( resource connection, string mask [, bool ops_only] )

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

ircg_whois

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

ircg_whois --  Query server for user information

Description

bool ircg_whois ( resource connection, string nick )

Sends a query to the connected server connection to ask for information about the specified user nick.

LXI. PHP / Java Integration

Introduzione

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.


Requisiti

You need a Java VM installed on your machine to use this extension.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Java configuration options

NameDefaultChangeableChangelog
java.class.pathNULLPHP_INI_ALL 
java.homeNULLPHP_INI_ALL 
java.library.pathNULLPHP_INI_ALL 
java.libraryJAVALIBPHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Esempio 1. Java Example

<?php
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');

// demonstrate property access
echo 'Java version=' . $system->getProperty('java.version') . '<br />';
echo 'Java vendor=' . $system->getProperty('java.vendor') . '<br />';
echo 'OS=' . $system->getProperty('os.name') . ' ' .
             $system->getProperty('os.version') . ' on ' .
             $system->getProperty('os.arch') . ' <br />';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
                      "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

echo $formatter->format(new Java('java.util.Date'));
?>

Esempio 2. AWT Example

<?php
// This example is only intended to be run as a CGI.

$frame  = new Java('java.awt.Frame', 'PHP');
$button = new Java('java.awt.Button', 'Hello Java World!');

$frame->add('North', $button);
$frame->validate();
$frame->pack();
$frame->visible = True;

$thread = new Java('java.lang.Thread');
$thread->sleep(10000);

$frame->dispose();
?>
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are 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.


Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary 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.

Sommario
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception

java_last_exception_clear

(PHP 4 >= 4.0.2, PECL)

java_last_exception_clear -- Clear last Java exception

Description

void java_last_exception_clear ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

java_last_exception_get

(PHP 4 >= 4.0.2, PECL)

java_last_exception_get -- Get last Java exception

Description

object java_last_exception_get ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
$stack = new Java('java.util.Stack');
$stack->push(1);

// This should succeed
$result = $stack->pop();
$ex = java_last_exception_get();
if (!$ex) {
  echo "$result\n";
}

// This should fail (error suppressed by @)
$result = @$stack->pop();
$ex = java_last_exception_get();
if ($ex) {
  echo $ex->toString();
}

// Clear last exception
java_last_exception_clear();
?>

LXII. KADM5

Introduzione

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.


Costanti predefinite

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.


Constants for Attribute Flags

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


Constants for Options

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

constantfuncdefdescription
KADM5_PRINCIPALlongThe expire time of the princial as a Kerberos timestamp.
KADM5_PRINC_EXPIRE_TIMElongThe expire time of the princial as a Kerberos timestamp.
KADM5_LAST_PW_CHANGElongThe time this principal's password was last changed.
KADM5_PW_EXPIRATIONlong The expire time of the principal's current password, as a Kerberos timestamp.
KADM5_MAX_LIFElong The maximum lifetime of any Kerberos ticket issued to this principal.
KADM5_MAX_RLIFElong The maximum renewable lifetime of any Kerberos ticket issued to or for this principal.
KADM5_MOD_NAMEstring The name of the Kerberos principal that most recently modified this principal.
KADM5_MOD_TIMElong The time this principal was last modified, as a Kerberos timestamp.
KADM5_KVNOlongThe version of the principal's current key.
KADM5_POLICYstringThe name of the policy controlling this principal.
KADM5_CLEARPOLICYlong Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour.
KADM5_LAST_SUCCESSlongThe KDC time of the last successfull AS_REQ.
KADM5_LAST_FAILEDlongThe KDC time of the last failed AS_REQ.
KADM5_FAIL_AUTH_COUNTlongThe number of consecutive failed AS_REQs.
KADM5_RANDKEYlong Generates a random password for the principal. The parameter password will be ignored.
KADM5_ATTRIBUTESlongA bitfield of attributes for use by the KDC.


Esempi

This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Esempio 1. KADM5 extension overview example

<?php

  $handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

  print "<h1>get_principals</h1>\n";
  $principals = kadm5_get_principals($handle);
  for( $i=0; $i<count($principals); $i++)
      print "$principals[$i]<br>\n";

  print "<h1>get_policies</h1>\n";
  $policies = kadm5_get_policies($handle);
  for( $i=0; $i<count($policies); $i++)
      print "$policies[$i]<br>\n";

  print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

  $options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
  $keys = array_keys($options);
  for( $i=0; $i<count($keys); $i++) {
    $value = $options[$keys[$i]];
    print "$keys[$i]: $value<br>\n";
  }

  $options = array(KADM5_PRINC_EXPIRE_TIME => 0);
  kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

  kadm5_destroy($handle);
?>


Contact Information

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.

Sommario
kadm5_chpass_principal -- Changes the principal's password
kadm5_create_principal -- Creates a kerberos principal with the given parameters
kadm5_delete_principal -- Deletes a kerberos principal
kadm5_destroy -- Closes the connection to the admin server and releases all related resources
kadm5_flush -- Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open
kadm5_get_policies -- Gets all policies from the Kerberos database
kadm5_get_principal -- Gets the principal's entries from the Kerberos database
kadm5_get_principals -- Gets all principals from the Kerberos database
kadm5_init_with_password -- Opens a connection to the KADM5 library and initializes any neccessary state information
kadm5_modify_principal -- Modifies a kerberos principal with the given parameters

kadm5_chpass_principal

(PECL)

kadm5_chpass_principal -- Changes the principal's password

Descrizione

bool kadm5_chpass_principal ( resource handle, string principal, string password )

kadm5_chpass_principal() sets the new password password for the principal.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Example of changing principal's password

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");

kadm5_destroy($handle);
?>

kadm5_create_principal

(PECL)

kadm5_create_principal -- Creates a kerberos principal with the given parameters

Descrizione

bool kadm5_create_principal ( resource handle, string principal [, string password [, array options]] )

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Example of principal's creation

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

kadm5_delete_principal

(PECL)

kadm5_delete_principal -- Deletes a kerberos principal

Descrizione

bool kadm5_delete_principal ( resource handle, string principal )

kadm5_delete_principal() remove the principal from the Kerberos database.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. kadm5_delete_principal() example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?>

kadm5_destroy

(PECL)

kadm5_destroy -- Closes the connection to the admin server and releases all related resources

Descrizione

bool kadm5_destroy ( resource handle )

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

kadm5_flush

(PECL)

kadm5_flush -- Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open

Descrizione

bool kadm5_flush ( resource handle )

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

kadm5_get_policies

(PECL)

kadm5_get_policies -- Gets all policies from the Kerberos database

Descrizione

array kadm5_get_policies ( resource handle )

kadm5_get_policies() returns an array containing the policies's names.

Valori restituiti

Returns array of policies on success, or FALSE on failure.

Esempi

Esempio 1. kadm5_get_policies() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
    echo "$policy<br />\n";
}

kadm5_destroy($handle);
?>

kadm5_get_principal

(PECL)

kadm5_get_principal -- Gets the principal's entries from the Kerberos database

Descrizione

array kadm5_get_principal ( resource handle, string principal )

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.

Valori restituiti

Returns array of options on success, or FALSE on failure.

Esempi

Esempio 1. kadm5_get_principal() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );

foreach ($options as $key => $value) {
    echo "$key: $value<br />\n";
}

kadm5_destroy($handle);
?>

kadm5_get_principals

(PECL)

kadm5_get_principals -- Gets all principals from the Kerberos database

Descrizione

array kadm5_get_principals ( resource handle )

kadm5_get_principals() returns an array containing the principals's names.

Valori restituiti

Returns array of principals on success, or FALSE on failure.

Esempi

Esempio 1. kadm5_get_principals() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
    echo "$principal<br />\n";
}

kadm5_destroy($handle);
?>

kadm5_init_with_password

(PECL)

kadm5_init_with_password -- Opens a connection to the KADM5 library and initializes any neccessary state information

Descrizione

resource kadm5_init_with_password ( string admin_server, string realm, string principal, string password )

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

Valori restituiti

Returns a KADM5 handle on success, or FALSE on failure.

Esempi

Esempio 1. KADM5 initialization example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

Note

Nota: Connection should be closed after use with kadm5_destroy().

Vedere anche:

kadm5_destroy()

kadm5_modify_principal

(PECL)

kadm5_modify_principal -- Modifies a kerberos principal with the given parameters

Descrizione

bool kadm5_modify_principal ( resource handle, string principal, array options )

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Example of modifying principal

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
                 KADM5_POLICY => "gonicus",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

LXIII. LDAP Functions

Introduzione

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.


Requisiti

You will need to get and compile LDAP client libraries from either OpenLDAP or Bind9.net in order to compile PHP with LDAP support.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. LDAP configuration options

NameDefaultChangeableChangelog
ldap.max_links"-1"PHP_INI_SYSTEM 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

LDAP_DEREF_NEVER (integer)

LDAP_DEREF_SEARCHING (integer)

LDAP_DEREF_FINDING (integer)

LDAP_DEREF_ALWAYS (integer)

LDAP_OPT_DEREF (integer)

LDAP_OPT_SIZELIMIT (integer)

LDAP_OPT_TIMELIMIT (integer)

LDAP_OPT_PROTOCOL_VERSION (integer)

LDAP_OPT_ERROR_NUMBER (integer)

LDAP_OPT_REFERRALS (integer)

LDAP_OPT_RESTART (integer)

LDAP_OPT_HOST_NAME (integer)

LDAP_OPT_ERROR_STRING (integer)

LDAP_OPT_MATCHED_DN (integer)

LDAP_OPT_SERVER_CONTROLS (integer)

LDAP_OPT_CLIENT_CONTROLS (integer)

LDAP_OPT_DEBUG_LEVEL (integer)

GSLC_SSL_NO_AUTH (integer)

GSLC_SSL_ONEWAY_AUTH (integer)

GSLC_SSL_TWOWAY_AUTH (integer)


Esempi

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

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is " . $ds . "<br />";

if ($ds) { 
    echo "Binding ..."; 
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is " . $r . "<br />";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");  
    echo "Search result is " . $sr . "<br />";

    echo "Number of entires returned is " . ldap_count_entries($ds, $sr) . "<br />";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for " . $info["count"] . " items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: " . $info[$i]["dn"] . "<br />";
        echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
        echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:


  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"

Sommario
ldap_8859_to_t61 --  Translate 8859 characters to t61 characters
ldap_add -- Add entries to LDAP directory
ldap_bind -- Bind to LDAP directory
ldap_close -- Alias di ldap_unbind()
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str --  Convert LDAP error number into string error message
ldap_errno --  Return the LDAP error number of the last LDAP command
ldap_error --  Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_first_reference --  Return first reference
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values_len -- Get all binary values from a result entry
ldap_get_values -- Get all values from a result entry
ldap_list -- Single-level search
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_modify -- Modify an LDAP entry
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_next_reference --  Get next reference
ldap_parse_reference --  Extract information from reference entry
ldap_parse_result --  Extract information from result
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_sasl_bind --  Bind to LDAP directory using SASL
ldap_search -- Search LDAP tree
ldap_set_option -- Set the value of the given option
ldap_set_rebind_proc --  Set a callback function to do re-binds on referral chasing
ldap_sort --  Sort LDAP result entries
ldap_start_tls --  Start TLS
ldap_t61_to_8859 --  Translate t61 characters to 8859 characters
ldap_unbind -- Unbind from LDAP directory

ldap_8859_to_t61

(PHP 4 >= 4.0.2, PHP 5)

ldap_8859_to_t61 --  Translate 8859 characters to t61 characters

Description

string ldap_8859_to_t61 ( string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_add

(PHP 3, PHP 4, PHP 5)

ldap_add -- Add entries to LDAP directory

Description

bool ldap_add ( resource link_identifier, string dn, array entry )

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

<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"]="John Jones";
    $info["sn"]="Jones";
    $info["mail"]="jonj@example.com";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server"; 
}
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

ldap_bind

(PHP 3, PHP 4, PHP 5)

ldap_bind -- Bind to LDAP directory

Description

bool ldap_bind ( resource link_identifier [, string bind_rdn [, string bind_password]] )

Binds to the LDAP directory with specified RDN and password. 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

<?php

// using ldap bind
$ldaprdn  = 'uname';     // ldap rdn or dn
$ldappass = 'password';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }
        
}

?>

Esempio 2. Using LDAP Bind Anonymously

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";
    } else {
        echo "LDAP bind anonymous failed...";
    }
 
}
    
?>

ldap_close

(PHP 3, PHP 4, PHP 5)

ldap_close -- Alias di ldap_unbind()

Descrizione

This function is an alias of: ldap_unbind().

ldap_compare

(PHP 4 >= 4.0.2, PHP 5)

ldap_compare -- Compare value of attribute found in entry specified with DN

Description

mixed ldap_compare ( resource link_identifier, string dn, string attribute, string value )

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Esempio 1. Complete example of password check

<?php

$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host
      
if ($ds) {

    // bind 
    if (ldap_bind($ds)) {

        // prepare data
        $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";
        $value = "secretpassword";
        $attr = "password"; 

        // compare value
        $r=ldap_compare($ds, $dn, $attr, $value);

        if ($r === -1) {
            echo "Error: " . ldap_error($ds);
        } elseif ($r === true) {
            echo "Password correct.";
        } elseif ($r === false) {
            echo "Wrong guess! Password incorrect.";
        }

    } else {
        echo "Unable to bind to LDAP server.";
    }          

    ldap_close($ds);

} else {
    echo "Unable to connect to LDAP server.";
}
?>

Avvertimento

ldap_compare() can NOT be used to compare BINARY values!

Nota: This function was added in 4.0.2.

ldap_connect

(PHP 3, PHP 4, PHP 5)

ldap_connect -- Connect to an LDAP server

Description

resource ldap_connect ( [string hostname [, int port]] )

Returns a positive LDAP link identifier on success, or FALSE on error. 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.

Esempio 1. Example of connecting to LDAP server.

<?php

// LDAP variables
$ldaphost = "ldap.example.com";  // your ldap servers
$ldapport = 389;                 // your ldap server's port number

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost, $ldapport) 
          or die("Could not connect to $ldaphost");

?>

Esempio 2. Example of connecting securely to LDAP server.

<?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost) 
          or die("Could not connect to {$ldaphost}");

?>

See also ldap_bind().

ldap_count_entries

(PHP 3, PHP 4, PHP 5)

ldap_count_entries -- Count the number of entries in a search

Description

int ldap_count_entries ( resource link_identifier, resource result_identifier )

Returns number of entries in the result or FALSE on error.

ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.

ldap_delete

(PHP 3, PHP 4, PHP 5)

ldap_delete -- Delete an entry from a directory

Description

bool ldap_delete ( resource link_identifier, string dn )

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

(PHP 3, PHP 4, PHP 5)

ldap_dn2ufn -- Convert DN to User Friendly Naming format

Description

string ldap_dn2ufn ( string dn )

ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.

ldap_err2str

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ldap_err2str --  Convert LDAP error number into string error message

Description

string ldap_err2str ( int errno )

Returns string error message.

This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

See also ldap_errno() and ldap_error().

Esempio 1. Enumerating all LDAP error messages

<?php
  for ($i=0; $i<100; $i++) {
    printf("Error $i: %s<br />\n", ldap_err2str($i));
  }
?>

ldap_errno

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

ldap_errno --  Return the LDAP error number of the last LDAP command

Description

int ldap_errno ( resource link_identifier )

Return the LDAP error number of the last LDAP command for this link.

This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Esempio 1. Generating and catching an error

<?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    echo "LDAP-Errno: " . ldap_errno($ld) . "<br />\n";
    echo "LDAP-Error: " . ldap_error($ld) . "<br />\n";
    die("Argh!<br />\n");
}
$info = ldap_get_entries($ld, $res);
echo $info["count"] . " matching entries.<br />\n";
?>

See also ldap_err2str() and ldap_error().

ldap_error

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

ldap_error --  Return the LDAP error message of the last LDAP command

Description

string ldap_error ( resource link_identifier )

Returns string error message.

This function returns the string error message explaining the error generated by the last LDAP command for the given link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

See also ldap_err2str() and ldap_errno().

ldap_explode_dn

(PHP 3, PHP 4, PHP 5)

ldap_explode_dn -- Splits DN into its component parts

Description

array ldap_explode_dn ( string dn, int with_attrib )

ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.

ldap_first_attribute

(PHP 3, PHP 4, PHP 5)

ldap_first_attribute -- Return first attribute

Description

string ldap_first_attribute ( resource link_identifier, resource result_entry_identifier, int &ber_identifier )

Returns the first attribute in the entry on success and FALSE on error.

Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.

See also ldap_get_attributes()

ldap_first_entry

(PHP 3, PHP 4, PHP 5)

ldap_first_entry -- Return first result id

Description

resource ldap_first_entry ( resource link_identifier, resource result_identifier )

Returns the result entry identifier for the first entry on success and FALSE on error.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.

See also ldap_get_entries().

ldap_first_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_first_reference --  Return first reference

Description

resource ldap_first_reference ( resource link, resource result )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_free_result

(PHP 3, PHP 4, PHP 5)

ldap_free_result -- Free result memory

Description

bool ldap_free_result ( resource result_identifier )

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.

ldap_get_attributes

(PHP 3, PHP 4, PHP 5)

ldap_get_attributes -- Get attributes from a search result entry

Description

array ldap_get_attributes ( resource link_identifier, resource result_entry_identifier )

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.

Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.

return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute

return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute

Esempio 1. Show the list of attributes held for a particular directory entry

<?php
// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = ldap_get_attributes($ds, $entry);

echo $attrs["count"] . " attributes held for this entry:<p>";

for ($i=0; $i<$attrs["count"]; $i++) {
    echo $attrs[$i] . "<br />";
}
?>

See also ldap_first_attribute() and ldap_next_attribute().

ldap_get_dn

(PHP 3, PHP 4, PHP 5)

ldap_get_dn -- Get the DN of a result entry

Description

string ldap_get_dn ( resource link_identifier, resource result_entry_identifier )

Returns the DN of the result entry and FALSE on error.

ldap_get_dn() function is used to find out the DN of an entry in the result.

ldap_get_entries

(PHP 3, PHP 4, PHP 5)

ldap_get_entries -- Get all result entries

Description

array ldap_get_entries ( resource link_identifier, resource result_identifier )

Returns a complete result information in a multi-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().

ldap_get_option

(PHP 4 >= 4.0.4, PHP 5)

ldap_get_option -- Get the current value for given option

Description

bool ldap_get_option ( resource link_identifier, int option, mixed &retval )

Sets retval to the value of the specified option. 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

Esempio 1. Check protocol version

<?php
// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version)) {
    echo "Using protocol version $version\n";
} else {
    echo "Unable to determine protocol version\n";
}
?>

See also ldap_set_option().

ldap_get_values_len

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

ldap_get_values_len -- Get all binary values from a result entry

Description

array ldap_get_values_len ( resource link_identifier, resource result_entry_identifier, string attribute )

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

Nota: This function was added in 4.0.

ldap_get_values

(PHP 3, PHP 4, PHP 5)

ldap_get_values -- Get all values from a result entry

Description

array ldap_get_values ( resource link_identifier, resource result_entry_identifier, string attribute )

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.

You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.

LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"


return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute

Esempio 1. List all values of the "mail" attribute for a directory entry

<?php
// $ds is a valid link identifier for a directory server

// $sr is a valid search result from a prior call to
//     one of the ldap directory search calls

// $entry is a valid entry identifier from a prior call to
//        one of the calls that returns a directory entry

$values = ldap_get_values($ds, $entry, "mail");

echo $values["count"] . " email addresses for this entry.<br />";

for ($i=0; $i < $values["count"]; $i++) {
    echo $values[$i] . "<br />";
}
?>

ldap_list

(PHP 3, PHP 4, PHP 5)

ldap_list -- Single-level search

Description

resource ldap_list ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )

Returns a search result identifier or FALSE on error.

ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

This call takes 5 optional parameters. See ldap_search() notes.

Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

Esempio 1. Produce a list of all organizational units of an organization

// $ds is a valid link identifier for a directory server

$basedn = "o=My Company, c=US";
$justthese = array("ou");

$sr=ldap_list($ds, $basedn, "ou=*", $justthese);

$info = ldap_get_entries($ds, $sr);

for ($i=0; $i<$info["count"]; $i++) {
    echo $info[$i]["ou"][0] ;
}

Nota: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

ldap_mod_add

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

ldap_mod_add -- Add attribute values to current attributes

Description

bool ldap_mod_add ( resource link_identifier, string dn, array entry )

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)

ldap_mod_del

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

ldap_mod_del -- Delete attribute values from current attributes

Description

bool ldap_mod_del ( resource link_identifier, string dn, array entry )

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.

ldap_mod_replace

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

ldap_mod_replace -- Replace attribute values with new ones

Description

bool ldap_mod_replace ( resource link_identifier, string dn, array entry )

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)

ldap_modify

(PHP 3, PHP 4, PHP 5)

ldap_modify -- Modify an LDAP entry

Description

bool ldap_modify ( resource link_identifier, string dn, array entry )

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)

ldap_next_attribute

(PHP 3, PHP 4, PHP 5)

ldap_next_attribute -- Get the next attribute in result

Description

string ldap_next_attribute ( resource link_identifier, resource result_entry_identifier, resource &ber_identifier )

Returns the next attribute in an entry on success and FALSE on error.

ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

See also ldap_get_attributes()

ldap_next_entry

(PHP 3, PHP 4, PHP 5)

ldap_next_entry -- Get next result entry

Description

resource ldap_next_entry ( resource link_identifier, resource result_entry_identifier )

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.

ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().

See also ldap_get_entries()

ldap_next_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_next_reference --  Get next reference

Description

resource ldap_next_reference ( resource link, resource entry )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_parse_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_reference --  Extract information from reference entry

Description

bool ldap_parse_reference ( resource link, resource entry, array &referrals )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_result --  Extract information from result

Description

bool ldap_parse_result ( resource link, resource result, int &errcode [, string &matcheddn [, string &errmsg [, array &referrals]]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_read

(PHP 3, PHP 4, PHP 5)

ldap_read -- Read an entry

Description

resource ldap_read ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )

Returns a search result identifier or FALSE on error.

ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".

This call takes 5 optional parameters. See ldap_search() notes.

Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

ldap_rename

(PHP 4 >= 4.0.5, PHP 5)

ldap_rename -- Modify the name of an entry

Description

bool ldap_rename ( resource link_identifier, string dn, string newrdn, string newparent, bool deleteoldrdn )

The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. 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.

ldap_sasl_bind

(PHP 5)

ldap_sasl_bind --  Bind to LDAP directory using SASL

Description

bool ldap_sasl_bind ( resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authz_id [, string props]]]]]] )

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.

ldap_search

(PHP 3, PHP 4, PHP 5)

ldap_search -- Search LDAP tree

Description

resource ldap_search ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]] )

Returns a search result identifier or FALSE on error.

ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.

There is 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

<?php
// $ds is a valid link identifier for a directory server

// $person is all or part of a person's name, eg "Jo"

$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array("ou", "sn", "givenname", "mail");

$sr=ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

echo $info["count"]." entries returned\n";
?>

From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.

ldap_set_option

(PHP 4 >= 4.0.4, PHP 5)

ldap_set_option -- Set the value of the given option

Description

bool ldap_set_option ( resource link_identifier, int option, mixed newval )

Sets the value of the specified option to be newval. 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 1. Set protocol version

<?php
// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
    echo "Using LDAPv3";
} else {
    echo "Failed to set protocol version to 3";
}
?>

Esempio 2. Set server controls

<?php
// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => true);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2)))
    echo "Failed to set server controls";
?>

See also ldap_get_option().

ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5)

ldap_set_rebind_proc --  Set a callback function to do re-binds on referral chasing

Description

bool ldap_set_rebind_proc ( resource link, callback callback )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_sort

(PHP 4 >= 4.2.0, PHP 5)

ldap_sort --  Sort LDAP result entries

Description

bool ldap_sort ( resource link, resource result, string sortfilter )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_start_tls

(PHP 4 >= 4.2.0, PHP 5)

ldap_start_tls --  Start TLS

Description

bool ldap_start_tls ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_t61_to_8859

(PHP 4 >= 4.0.2, PHP 5)

ldap_t61_to_8859 --  Translate t61 characters to 8859 characters

Description

string ldap_t61_to_8859 ( string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ldap_unbind

(PHP 3, PHP 4, PHP 5)

ldap_unbind -- Unbind from LDAP directory

Description

bool ldap_unbind ( resource link_identifier )

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ldap_unbind() function unbinds from the LDAP directory.

LXIV. libxml Functions

Introduzione

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.


Requisiti

This extension requires libxml >= 2.6.0.


Classi predefinite

LibXMLError

Proprietà

  • 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


Costanti predefinite

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.

LIBXML_COMPACT (integer)

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

LIBXML_DTDATTR (integer)

Default DTD attributes

LIBXML_DTDLOAD (integer)

Load the external subset

LIBXML_DTDVALID (integer)

Validate with the DTD

LIBXML_NOBLANKS (integer)

Remove blank nodes

LIBXML_NOCDATA (integer)

Merge CDATA as text nodes

LIBXML_NOEMPTYTAG (integer)

Expand empty tags (e.g. <br/> to <br></br>)

Nota: This option is currently just available in the DOMDocument->save() and DOMDocument->saveXML() functions.

LIBXML_NOENT (integer)

Substitute entities

LIBXML_NOERROR (integer)

Suppress error reports

LIBXML_NONET (integer)

Disable network access when loading documents

LIBXML_NOWARNING (integer)

Suppress warning reports

LIBXML_NOXMLDECL (integer)

Drop the XML declaration when saving a document

Nota: Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)

Remove redundant namespaces declarations

LIBXML_XINCLUDE (integer)

Implement XInclude substitution

LIBXML_ERR_ERROR (integer)

A recoverable error

LIBXML_ERR_FATAL (integer)

A fatal error

LIBXML_ERR_NONE (integer)

No errors

LIBXML_ERR_WARNING (integer)

A simple warning

LIBXML_VERSION (integer)

libxml version like 20605 or 20617

LIBXML_DOTTED_VERSION (string)

libxml version like 2.6.5 or 2.6.17

Sommario
libxml_clear_errors --  Clear libxml error buffer
libxml_get_errors --  Retrieve array of errors
libxml_get_last_error --  Retrieve last error from libxml
libxml_set_streams_context --  Set the streams context for the next libxml document load or write
libxml_use_internal_errors --  Disable libxml errors and allow user to fetch error information as needed

libxml_clear_errors

(PHP 5 >= 5.1.0RC1)

libxml_clear_errors --  Clear libxml error buffer

Descrizione

void libxml_clear_errors ( void )

libxml_clear_errors() clears the libxml error buffer.

Valori restituiti

No value is returned.

libxml_get_errors

(PHP 5 >= 5.1.0RC1)

libxml_get_errors --  Retrieve array of errors

Descrizione

array libxml_get_errors ( void )

Retrieve array of errors.

Valori restituiti

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Esempi

Esempio 1. A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}


function display_xml_error($error, $xml)
{
    $return  = $xml[$error->line - 1] . "\n";
    $return .= str_repeat('-', $error->column) . "^\n";

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error->code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error->code: ";
            break;
    }

    $return .= trim($error->message) .
               "\n  Line: $error->line" .
               "\n  Column: $error->column";

    if ($error->file) {
        $return .= "\n  File: $error->file";
    }

    return "$return\n\n--------------------------------------------\n\n";
}

?>

Il precedente esempio visualizzerà:

<titles>PHP: Behind the Parser</title>
^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 0

--------------------------------------------

libxml_get_last_error

(PHP 5 >= 5.1.0RC1)

libxml_get_last_error --  Retrieve last error from libxml

Descrizione

LibXMLError libxml_get_last_error ( void )

Retrieve last error from libxml.

Valori restituiti

Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.

libxml_set_streams_context

(PHP 5)

libxml_set_streams_context --  Set the streams context for the next libxml document load or write

Descrizione

void libxml_set_streams_context ( resource streams_context )

Sets the streams context for the next libxml document load or write.

Elenco dei parametri

streams_context

The stream context resource (created with stream_context_create())

Valori restituiti

No value is returned.

Esempi

Esempio 1. A libxml_set_streams_context() example

<?php

$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

libxml_use_internal_errors

(PHP 5 >= 5.1.0RC1)

libxml_use_internal_errors --  Disable libxml errors and allow user to fetch error information as needed

Descrizione

bool libxml_use_internal_errors ( [bool use_errors] )

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

Elenco dei parametri

use_errors

Whether to enable user error handling. Defaults to FALSE.

Valori restituiti

This function returns the previous value of use_errors.

Esempi

Esempio 1. A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

<?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

$doc = DOMDocument::load('file.xml');

if (!$doc) {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        // handle errors here
    }

    libxml_clear_errors();
}

?>

Il precedente esempio visualizzerà:

bool(false)

LXV. Lotus Notes Functions

Introduzione

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.

Sommario
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_copy_db -- Copy a Lotus Notes database
notes_create_db -- Create a Lotus Notes database
notes_create_note -- Create a note using form form_name
notes_drop_db -- Drop a Lotus Notes database
notes_find_note -- Returns a note id found in database_name
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_list_msgs -- Returns the notes from a selected database_name
notes_mark_read -- Mark a note_id as read for the User user_name
notes_mark_unread -- Mark a note_id as unread for the User user_name
notes_nav_create -- Create a navigator name, in database_name
notes_search -- Find notes that match keywords in database_name
notes_unread -- Returns the unread note id's for the current User user_name
notes_version -- Get the version Lotus Notes

notes_body

(PHP 4 >= 4.0.5, PECL)

notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string server, string mailbox, int msg_number )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_copy_db

(PHP 4 >= 4.0.5, PECL)

notes_copy_db -- Copy a Lotus Notes database

Description

bool notes_copy_db ( string from_database_name, string to_database_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

notes_create_db

(PHP 4 >= 4.0.5, PECL)

notes_create_db -- Create a Lotus Notes database

Description

bool notes_create_db ( string database_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

notes_create_note

(PHP 4 >= 4.0.5, PECL)

notes_create_note -- Create a note using form form_name

Description

bool notes_create_note ( string database_name, string form_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

notes_drop_db

(PHP 4 >= 4.0.5, PECL)

notes_drop_db -- Drop a Lotus Notes database

Description

bool notes_drop_db ( string database_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

notes_find_note

(PHP 4 >= 4.0.5, PECL)

notes_find_note -- Returns a note id found in database_name

Description

int notes_find_note ( string database_name, string name [, string type] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_header_info

(PHP 4 >= 4.0.5, PECL)

notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

object notes_header_info ( string server, string mailbox, int msg_number )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_list_msgs

(PHP 4 >= 4.0.5, PECL)

notes_list_msgs -- Returns the notes from a selected database_name

Description

bool notes_list_msgs ( string db )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_mark_read

(PHP 4 >= 4.0.5, PECL)

notes_mark_read -- Mark a note_id as read for the User user_name

Description

bool notes_mark_read ( string database_name, string user_name, string note_id )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_mark_unread

(PHP 4 >= 4.0.5, PECL)

notes_mark_unread -- Mark a note_id as unread for the User user_name

Description

bool notes_mark_unread ( string database_name, string user_name, string note_id )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_nav_create

(PHP 4 >= 4.0.5, PECL)

notes_nav_create -- Create a navigator name, in database_name

Description

bool notes_nav_create ( string database_name, string 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

notes_search

(PHP 4 >= 4.0.5, PECL)

notes_search -- Find notes that match keywords in database_name

Description

array notes_search ( string database_name, string keywords )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

notes_unread

(PHP 4 >= 4.0.5, PECL)

notes_unread -- Returns the unread note id's for the current User user_name

Description

array notes_unread ( string database_name, string user_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

notes_version

(PHP 4 >= 4.0.5, PECL)

notes_version -- Get the version Lotus Notes

Description

float notes_version ( string database_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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LXVI. Funzioni LZF

Introduzione

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.


Installazione

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

Sommario
lzf_compress --  Compression LZF.
lzf_decompress --  Decompressione LZF.
lzf_optimized_for --  Determina il tipo di ottimizzazione del modulo LZF.

lzf_compress

(PECL)

lzf_compress --  Compression LZF.

Descrizione

string lzf_compress ( string arg )

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

(PECL)

lzf_decompress --  Decompressione LZF.

Descrizione

string lzf_decompress ( string arg )

lzf_decompress() decomprime i dati dal parametro arg.

Restituisce id ati decompressi oppure FALSE se si verifica un errore.

Vedere anche lzf_compress().

lzf_optimized_for

(PECL)

lzf_optimized_for --  Determina il tipo di ottimizzazione del modulo LZF.

Descrizione

int lzf_optimized_for ( void )

Restituisce 1 se LZF è ottimizzato per la velocità, 0 per la compressione.

LXVII. Funzioni di Mail

Introduzione

La funzione mail() permette di inviare messaggi di posta elettronica.


Requisiti

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.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione Mail

NomePredefinitoModificabile in
SMTP"localhost"PHP_INI_ALL
smtp_port"25"PHP_INI_ALL
sendmail_fromNULLPHP_INI_ALL
sendmail_pathDEFAULT_SENDMAIL_PATHPHP_INI_SYSTEM
Per ulteriori dettagli e per la definizione delle costanti PHP_INI_* fare riferimento a ini_set().

Breve descrizione dei parametri di configurazione.

SMTP string

Usato solo sotto Windows: Nome DNS o indirizzo IP del server SMTP che PHP deve usare per spedire posta elettronica con la funzione mail().

smtp_port int

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.

sendmail_from string

Quale campo "From:" devono avere i messaggi inviati da PHP sotto Windows.

sendmail_path string

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.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
ezmlm_hash -- Calcola il valore hash che occorre a EZMLM
mail -- Invio mail

ezmlm_hash

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.2, PHP 5)

ezmlm_hash -- Calcola il valore hash che occorre a EZMLM

Descrizione

int ezmlm_hash ( string addr )

ezmlm_hash() calcola il valore hash che occorre quando si mantengono mailing list EZMLM in un database MySQL.

Esempio 1. Calcolare l'hash e iscrivere un utente

<?php
$utente = "pippo@example.com";
$hash = ezmlm_hash($utente);
$query = sprintf("INSERT INTO esempio VALUES (%s, '%s')", $hash, $utente);
$db->query($query); // tramite l'interfaccia db PHPLIB
?>

mail

(PHP 3, PHP 4, PHP 5)

mail -- Invio mail

Descrizione

bool mail ( string a, string oggetto, string messaggio [, string header_addizionali [, string parametri_addizionali]] )

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.

Esempio 1. Inviare mail.

<?php
mail("pippo@example.com", "Oggetto", "Linea 1\nLinea 2\nLinea 3");
?>

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

Esempio 2. Invio di mail con intestazioni supplementari.

<?php
mail("nessuno@example.com", "oggetto", $messaggio,
     "From: webmaster@{$_SERVER['SERVER_NAME']}\r\n" .
     "Reply-To: webmaster@{$_SERVER['SERVER_NAME']}\r\n" .
     "X-Mailer: PHP/" . phpversion());
?>

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.

Esempio 3. Invio di mail con intestazioni supplementari e impostazione dei parametri addizionali a linea di comando.

<?php
mail("nessuno@example.com", "oggetto", $messaggio,
     "From: webmaster@{$_SERVER['SERVER_NAME']}", "-fwebmaster@{$_SERVER['SERVER_NAME']}");
?>

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.

<?php
/* destinatari */
$destinatari  = "Maria <maria@example.com>" . ", " ; // notare la virgola
$destinatari .= "Enrica <enrica@example.com>";

/* oggetto */
$oggetto = "Promemoria compleanni di Agosto";

/* messaggio */
$messaggio = '
<html>
<head>
 <title>Promemoria compleanni di Agosto</title>
</head>
<body>
<p>Questi sono i compleanni di Agosto!</p>
<table>
 <tr>
  <th>Persona</th><th>Giorno</th><th>Mese</th><th>Anno</th>
 </tr>
 <tr>
  <td>Walter</td><td>11</td><td>Agosto</td><td>1946</td>
 </tr>
 <tr>
  <td>Sara</td><td>14</td><td>Agosto</td><td>1985</td>
 </tr>
</table>
</body>
</html>
';

/* Per inviare email in formato HTML, si deve impostare l'intestazione Content-type. */
$intestazioni  = "MIME-Version: 1.0\r\n";
$intestazioni .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* intestazioni addizionali */
$intestazioni .= "To: Mary <mary@example.com>, Kelly <kelly@example.com>\r\n";
$intestazioni .= "From: Promemoria Compleanni <compleanni@example.com>\r\n";
$intestazioni .= "Cc: archiviocompleanni@example.com\r\n";
$intestazioni .= "Bcc: controllocompleanni@example.com\r\n";

/* ed infine l'invio */
mail($destinatari, $oggetto, $messaggio, $intestazioni);
?>

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

LXVIII. mailparse Functions

Introduzione

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.


Installazione

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

Sommario
mailparse_determine_best_xfer_encoding --  Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able
mailparse_msg_create -- Returns a handle that can be used to parse a message
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding
mailparse_msg_extract_part --  Extracts/decodes a message section
mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()
mailparse_msg_get_part_data -- Returns an associative array of info about the message
mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message
mailparse_msg_parse_file -- Parse file and return a resource representing the structure
mailparse_msg_parse -- Incrementally parse data into buffer
mailparse_rfc822_parse_addresses --  Parse addresses and returns a hash containing that data
mailparse_stream_encode --  Streams data from source file pointer, apply encoding and write to destfp
mailparse_uudecode_all --  Scans the data from fp and extract each embedded uuencoded file

mailparse_determine_best_xfer_encoding

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

Description

string mailparse_determine_best_xfer_encoding ( resource fp )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_create

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_create -- Returns a handle that can be used to parse a message

Description

resource mailparse_msg_create ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_extract_part_file

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding

Description

string mailparse_msg_extract_part_file ( resource rfc2045, string filename [, callback callbackfunc] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_extract_part

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_extract_part --  Extracts/decodes a message section

Description

void mailparse_msg_extract_part ( resource rfc2045, string msgbody [, callback callbackfunc] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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".

mailparse_msg_free

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()

Description

bool mailparse_msg_free ( resource rfc2045buf )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_get_part_data

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_get_part_data -- Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource rfc2045 )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_get_part

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage

Description

resource mailparse_msg_get_part ( resource rfc2045, string mimesection )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_get_structure

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource rfc2045 )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_parse_file

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_parse_file -- Parse file and return a resource representing the structure

Description

resource mailparse_msg_parse_file ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_msg_parse

(4.1.0 - 4.1.2 only, PECL)

mailparse_msg_parse -- Incrementally parse data into buffer

Description

bool mailparse_msg_parse ( resource rfc2045buf, string data )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_rfc822_parse_addresses

(4.1.0 - 4.1.2 only, PECL)

mailparse_rfc822_parse_addresses --  Parse addresses and returns a hash containing that data

Description

array mailparse_rfc822_parse_addresses ( string addresses )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_stream_encode

(4.1.0 - 4.1.2 only, PECL)

mailparse_stream_encode --  Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource sourcefp, resource destfp, string encoding )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

mailparse_uudecode_all

(PECL)

mailparse_uudecode_all --  Scans the data from fp and extract each embedded uuencoded file

Description

array mailparse_uudecode_all ( resource fp )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

LXIX. Funzioni Matematiche

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.

Tabella 1. Costanti Matematiche

CostanteValoreDescrizione
M_PI3.14159265358979323846Pi
M_E2.7182818284590452354e
M_LOG2E1.4426950408889634074log_2 e
M_LOG10E0.43429448190325182765log_10 e
M_LN20.69314718055994530942log_e 2
M_LN102.30258509299404568402log_e 10
M_PI_21.57079632679489661923pi/2
M_PI_40.78539816339744830962pi/4
M_1_PI0.318309886183790671541/pi
M_2_PI0.636619772367581343082/pi
M_SQRTPI1.77245385090551602729sqrt(pi) [4.0.2]
M_2_SQRTPI1.128379167095512573902/sqrt(pi)
M_SQRT21.41421356237309504880sqrt(2)
M_SQRT31.73205080756887729352sqrt(3) [4.0.2]
M_SQRT1_20.707106781186547524401/sqrt(2)
M_LNPI1.14472988584940017414log_e(pi) [4.0.2]
M_EULER0.57721566490153286061Costante di Eulero [4.0.2]
Soltanto M_PI è disponibile nelle versioni precedenti alla PHP 4.0.0 (compresa). Tutte le rimanenti costanti sono disponibili a partire dal PHP 4.0.0. Le costanti indicate con [4.0.2] sono state aggiunte nel PHP 4.0.2.

Sommario
abs -- Valore assoluto
acos -- Arco coseno
acosh -- Inverso del coseno iperbolico
asin -- Arco seno
asinh -- Inverso del seno iperbolico
atan2 -- Arco tangente di due variabili
atan -- Arco tangente
atanh -- Inverso della tangente iperbolica
base_convert -- Converte un numero fra basi arbitrarie
bindec -- Da binario a decimale
ceil -- arrotonda le frazioni all'intero superiore
cos -- Coseno
cosh -- Coseno iperbolico
decbin -- Da decimale a binario
dechex -- Da decimale a esadecimale
decoct -- Da decimale a ottale
deg2rad --  Converte il numero dato in gradi nell'equivalente espresso in radianti
exp -- Calcola l'esponente di e (la base logaritmica naturale o di Nepero)
expm1 --  Restituisce exp(numero) - 1, computato in maniera tale da essere accurato anche se il valore del numero è vicino a zero
floor -- Arrotonda le frazioni all'intero inferiore
fmod -- Returns the floating point remainder (modulo) of the division of the arguments
getrandmax -- Mostra il più grande numero casuale disponibile
hexdec -- Da esadecimale a decimale
hypot --  Restituisce sqrt(num1*num1 + num2*num2)
is_finite -- Verifica se un numero dato è un numero finito
is_infinite -- Verifica se un dato valore è infinito
is_nan -- Verifica se un dato valore non sia un numero
lcg_value -- Generatore combinato lineare congruenziale
log10 -- Logaritmo base-10
log1p --  Restituisce log(1 + numero), computato in maniera tale da essere accurato anche se il valore del numero è vicino a zero
log -- Logaritmo naturale
max -- Trova il valore massimo
min -- Trova il valore minimo
mt_getrandmax -- Mostra il più grande valore casuale disponibile
mt_rand -- Genera un valore casuale migliore
mt_srand -- Inizializza un generatore di numeri casuali migliore
octdec -- Da ottale a decimale
pi -- Restituisce il valore di pi
pow -- Espressione esponenziale
rad2deg --  Converte un numero in radianti nell'equivalente numero in gradi
rand -- Genera un valore casuale
round -- Arrotonda un numero non intero
sin -- Seno
sinh -- Seno iperbolico
sqrt -- Radice quadrata
srand -- inizializza il generatore di numeri casuali
tan -- Tangente
tanh -- Tangente iperbolica

abs

(PHP 3, PHP 4, PHP 5)

abs -- Valore assoluto

Descrizione

number abs ( mixed numero )

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

Esempio 1. Esempio di abs()

<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)
?>

acos

(PHP 3, PHP 4, PHP 5)

acos -- Arco coseno

Descrizione

float acos ( float arg )

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

Vedere anche: acosh(), asin() e atan().

acosh

(PHP 4 >= 4.1.0, PHP 5)

acosh -- Inverso del coseno iperbolico

Descrizione

float acosh ( float arg )

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

Vedere anche acos(), asinh() e atanh().

asin

(PHP 3, PHP 4, PHP 5)

asin -- Arco seno

Descrizione

float asin ( float arg )

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

Vedere anche asinh(), acos() e atan().

asinh

(PHP 4 >= 4.1.0, PHP 5)

asinh -- Inverso del seno iperbolico

Descrizione

float asinh ( float arg )

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

Vedere anche asin(), acosh() e atanh().

atan2

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

atan2 -- Arco tangente di due variabili

Descrizione

float atan2 ( float y, float x )

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

Vedere anche acos() e atan().

atan

(PHP 3, PHP 4, PHP 5)

atan -- Arco tangente

Descrizione

float atan ( float arg )

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

Vedere anche atanh(), asin() e acos().

atanh

(PHP 4 >= 4.1.0, PHP 5)

atanh -- Inverso della tangente iperbolica

Descrizione

float atanh ( float arg )

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

Vedere anche: atan(), asinh() e acosh().

base_convert

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

base_convert -- Converte un numero fra basi arbitrarie

Descrizione

string base_convert ( string numero, int base_di_partenza, int base_di_arrivo )

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.

Esempio 1. Esempio di uso di base_convert()

<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);
?>

Visualizza:

101000110111001100110100

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.

bindec

(PHP 3, PHP 4, PHP 5)

bindec -- Da binario a decimale

Descrizione

int bindec ( string stringa_binaria )

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.

Esempio 1. Esempio di bindec()

<?php 
echo bindec('110011') . "\n"; 
echo bindec('000110011') . "\n"; 
 
echo bindec('111'); 
?>

L'esempio precedente visualizzerà:

51 
51 
7

Vedere anche decbin(), octdec(), hexdec() e base_convert().

ceil

(PHP 3, PHP 4, PHP 5)

ceil -- arrotonda le frazioni all'intero superiore

Descrizione

float ceil ( float numero )

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.

Esempio 1. Esempio di ceil()

<?php
$cinque = ceil(4.3);   // 5
$dieci = ceil(9.999);  // 10
?>

Vedere anche floor() e round().

cos

(PHP 3, PHP 4, PHP 5)

cos -- Coseno

Descrizione

float cos ( float arg )

Restituisce il coseno di arg. Il parametro arg deve essere espresso in radianti.

Esempio 1. Esempio di cos()

<?php 
 
echo cos(M_PI); // -1 
 
?>

Vedere anche acos(), sin(), tan() e deg2rad().

cosh

(PHP 4 >= 4.1.0, PHP 5)

cosh -- Coseno iperbolico

Descrizione

float cosh ( float arg )

Restituisce il coseno iperbolico di arg, definito come (exp(arg) + exp(-arg))/2.

Vedere anche: cos(), acosh(), sin() e tan().

decbin

(PHP 3, PHP 4, PHP 5)

decbin -- Da decimale a binario

Descrizione

string decbin ( int numero )

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.

Esempio 1. Esempio per decbin()

<?php 
echo decbin(12) . "\n"; 
echo decbin(26); 
?>

L'esempio precedente visualizzerà:

1100 
11010

Vedere anche bindec(), decoct(), dechex() e base_convert().

dechex

(PHP 3, PHP 4, PHP 5)

dechex -- Da decimale a esadecimale

Descrizione

string dechex ( int numero )

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

Esempio 1. Esempio per dechex()

<?php 
echo dechex(10) . "\n"; 
echo dechex(47); 
?>

L'esempio precedente visualizzerà:

a 
2f

Vedere anche hexdec(), decbin(), decoct() e base_convert().

decoct

(PHP 3, PHP 4, PHP 5)

decoct -- Da decimale a ottale

Descrizione

string decoct ( int numero )

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

Esempio 1. Esempio per decoct()

<?php 
echo decoct(15) . "\n"; 
echo decoct(264); 
?>

L'esempio precedente visualizzerà:

17 
410

Vedere anche octdec(), decbin(), dechex() e base_convert().

deg2rad

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

deg2rad --  Converte il numero dato in gradi nell'equivalente espresso in radianti

Descrizione

double deg2rad ( double numero )

Questa funzione converte numero da gradi al valore equivalente espresso in radianti.

Esempio 1. Esempio per deg2rad()

<?php
 
echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)
 
?>

Vedere anche rad2deg().

exp

(PHP 3, PHP 4, PHP 5)

exp -- Calcola l'esponente di e (la base logaritmica naturale o di Nepero)

Descrizione

float exp ( float arg )

Restituisce e elevato alla potenza di arg.

Nota: 'e' è la base del sistema dei logaritmi dei numeri naturali, e vale 2.718282.

Esempio 1. Esempio per exp()

<?php 
echo exp(12) . "\n"; 
echo exp(5.7); 
?>

L'esempio precedente visualizzerà:

1.6275E+005 
298.87

Vedere anche log() e pow().

expm1

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

Description

float expm1 ( float number )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

floor

(PHP 3, PHP 4, PHP 5)

floor -- Arrotonda le frazioni all'intero inferiore

Descrizione

float floor ( float numero )

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.

Esempio 1. Esempio di floor()

<?php
echo floor(4.3); // 4
echo floor(9.999);  // 9
?>

Vedere anche ceil() e round().

fmod

(PHP 4 >= 4.2.0, PHP 5)

fmod -- Returns the floating point remainder (modulo) of the division of the arguments

Description

float fmod ( float x, float y )

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

Esempio 1. Using fmod()

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

getrandmax

(PHP 3, PHP 4, PHP 5)

getrandmax -- Mostra il più grande numero casuale disponibile

Descrizione

int getrandmax ( void )

Restituisce il valore massimo che può essere restituito da una chiamata alla funzione rand().

Vedere anche rand(), srand() e mt_getrandmax().

hexdec

(PHP 3, PHP 4, PHP 5)

hexdec -- Da esadecimale a decimale

Descrizione

int hexdec ( string stringa_esadecimale )

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.

Esempio 1. esempio di hexdec()

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// entrambi stampano "int(238)"

var_dump(hexdec("that")); // stampa "int(10)"
var_dump(hexdec("a0"));   // stampa "int(160)"
?>

Vedere anche dechex(), bindec(), octdec() e base_convert().

hypot

(PHP 4 >= 4.1.0, PHP 5)

hypot --  Restituisce sqrt(num1*num1 + num2*num2)

Descrizione

float hypot ( float num1, float num2 )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

is_finite

(PHP 4 >= 4.2.0, PHP 5)

is_finite -- Verifica se un numero dato è un numero finito

Descrizione

bool is_finite ( float val )

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

is_infinite

(PHP 4 >= 4.2.0, PHP 5)

is_infinite -- Verifica se un dato valore è infinito

Descrizione

bool is_infinite ( float val )

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

is_nan

(PHP 4 >= 4.2.0, PHP 5)

is_nan -- Verifica se un dato valore non sia un numero

Descrizione

bool is_nan ( float val )

Restituisce TRUE se val 'non è un numero', come il risultato di acos(1.01).

Vedere anche is_finite() e is_infinite().

lcg_value

(PHP 4, PHP 5)

lcg_value -- Generatore combinato lineare congruenziale

Descriztione

float lcg_value ( void )

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.

log10

(PHP 3, PHP 4, PHP 5)

log10 -- Logaritmo base-10

Descrizione

float log10 ( float arg )

Restituisce il logaritmo in base-10 di arg.

Vedere anche: log()

log1p

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

Description

float log1p ( float number )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

log

(PHP 3, PHP 4, PHP 5)

log -- Logaritmo naturale

Descrizione

float log ( float arg [, float base] )

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

(PHP 3, PHP 4, PHP 5)

max -- Trova il valore massimo

Descrizione

mixed max ( number arg1, number arg2 [, number ...] )

mixed max ( array numbers [, array ...] )

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

<?php
echo max(1, 3, 5, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello
echo max(-1, 'hello');    // hello

// Con diversi array, max confronta da sinistra a destra
// quindi nell'esempio: 2 == 2, e 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// Nel caso siano forniti array e parametri non array, la funzione restituirà
// sempre l'array, considerando questo il più grande
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
?>

Vedere anche min() e count().

min

(PHP 3, PHP 4, PHP 5)

min -- Trova il valore minimo

Descrizione

mixed min ( number arg1, number arg2 [, number ...] )

mixed min ( array numbers [, array ...] )

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

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello
echo min('hello', -1);    // -1

// Con diversi array, min confronta da sinistra a destra
// quindi nell'esempio: 2 == 2, e 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// In caso di parametri misti array e non array, l'array non sarà mai restituito
// perchè considerato il più grande
$val = min('string', array(2, 5, 7), 42);   // string
?>

Vedere anche max() e count().

mt_getrandmax

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_getrandmax -- Mostra il più grande valore casuale disponibile

Descrizione

int mt_getrandmax ( void )

Restituisce il massimo valore che può essere restituito da una chiamata alla funzione mt_rand().

Vedere anche mt_rand(), mt_srand() e getrandmax().

mt_rand

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_rand -- Genera un valore casuale migliore

Descrizione

int mt_rand ( [int min, int max] )

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

Esempio 1. Esempio per mt_rand()

<?php 
echo mt_rand() . "\n"; 
echo mt_rand() . "\n"; 
echo mt_rand(5, 15); 
?>

L'esempio precedente visualizzerà qualcosa simile a:

1604716014 
1478613278 
6

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

mt_srand

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_srand -- Inizializza un generatore di numeri casuali migliore

Descrizione

void mt_srand ( [int seme] )

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.

Esempio 1. Esempio di uso di mt_srand()

<?php
// inizializza usando i microsecondi
function crea_seme() 
{
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
mt_srand(crea_seme());
$valorecasuale = 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.

Vedere anche mt_rand(), mt_getrandmax() e srand().

octdec

(PHP 3, PHP 4, PHP 5)

octdec -- Da ottale a decimale

Descrizione

int octdec ( string stringa_ottale )

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.

Esempio 1. Esempio per octdec()

<?php 
echo octdec('77') . "\n"; 
echo octdec(decoct(45)); 
?>

L'esempio precedente visualizzerà:

63 
45

Vedere anche decoct(), bindec(), hexdec() e base_convert().

pi

(PHP 3, PHP 4, PHP 5)

pi -- Restituisce il valore di pi

Descrizione

double pi ( void )

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

Esempio 1. Esempio di uso di pi()

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

pow

(PHP 3, PHP 4, PHP 5)

pow -- Espressione esponenziale

Descrizione

float pow ( float base, float esp )

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.

Esempio 1. Alcuni esempi di pow()

<?php

var_dump( pow(2,8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // errore

?>

Avvertimento

Nel PHP 4.0.6 e precedenti, pow() restituiva sempre un float e non generava alcun errore.

Vedere anche exp() sqrt() bcpow() e gmp_pow().

rad2deg

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

rad2deg --  Converte un numero in radianti nell'equivalente numero in gradi

Descrizione

double rad2deg ( double numero )

Questa funzione converte numero da radianti a gradi.

Esempio 1. Esempio per rad2deg()

<?php
 
echo rad2deg(M_PI_4); // 45
 
?>

Vedere anche deg2rad().

rand

(PHP 3, PHP 4, PHP 5)

rand -- Genera un valore casuale

Descrizione

int rand ( [int min, int max] )

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

Esempio 1. Esempio per rand()

<?php
echo rand() . "\n";
echo rand() . "\n";
echo rand(5, 15);
?>

L'esempio precedente visualizzerà qualcosa simile a:

7771
22264
11

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

round

(PHP 3, PHP 4, PHP 5)

round -- Arrotonda un numero non intero

Descrizione

double round ( double val [, int precisione] )

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

Esempio 1. round() examples

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

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

sin

(PHP 3, PHP 4, PHP 5)

sin -- Seno

Descrizione

float sin ( float arg )

La funzione sin() restituisce il seno di arg. Il parametro arg viene espresso in radianti.

Esempio 1. Esempio di uso di sin()

<?php

// La precisione dipende dalle direttive di precisione
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...

?>

Vedere anche: asin(), cos(), tan() e deg2rad().

sinh

(PHP 4 >= 4.1.0, PHP 5)

sinh -- Seno iperbolico

Descrizione

float sinh ( float arg )

Restituisce il seno iperbolico di arg, definito come (exp(arg) - exp(-arg))/2.

Vedere anche: sin(), asinh(), cos() e tan().

sqrt

(PHP 3, PHP 4, PHP 5)

sqrt -- Radice quadrata

Descrizione

float sqrt ( float arg )

Restituisce la radice quadrata di arg.

Esempio 1. Esempio di uso di sqrt()

<?php
// La precisione dipende dalle impostazioni delle direttive sulla precisione
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

Vedere anche pow().

srand

(PHP 3, PHP 4, PHP 5)

srand -- inizializza il generatore di numeri casuali

Descrizione

void srand ( [int seme] )

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.

Esempio 1. Esempio di uso di srand()

<?php
// inizializza usando i microsecondi
function crea_seme()
{
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand((double)microtime()*1000000);
$valorecasuale = 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.

Vedere anche: rand(), getrandmax() e mt_srand().

tan

(PHP 3, PHP 4, PHP 5)

tan -- Tangente

Descrizione

float tan ( float arg )

La funzione tan() restituisce la tangente del parametro arg. Il parametro arg deve essere espresso in radianti.

Esempio 1. Esempio per tan()

<?php 
 
echo tan(M_PI_2); // 1 
 
?>

Vedere anche: atan(), sin(), cos() e deg2rad().

tanh

(PHP 4 >= 4.1.0, PHP 5)

tanh -- Tangente iperbolica

Descrizione

float tanh ( float arg )

Restituisce la tangente iperbolica di arg, definita come sinh(arg)/cosh(arg).

Vedere anche: tan(), atanh(), sin() e cos().

LXX. MaxDB PHP Extension

Introduzione

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


Requisiti

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.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. MaxDB Configuration Options

NameDefaultChangeableChangelog
maxdb.default_hostNULLPHP_INI_ALL 
maxdb.default_dbNULLPHP_INI_ALL 
maxdb.default_userNULLPHP_INI_ALL 
maxdb.default_pwNULLPHP_INI_ALL 
maxdb.long_readlen"200"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

maxdb.default_host string

The default server host to use when connecting to the database server if no other host is specified.

maxdb.default_db string

The default server database to use when connecting if no other database is specified.

maxdb.default_user string

The default user name to use when connecting to the database server if no other name is specified.

maxdb.default_pw string

The default password to use when connecting to the database server if no other password is specified.

maxdb.long_readlen integer

The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.


Classi predefinite

maxdb

Represents a connection between PHP and a MaxDB database.


Costruttori

  • maxdb - construct a new maxdb object


Metodi

  • 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


Proprietà

  • 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


maxdb_stmt

Represents a prepared statement.


Metodi

  • 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


Proprietà

  • 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


maxdb_result

Represents the result set obtained from a query against the database.


Metodi

  • 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


Proprietà


Costanti predefinite

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

ConstantDescription
MAXDB_COMPNAMEThe component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATIONThe application to be connected to the database.
MAXDB_APPVERSIONThe version of the application.
MAXDB_SQLMODEThe SQL mode.
MAXDB_UNICODETRUE, 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

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


Esempi

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

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");
   
/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$query = "SELECT * FROM hotel.city";
$result = maxdb_query($link, $query) or die("Query failed : " . maxdb_error());

/* Printing results in HTML */
echo "<table>\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
    echo "  <tr>\n";
    foreach ($line as $col_value) {
        echo "    <td>$col_value</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

/* Free resultset */
maxdb_free_result($result);

/* Closing connection */
maxdb_close($link);
?>

The following example shows how to bind variables to a SELECT INTO statement.

Esempio 2. Example for use of SELECT INTO statements

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
   
/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT percentage INTO ? FROM hotel.countrylanguage where language = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$name = "Mbundu";

maxdb_stmt_bind_param($stmt, 'ds', $percentage, $name);
maxdb_stmt_execute($stmt);

printf ("%f\n", $percentage);

maxdb_stmt_close ($stmt);
?>

The following example shows how to use MaxDB database procedures.

Esempio 3. Example fore using database procedures

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

Sommario
maxdb_affected_rows -- Gets the number of affected rows in a previous MaxDB operation
maxdb_autocommit -- Turns on or off auto-commiting database modifications
maxdb_bind_param -- Alias di maxdb_stmt_bind_param()
maxdb_bind_result -- Alias di maxdb_stmt_bind_result()
maxdb_change_user -- Changes the user of the specified database connection
maxdb_character_set_name -- Returns the default character set for the database connection
maxdb_client_encoding -- Alias di maxdb_character_set_name()
maxdb_close_long_data -- Alias di maxdb_stmt_close_long_data()
maxdb_close -- Closes a previously opened database connection
maxdb_commit -- Commits the current transaction
maxdb_connect_errno -- Returns the error code from last connect call
maxdb_connect_error -- Returns a string description of the last connect error
maxdb_connect -- Open a new connection to the MaxDB server
maxdb_data_seek -- Adjusts the result pointer to an arbitary row in the result
maxdb_debug -- Performs debugging operations
maxdb_disable_reads_from_master -- Disable reads from master
maxdb_disable_rpl_parse -- Disable RPL parse
maxdb_dump_debug_info -- Dump debugging information into the log
maxdb_embedded_connect -- Open a connection to an embedded MaxDB server
maxdb_enable_reads_from_master -- Enable reads from master
maxdb_enable_rpl_parse -- Enable RPL parse
maxdb_errno -- Returns the error code for the most recent function call
maxdb_error -- Returns a string description of the last error
maxdb_escape_string -- Alias di maxdb_real_escape_string()
maxdb_execute -- Alias di maxdb_stmt_execute()
maxdb_fetch_array -- Fetch a result row as an associative, a numeric array, or both
maxdb_fetch_assoc -- Fetch a result row as an associative array
maxdb_fetch_field_direct --  Fetch meta-data for a single field
maxdb_fetch_field -- Returns the next field in the result set
maxdb_fetch_fields -- Returns an array of resources representing the fields in a result set
maxdb_fetch_lengths -- Returns the lengths of the columns of the current row in the result set
maxdb_fetch_object -- Returns the current row of a result set as an object
maxdb_fetch_row -- Get a result row as an enumerated array
maxdb_fetch -- Alias di maxdb_stmt_fetch()
maxdb_field_count -- Returns the number of columns for the most recent query
maxdb_field_seek --  Set result pointer to a specified field offset
maxdb_field_tell --  Get current field offset of a result pointer
maxdb_free_result -- Frees the memory associated with a result
maxdb_get_client_info -- Returns the MaxDB client version as a string
maxdb_get_client_version -- Get MaxDB client info
maxdb_get_host_info -- Returns a string representing the type of connection used
maxdb_get_metadata -- Alias di maxdb_stmt_result_metadata()
maxdb_get_proto_info -- Returns the version of the MaxDB protocol used
maxdb_get_server_info -- Returns the version of the MaxDB server
maxdb_get_server_version -- Returns the version of the MaxDB server as an integer
maxdb_info -- Retrieves information about the most recently executed query
maxdb_init --  Initializes MaxDB and returns an resource for use with maxdb_real_connect
maxdb_insert_id -- Returns the auto generated id used in the last query
maxdb_kill -- Disconnects from a MaxDB server
maxdb_master_query -- Enforce execution of a query on the master in a master/slave setup
maxdb_more_results -- Check if there any more query results from a multi query
maxdb_multi_query -- Performs a query on the database
maxdb_next_result -- Prepare next result from multi_query
maxdb_num_fields --  Get the number of fields in a result
maxdb_num_rows --  Gets the number of rows in a result
maxdb_options -- Set options
maxdb_param_count -- Alias di maxdb_stmt_param_count()
maxdb_ping --  Pings a server connection, or tries to reconnect if the connection has gone down
maxdb_prepare --  Prepare a SQL statement for execution
maxdb_query -- Performs a query on the database
maxdb_real_connect -- Opens a connection to a MaxDB server
maxdb_real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
maxdb_real_query -- Execute an SQL query
maxdb_report -- Enables or disables internal report functions
maxdb_rollback -- Rolls back current transaction
maxdb_rpl_parse_enabled -- Check if RPL parse is enabled
maxdb_rpl_probe -- RPL probe
maxdb_rpl_query_type -- Returns RPL query type
maxdb_select_db -- Selects the default database for database queries
maxdb_send_long_data -- Alias di maxdb_stmt_send_long_data()
maxdb_send_query -- Send the query and return
maxdb_server_end -- Shut down the embedded server
maxdb_server_init -- Initialize embedded server
maxdb_set_opt -- Alias di maxdb_options()
maxdb_sqlstate -- Returns the SQLSTATE error from previous MaxDB operation
maxdb_ssl_set -- Used for establishing secure connections using SSL
maxdb_stat -- Gets the current system status
maxdb_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
maxdb_stmt_bind_param -- Binds variables to a prepared statement as parameters
maxdb_stmt_bind_result -- Binds variables to a prepared statement for result storage
maxdb_stmt_close_long_data -- Ends a sequence of maxdb_stmt_send_long_data()
maxdb_stmt_close -- Closes a prepared statement
maxdb_stmt_data_seek -- Seeks to an arbitray row in statement result set
maxdb_stmt_errno -- Returns the error code for the most recent statement call
maxdb_stmt_error -- Returns a string description for last statement error
maxdb_stmt_execute -- Executes a prepared Query
maxdb_stmt_fetch --  Fetch results from a prepared statement into the bound variables
maxdb_stmt_free_result -- Frees stored result memory for the given statement handle
maxdb_stmt_init --  Initializes a statement and returns an resource for use with maxdb_stmt_prepare
maxdb_stmt_num_rows -- Return the number of rows in statements result set
maxdb_stmt_param_count -- Returns the number of parameter for the given statement
maxdb_stmt_prepare --  Prepare a SQL statement for execution
maxdb_stmt_reset -- Resets a prepared statement
maxdb_stmt_result_metadata -- Returns result set metadata from a prepared statement
maxdb_stmt_send_long_data -- Send data in blocks
maxdb_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation
maxdb_stmt_store_result -- Transfers a result set from a prepared statement
maxdb_store_result -- Transfers a result set from the last query
maxdb_thread_id -- Returns the thread ID for the current connection
maxdb_thread_safe -- Returns whether thread safety is given or not
maxdb_use_result -- Initiate a result set retrieval
maxdb_warning_count -- Returns the number of warnings from the last query for the given link

maxdb_affected_rows

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

Description

Procedural style:

int maxdb_affected_rows ( resource link )

Object oriented style (property):

class maxdb {

int affected_rows

}

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.

Return Values

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.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
$maxdb->query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb->affected_rows);

$maxdb->query("ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
$maxdb->query("UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", $maxdb->affected_rows);

/* delete rows */
$maxdb->query("DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", $maxdb->affected_rows);

/* select all rows */
$result = $maxdb->query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb->affected_rows);

$result->close();

/* Delete table Language */
$maxdb->query("DROP TABLE mycustomer");

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
maxdb_query($link, "CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", maxdb_affected_rows($link));

maxdb_query($link, "ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
maxdb_query($link, "UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));

/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", maxdb_affected_rows($link));

/* select all rows */
$result = maxdb_query($link, "SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", maxdb_affected_rows($link));

maxdb_free_result($result);

/* Delete table Language */
maxdb_query($link, "DROP TABLE mycustomer");

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

maxdb_autocommit

(PECL)

maxdb_autocommit

(no version information, might be only in CVS)

maxdb->auto_commit -- Turns on or off auto-commiting database modifications

Description

Procedural style:

bool maxdb_autocommit ( resource link, bool mode )

Object oriented style (method)

class maxdb {

bool auto_commit ( bool mode )

}

maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
$maxdb->autocommit(TRUE);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
maxdb_autocommit($link, TRUE);

/* close connection */
maxdb_close($link);
?>

The above examples would produce no output.

maxdb_bind_param

(PECL)

maxdb_bind_param -- Alias di maxdb_stmt_bind_param()

Descrizione

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.

maxdb_bind_result

(PECL)

maxdb_bind_result -- Alias di maxdb_stmt_bind_result()

Descrizione

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.

maxdb_change_user

(PECL)

maxdb_change_user

(no version information, might be only in CVS)

maxdb->change_user -- Changes the user of the specified database connection

Description

Procedural style:

bool maxdb_change_user ( resource link, string user, string password, string database )

Object oriented style (method):

class maxdb {

bool change_user ( string user, string password, string database )

}

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.

Return Values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php

/* connect database test */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM dual")) {
   $row = $result->fetch_row();
   printf("Result: %s\n", $row[0]);
   $result->free();
}

/* reset all and select a new database */
if (!$maxdb->change_user("DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM dual")) {
   $row = maxdb_fetch_row($result);
   printf("Result: %s\n", $row[0]);
   maxdb_free_result($result);
}

/* reset all and select a new database */
if (!maxdb_change_user($link, "DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Result: a
Database running

maxdb_character_set_name

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

Description

Procedural style:

string maxdb_character_set_name ( resource link )

Object oriented style (method):

class maxdb {

string character_set_name ( void )

}

Returns the current character set for the database connection specified by the link parameter.

Return values

The default character set for the current connection, either ascii or unicode.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");
                                                                             
/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = $maxdb->character_set_name();
printf ("Current character set is %s\n", $charset);

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = maxdb_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
maxdb_close($link);
?>

The above examples would be produce the following output:

Current character set is ascii

maxdb_client_encoding

(PECL)

maxdb_client_encoding -- Alias di maxdb_character_set_name()

Descrizione

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.

maxdb_close_long_data

(PECL)

maxdb_close_long_data

(no version information, might be only in CVS)

maxdb->close_long_data -- Alias di maxdb_stmt_close_long_data()

Descrizione

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.

maxdb_close

(PECL)

maxdb_close

(no version information, might be only in CVS)

maxdb->close -- Closes a previously opened database connection

Description

Procedural style:

bool maxdb_close ( resource link )

Object oriented style (method):

class maxdb {

bool close ( void )

}

The maxdb_close() function closes a previously opened database connection specified by the link parameter.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

maxdb_commit

(PECL)

maxdb_commit

(no version information, might be only in CVS)

maxdb->commit -- Commits the current transaction

Description

Procedural style:

bool maxdb_commit ( resource link )

Object oriented style (method)

class maxdb {

bool commit ( void )

}

Commits the current transaction for the database connection specified by the link parameter.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
$maxdb->autocommit(FALSE);

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
$maxdb->query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb->query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
$maxdb->commit();

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
maxdb_autocommit($link, FALSE);

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
maxdb_query($link, "INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
maxdb_query($link, "INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
maxdb_commit($link);

/* close connection */
maxdb_close($link);
?>

The above examples produces no output.

maxdb_connect_errno

(PECL)

maxdb_connect_errno -- Returns the error code from last connect call

Description

int maxdb_connect_errno ( void )

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.

Return values

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

Example

Esempio 1. maxdb_connect_errno sample

<?php
$link = maxdb_connect("localhost", "XXXXXXXX", "YYYYYYYYY");

if (!$link) {
   printf("Can't connect to localhost. Errorcode: %d\n", maxdb_connect_errno());
}
?>

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

maxdb_connect_error

(PECL)

maxdb_connect_error -- Returns a string description of the last connect error

Description

string maxdb_connect_error ( void )

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.

Return values

A string that describes the error. An empty string if no error occurred.

Example

Esempio 1. maxdb_connect_error sample

<?php

$link = maxdb_connect("localhost", "nonexisting_user", "");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
}
?>

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

maxdb_connect

(PECL)

maxdb_connect

(no version information, might be only in CVS)

maxdb() -- Open a new connection to the MaxDB server

Description

Procedural style

resource maxdb_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

Object oriented style (constructor):

class maxdb {

__construct ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

}

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.

Return values

Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Host information: localhost

maxdb_data_seek

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

Description

Procedural style:

bool maxdb_data_seek ( resource result, int offset )

Object oriented style (method):

class result {

bool data_seek ( int offset )

}

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";
if ($result = $maxdb->query( $query)) {

   /* seek to row no. 10 */
   $result->data_seek(10);

   /* fetch row */
   $row = $result->fetch_row();

   printf ("City: %s  State: %s\n", $row[0], $row[1]);
       
   /* free result set*/
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* seek to row no. 400 */
   maxdb_data_seek($result, 10);

   /* fetch row */
   $row = maxdb_fetch_row($result);

   printf ("City: %s  State: %s\n", $row[0], $row[1]);
       
   /* free result set*/
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

City: Irvine  State: CA

maxdb_debug

(PECL)

maxdb_debug -- Performs debugging operations

Description

void maxdb_debug ( string debug )

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.

Return values

maxdb_debug() doesn't return any value.

Example

Esempio 1. Procedural style

<?php
   
maxdb_debug("trace packet 200");

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* close connection */
maxdb_close($link);   
?>

The above example produces no output.

maxdb_disable_reads_from_master

(PECL)

maxdb_disable_reads_from_master

(no version information, might be only in CVS)

maxdb->disable_reads_from_master -- Disable reads from master

Description

Procedural style:

bool maxdb_disable_reads_from_master ( resource link )

Object oriented style (method):

class maxdb {

void disable_reads_from_master ( void )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_disable_rpl_parse

(PECL)

maxdb_disable_rpl_parse -- Disable RPL parse

Description

bool maxdb_disable_rpl_parse ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_dump_debug_info

(PECL)

maxdb_dump_debug_info -- Dump debugging information into the log

Description

bool maxdb_dump_debug_info ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_embedded_connect

(PECL)

maxdb_embedded_connect -- Open a connection to an embedded MaxDB server

Description

resource maxdb_embedded_connect ( [string dbname] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_enable_reads_from_master

(PECL)

maxdb_enable_reads_from_master -- Enable reads from master

Description

bool maxdb_enable_reads_from_master ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_enable_rpl_parse

(PECL)

maxdb_enable_rpl_parse -- Enable RPL parse

Description

bool maxdb_enable_rpl_parse ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_errno

(PECL)

maxdb_errno

(no version information, might be only in CVS)

maxdb->errno -- Returns the error code for the most recent function call

Description

Procedural style:

int maxdb_errno ( resource link )

Object oriented style (property):

class maxdb {

int errno

}

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.

Return values

An error code value for the last call, if it failed. zero means no error occurred.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", $maxdb->errno);
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", maxdb_errno($link));
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

maxdb_error

(PECL)

maxdb_error -- Returns a string description of the last error

Description

Procedural style:

string maxdb_error ( resource link )

Object oriented style (property)

class maxdb {

string error

}

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.

Return values

A string that describes the error. An empty string if no error occurred.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errormessage: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errormessgae: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

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

maxdb_escape_string

(PECL)

maxdb_escape_string -- Alias di maxdb_real_escape_string()

Descrizione

This function is an alias of: maxdb_real_escape_string().

maxdb_execute

(PECL)

maxdb_execute -- Alias di maxdb_stmt_execute()

Descrizione

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.

maxdb_fetch_array

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

Description

Procedural style:

mixed maxdb_fetch_array ( resource result [, int resulttype] )

Object oriented style (method):

class result {

mixed fetch_array ( [int resulttype] )

}

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.

Return values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

See also

maxdb_fetch_assoc(), maxdb_fetch_row(), maxdb_fetch_resource().

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
 
$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = $maxdb->query($query);

/* numeric array */
$row = $result->fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);  

/* associative array */
$row = $result->fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);  

/* associative and numeric array */
$row = $result->fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);  

/* free result set */
$result->close();

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = maxdb_query($link, $query);

/* numeric array */
$row = maxdb_fetch_array($result, MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);  

/* associative array */
$row = maxdb_fetch_array($result, MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);  

/* associative and numeric array */
$row = maxdb_fetch_array($result, MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);  

/* free result set */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

New York (NY)
New York (NY)
Long Island (NY)

maxdb_fetch_assoc

(PECL)

maxdb_fetch_assoc

(no version information, might be only in CVS)

maxdb->fetch_assoc -- Fetch a result row as an associative array

Description

Procedural style:

array maxdb_fetch_assoc ( resource result )

Object oriented style (method):

class result {

array fetch_assoc ( void )

}

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.

Return values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

See also

maxdb_fetch_array(), maxdb_fetch_row(), maxdb_fetch_resource().

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
 
$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($row = maxdb_fetch_assoc($result)) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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)

maxdb_fetch_field_direct

(PECL)

maxdb_fetch_field_direct

(no version information, might be only in CVS)

result->fetch_field_direct --  Fetch meta-data for a single field

Description

Procedural style:

mixed maxdb_fetch_field_direct ( resource result, int fieldnr )

Object oriented style (method):

class result {

mixed fetch_field_direct ( int fieldnr )

}

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.

Return values

Returns an resource which contains field definition informations or FALSE if no field information for specified fieldnr is available.

Tabella 1. Object attributes

AttributeDescription
nameThe name of the column
max_lengthThe maximum width of the field for the result set.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = $maxdb->query($query)) {

   /* Get field information for column 'SurfaceArea' */
   $finfo = $result->fetch_field_direct(1);
 
   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);
   
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for column 'cno' */
   $finfo = maxdb_fetch_field_direct($result, 1);
 
   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

maxdb_fetch_field

(PECL)

maxdb_fetch_field

(no version information, might be only in CVS)

result->fetch_field -- Returns the next field in the result set

Description

Procedural style:

mixed maxdb_fetch_field ( resource result )

Object oriented style (method):

class result {

mixed fetch_field ( void )

}

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.

Return values

Returns an resource which contains field definition informations or FALSE if no field information is available.

Tabella 1. Object properties

PropertyDescription
nameThe name of the column
max_lengthThe maximum width of the field for the result set.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {
 
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }    
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {
 
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

maxdb_fetch_fields

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

Description

Procedural Style:

mixed maxdb_fetch_fields ( resource result )

Object oriented style (method):

class result {

mixed fetch_fields ( void )

}

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.

Return values

Returns an array of resources which contains field definition informations or FALSE if no field information is available.

Tabella 1. Object properties

PropertyDescription
nameThe name of the column
max_lengthThe maximum width of the field for the result set.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   $finfo = $result->fetch_fields();

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }    
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all columns */
   $finfo = maxdb_fetch_fields($result);
 
   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }    
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

maxdb_fetch_lengths

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

Description

Procedural style:

array maxdb_fetch_lengths ( resource result )

Object oriented style (property):

class result {

array lengths

}

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.

Return values

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.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = $maxdb->query($query)) {

   $row = $result->fetch_row();

   /* display column lengths */
   foreach ($result->lengths as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = maxdb_query($link, $query)) {

   $row = maxdb_fetch_row($result);

   /* display column lengths */
   foreach (maxdb_fetch_lengths($result) as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

maxdb_fetch_object

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

Description

Procedural style:

object maxdb_fetch_object ( object result )

Object oriented style (method):

class result {

object fetch_object ( void )

}

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.

Return values

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.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
 
$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch object array */
   while ($obj = $result->fetch_object()) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($obj = maxdb_fetch_object($result)) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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)

maxdb_fetch_row

(PECL)

maxdb_fetch_row

(no version information, might be only in CVS)

result->fetch_row -- Get a result row as an enumerated array

Description

Procedural style:

mixed maxdb_fetch_row ( resource result )

Object oriented style (method):

class result {

mixed fetch_row ( void )

}

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.

Return values

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.

See also

maxdb_fetch_array(), maxdb_fetch_assoc(), maxdb_fetch_resource().

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
 
$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch object array */
   while ($row = $result->fetch_row()) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($row = maxdb_fetch_row($result)) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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)

maxdb_fetch

(PECL)

maxdb_fetch -- Alias di maxdb_stmt_fetch()

Descrizione

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.

maxdb_field_count

(PECL)

maxdb_field_count

(no version information, might be only in CVS)

maxdb->field_count -- Returns the number of columns for the most recent query

Description

Procedural style:

int maxdb_field_count ( resource link )

Object oriented style (method):

class maxdb {

int field_count ( void )

}

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.

Return values

An integer representing the number of fields in a result set

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query( "CREATE TABLE friends (id int, name varchar(20))"); 
 
$maxdb->query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb->query( "INSERT INTO friends VALUES (2, 'Ulf')");

if ($maxdb->field_count()) {
   /* this was a select/show or describe query */
   $result = $maxdb->store_result();
   
   /* process resultset */
   $row = $result->fetch_row();

   /* free resultset */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE friends (id int, name varchar(20))"); 
 
maxdb_query($link, "INSERT INTO friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO friends VALUES (2, 'Ulf')");

if (maxdb_field_count($link)) {
   /* this was a select/show or describe query */
   $result = maxdb_store_result($link);
   
   /* process resultset */
   $row = maxdb_fetch_row($result);

   /* free resultset */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.

maxdb_field_seek

(PECL)

maxdb_field_seek

(no version information, might be only in CVS)

result->field_seek --  Set result pointer to a specified field offset

Description

Procedural style:

bool maxdb_field_seek ( resource result, int fieldnr )

Object oriented style (method):

class result {

bool field_seek ( int fieldnr )

}

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.

Return values

maxdb_field_seek() returns previuos value of field cursor.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for 2nd column */
   $result->field_seek(1);
   $finfo = $result->fetch_field();
 
   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);
   
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for 2nd column */
   maxdb_field_seek($result, 1);
   $finfo = maxdb_fetch_field($result);
 
   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

maxdb_field_tell

(PECL)

maxdb_field_tell

(no version information, might be only in CVS)

result->current_field --  Get current field offset of a result pointer

Description

Procedural style:

int maxdb_field_tell ( resource result )

Object oriented style (property):

class result {

int current_field

}

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

Valori restituiti

Returns current offset of field cursor.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       /* get fieldpointer offset */
       $currentfield = $result->current_field;

       printf("Column    %d:\n", $currentfield); 
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }    
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {
 
       /* get fieldpointer offset */
       $currentfield = maxdb_field_tell($result);

       printf("Column    %d:\n", $currentfield); 
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

maxdb_free_result

(PECL)

maxdb_free_result

(no version information, might be only in CVS)

result->free -- Frees the memory associated with a result

Description

Procedural style:

void maxdb_free_result ( resource result )

Object oriented style (method):

class result {

void free ( void )

}

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.

Valori restituiti

This function doesn't return any value.

maxdb_get_client_info

(PECL)

maxdb_get_client_info -- Returns the MaxDB client version as a string

Description

string maxdb_get_client_info ( void )

The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.

Valori restituiti

A string that represents the MaxDB client library version

Example

Esempio 1. maxdb_get_client_info

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %s\n", maxdb_get_client_info());
?>

The above examples would produce the following output:

Client library version: libSQLDBC <...>

maxdb_get_client_version

(PECL)

maxdb_get_client_version -- Get MaxDB client info

Description

int maxdb_get_client_version ( void )

Returns client version number as an integer.

Return values

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.

Example

Esempio 1. maxdb_get_client_version

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %d\n", maxdb_get_client_version());
?>

The above examples would produce the following output:

Client library version: 7.<...>

maxdb_get_host_info

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

Description

Procdural style:

string maxdb_get_host_info ( resource link )

Object oriented style (property):

class maxdb {

string host_info

}

The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.

Valori restituiti

A character string representing the server hostname and the connection type.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Host info: localhost

maxdb_get_metadata

(PECL)

maxdb_get_metadata -- Alias di maxdb_stmt_result_metadata()

Descrizione

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.

maxdb_get_proto_info

(PECL)

maxdb_get_proto_info

(no version information, might be only in CVS)

maxdb->protocol_version -- Returns the version of the MaxDB protocol used

Description

Procedural style:

int maxdb_get_proto_info ( resource link )

Object oriented style (property):

class maxdb {

string protocol_version

}

Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.

Valori restituiti

Returns an integer representing the protocol version (constant 10).

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $maxdb->protocol_version);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", maxdb_get_proto_info($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Protocol version: 10

maxdb_get_server_info

(PECL)

maxdb_get_server_info

(no version information, might be only in CVS)

maxdb->server_info -- Returns the version of the MaxDB server

Description

Procedural style:

string maxdb_get_server_info ( resource link )

Object oriented style (property):

class maxdb {

string server_info

}

Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).

Valori restituiti

A character string representing the server version.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", $maxdb->server_info);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", maxdb_get_server_info($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Server version: Kernel    7<...>

maxdb_get_server_version

(PECL)

maxdb_get_server_version -- Returns the version of the MaxDB server as an integer

Description

Procedural style:

int maxdb_get_server_version ( resource link )

Object oriented style (property):

class maxdb {

int server_version

}

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

Valori restituiti

An integer representing the server version.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", $maxdb->server_version);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", maxdb_get_server_version($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Server version: 7<...>

maxdb_info

(PECL)

maxdb_info

(no version information, might be only in CVS)

maxdb->info -- Retrieves information about the most recently executed query

Description

Procedural style:

string maxdb_info ( resource link )

Object oriented style (property)

class maxdb {

string info

}

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

Valori restituiti

A character string representing additional information about the most recently executed query.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
$maxdb->query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb->info);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
maxdb_query($link, "INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", maxdb_info($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Records: 25 Duplicates: 0 Warnings: 0

maxdb_init

(PECL)

maxdb_init --  Initializes MaxDB and returns an resource for use with maxdb_real_connect

Description

resource maxdb_init ( void )

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.

Valori restituiti

Returns an resource.

maxdb_insert_id

(PECL)

maxdb_insert_id

(no version information, might be only in CVS)

maxdb->insert_id -- Returns the auto generated id used in the last query

Description

Procedural style:

mixed maxdb_insert_id ( resource link )

Object oriented style (property):

class maxdb {

mixed insert_id

}

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.

Valori restituiti

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.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycity LIKE hotel.city");
$maxdb->query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb->query($query);

printf ("New Record has id %d.\n", $maxdb->insert_id);

/* drop table */
$maxdb->query("DROP TABLE mycity");

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city");
maxdb_query($link, "ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
maxdb_query($link, $query);

printf ("New Record has id %d.\n", maxdb_insert_id($link));

/* drop table */
maxdb_query($link, "DROP TABLE mycity");

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

New Record has id 1.

maxdb_kill

(PECL)

maxdb_kill

(no version information, might be only in CVS)

maxdb->kill -- Disconnects from a MaxDB server

Description

Procedural style:

bool maxdb_kill ( resource link, int processid )

Object oriented style (method)

class maxdb {

bool kill ( int processid )

}

This function is used to disconnect from a MaxDB server specified by the processid parameter.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

maxdb_thread_id()

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Error: Session not connected

maxdb_master_query

(PECL)

maxdb_master_query -- Enforce execution of a query on the master in a master/slave setup

Description

bool maxdb_master_query ( resource link, string query )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_more_results

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

Description

bool maxdb_more_results ( resource link )

maxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().

Return values

Always FALSE.

maxdb_multi_query

(PECL)

maxdb_multi_query

(no version information, might be only in CVS)

maxdb->multi_query -- Performs a query on the database

Description

Procedural style:

bool maxdb_multi_query ( resource link, string query )

Object oriented style (method):

class maxdb {

bool multi_query ( string query )

}

The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM dual";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->store_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * FROM dual";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_store_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

a

maxdb_next_result

(PECL)

maxdb_next_result

(no version information, might be only in CVS)

maxdb->next_result -- Prepare next result from multi_query

Description

bool maxdb_next_result ( resource link )

Since multiple queries are not yet supported, maxdb_next_result() returns always FALSE.

Return values

FALSE

maxdb_num_fields

(PECL)

maxdb_num_fields

(no version information, might be only in CVS)

result->field_count --  Get the number of fields in a result

Description

Procedural style:

int maxdb_num_fields ( resource result )

Object oriented style (property):

class result {

int field_count

}

maxdb_num_fields() returns the number of fields from specified result set.

Valori restituiti

The number of fields from a result set

Vedere anche:

maxdb_fetch_field()

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = $result->field_count;

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = maxdb_num_fields($result);

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Result set has 3 fields.

maxdb_num_rows

(PECL)

maxdb_num_rows --  Gets the number of rows in a result

Description

Procedural style:

int maxdb_num_rows ( resource result )

Object oriented style (property):

class maxdb {

int num_rows

}

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.

Valori restituiti

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.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = $result->num_rows;

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = maxdb_num_rows($result);

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Result set has 15 rows.

maxdb_options

(PECL)

maxdb_options

(no version information, might be only in CVS)

maxdb->options -- Set options

Description

Procedural style:

bool maxdb_options ( resource link, int option, mixed value )

Object oriented style (method)

class maxdb {

bool options ( int option, mixed value )

}

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

NameDescription
MAXDB_COMPNAMEThe component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATIONThe application to be connected to the database.
MAXDB_APPVERSIONThe 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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

maxdb_param_count

(PECL)

maxdb_param_count -- Alias di maxdb_stmt_param_count()

Descrizione

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.

maxdb_ping

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

Description

Procedural style:

bool maxdb_ping ( resource link )

Object oriented style (method):

class maxdb {

bool ping ( void )

}

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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if ($maxdb->ping()) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if (maxdb_ping($link)) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Our connection is ok!

maxdb_prepare

(PECL)

maxdb_prepare

(no version information, might be only in CVS)

maxdb->prepare --  Prepare a SQL statement for execution

Description

Procedure style:

resource maxdb_prepare ( resource link, string query )

Object oriented style (method)

class stmt {

resource prepare ( string query )

}

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.

Valori restituiti

maxdb_prepare() returns a statement resource or FALSE if an error occured.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = $maxdb->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
} 

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = maxdb_prepare($link, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

  /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
} 

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Rosemont is in district IL

maxdb_query

(PECL)

maxdb_query

(no version information, might be only in CVS)

maxdb->query -- Performs a query on the database

Description

Procedural style:

mixed maxdb_query ( resource link, string query [, int resultmode] )

Object oriented style (method):

class maxdb {

mixed query ( string query )

}

The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if ($maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $maxdb->query("SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", $result->num_rows);

   /* free result set */
   $result->close();
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb->query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   $result->close();
}

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if (maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = maxdb_query($link, "SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", maxdb_num_rows($result));

   /* free result set */
   maxdb_free_result($result);
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = maxdb_query($link, "SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   maxdb_free_result($result);
}

maxdb_close($link);
?>

The above examples would produce the following output:

Table mycity successfully created.
Select returned 25 rows.

maxdb_real_connect

(PECL)

maxdb_real_connect

(no version information, might be only in CVS)

maxdb->real_connect -- Opens a connection to a MaxDB server

Description

Procedural 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 {

bool real_connect ( [string hostname [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php

/* create a connection object which is not connected */
$maxdb = maxdb_init();

/* set connection options */
$maxdb->options(MAXDB_UNICODE, "FALSE");
$maxdb->options(MAXDB_TIMEOUT, 5);

/* connect to server */
$maxdb->real_connect('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", $maxdb->host_info);

$maxdb->close();
?>

Esempio 2. Procedural style

<?php

/* create a connection object which is not connected */
$link = maxdb_init();

/* set connection options */
maxdb_options($link, MAXDB_UNICODE, "FALSE");
maxdb_options($link, MAXDB_TIMEOUT, 5);

/* connect to server */
maxdb_real_connect($link, 'localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", maxdb_get_host_info($link));

maxdb_close($link);
?>

The above examples would produce the following output:

Connection: localhost <...>

maxdb_real_escape_string

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

Description

Procedural style:

string maxdb_real_escape_string ( resource link, string escapestr )

Object oriented style (method):

class maxdb {

string real_escape_sring ( string escapestr )

}

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

Return values

Returns an escaped string.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$maxdb->query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", $maxdb->sqlstate);
}

$city = $maxdb->real_escape_string($city);

/* this query with escaped $city will work */
if ($maxdb->query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", $maxdb->affected_rows);
} 

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!maxdb_query($link, "INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", maxdb_sqlstate($link));
}

$city = maxdb_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (maxdb_query($link, "INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", maxdb_affected_rows($link));
} 

maxdb_close($link);
?>

The above examples would produce the following output:

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

maxdb_real_query

(PECL)

maxdb_real_query

(no version information, might be only in CVS)

maxdb->real_query -- Execute an SQL query

Description

Procedural style

bool maxdb_real_query ( resource link, string query )

Object oriented style (method):

class maxdb {

bool real_query ( string query )

}

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

maxdb_report

(PECL)

maxdb_report -- Enables or disables internal report functions

Description

bool maxdb_report ( int flags )

Example

Esempio 1. Procedural style

<?php
/* activate reporting */
maxdb_report(MAXDB_REPORT_ERROR);

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* this query should report an error */
$result = maxdb_query($link,"SELECT Name FROM Nonexistingtable WHERE population > 50000");

maxdb_close($link);
?>

The above examples would produce the following output:

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>

maxdb_rollback

(PECL)

maxdb_rollback

(no version information, might be only in CVS)

maxdb->rollback -- Rolls back current transaction

Description

bool maxdb_rollback ( resource link )

class maxdb {

bool rollback ( void )

}

Rollbacks the current transaction for the database specified by the link parameter.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
$maxdb->autocommit(FALSE);

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
$maxdb->commit();

/* delete all rows */
$maxdb->query("DELETE FROM temp.mycity");

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Rollback */
$maxdb->rollback();

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Drop table myCity */
$maxdb->query("DROP TABLE temp.mycity");

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
maxdb_autocommit($link, FALSE);

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
maxdb_commit($link);

/* delete all rows */
maxdb_query($link, "DELETE FROM temp.mycity");

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Rollback */
maxdb_rollback($link);

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Drop table myCity */
maxdb_query($link, "DROP TABLE temp.mycity");

maxdb_close($link);
?>

The above examples would produce the following output:

0 rows in table mycity.
25 rows in table mycity (after rollback).

maxdb_rpl_parse_enabled

(PECL)

maxdb_rpl_parse_enabled -- Check if RPL parse is enabled

Description

int maxdb_rpl_parse_enabled ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_rpl_probe

(PECL)

maxdb_rpl_probe -- RPL probe

Description

bool maxdb_rpl_probe ( resource link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_rpl_query_type

(PECL)

maxdb_rpl_query_type

(no version information, might be only in CVS)

maxdb->rpl_query_type -- Returns RPL query type

Description

int maxdb_rpl_query_type ( resource link )

Object oriented style (method)

class maxdb {

int rpl_query_type ( void )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_select_db

(PECL)

maxdb_select_db

(no version information, might be only in CVS)

maxdb->select_db -- Selects the default database for database queries

Description

bool maxdb_select_db ( resource link, string dbname )

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

/* change db to non existing db */
$maxdb->select_db("XXXXXXXX");

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

/* change db to non existing db */
maxdb_select_db($link, "XXXXXXXX");

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

maxdb_close($link);
?>

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

maxdb_send_long_data

(PECL)

maxdb_send_long_data -- Alias di maxdb_stmt_send_long_data()

Descrizione

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.

maxdb_send_query

(PECL)

maxdb_send_query

(no version information, might be only in CVS)

maxdb->send_query -- Send the query and return

Description

bool maxdb_send_query ( resource link, string query )

Object oriented style (method)

class maxdb {

bool send_query ( string query )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_server_end

(PECL)

maxdb_server_end -- Shut down the embedded server

Description

void maxdb_server_end ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_server_init

(PECL)

maxdb_server_init -- Initialize embedded server

Description

bool maxdb_server_init ( [array server [, array groups]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_set_opt

(PECL)

maxdb_set_opt -- Alias di maxdb_options()

Descrizione

This function is an alias of: maxdb_options().

maxdb_sqlstate

(PECL)

maxdb_sqlstate

(no version information, might be only in CVS)

maxdb->sqlstate -- Returns the SQLSTATE error from previous MaxDB operation

Description

Procedural style:

string maxdb_sqlstate ( resource link )

Object oriented style (property):

class maxdb {

string sqlstate

}

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.

Return values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!$maxdb->query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", $maxdb->sqlstate);
}

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!maxdb_query($link, "CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", maxdb_sqlstate($link));
}

maxdb_close($link);
?>

The above examples would produce the following output:

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

maxdb_ssl_set

(PECL)

maxdb_ssl_set

(no version information, might be only in CVS)

maxdb->ssl_set -- Used for establishing secure connections using SSL

Description

Procedural style:

bool maxdb_ssl_set ( resource link, string key, string cert, string ca, string capath, string cipher )

Object oriented style (method):

class maxdb {

bool ssl_set ( string key, string cert, string ca, string capath, string cipher )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_stat

(PECL)

maxdb_stat

(no version information, might be only in CVS)

maxdb->stat -- Gets the current system status

Description

Procedural style:

string maxdb_stat ( resource link )

Object oriented style (method):

class maxdb {

string maxdb->stat ( void )

}

maxdb_stat() returns a string containing several information about the MaxDB server running.

Return values

A string describing the server status. FALSE if an error occurred.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("System status: %s\n", $maxdb->stat());

$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("System status: %s\n", maxdb_stat($link));

maxdb_close($link);
?>

The above examples would produce the following output:

System status: Kernel    7<...>

maxdb_stmt_affected_rows

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

Description

Procedural style :

int maxdb_stmt_affected_rows ( resource stmt )

Object oriented style (property):

class stmt {

int affected_rows

}

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.

Return Values

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.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = $maxdb->prepare($query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   $stmt->bind_param("s", $code);
   
   /* execute statement */
   $stmt->execute();

   printf("rows inserted: %d\n", $stmt->affected_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = maxdb_prepare($link, $query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   maxdb_stmt_bind_param($stmt, "s", $code);
   
   /* execute statement */
   maxdb_stmt_execute($stmt);

   printf("rows inserted: %d\n", maxdb_stmt_affected_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

rows inserted: 4

maxdb_stmt_bind_param

(PECL)

maxdb_stmt_bind_param

(no version information, might be only in CVS)

stmt->bind_param -- Binds variables to a prepared statement as parameters

Description

Procedural style:

bool maxdb_stmt_bind_param ( resource stmt, string types, mixed &var1 [, mixed &...] )

Object oriented style (method):

class stmt {

bool bind_param ( array types, mixed &var1 [, mixed &...] )

}

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

Tabella 1. Type specification chars

CharacterDescription
icorresponding variable has type integer
dcorresponding variable has type double
scorresponding variable has type string
bcorresponding variable is a blob and will be send in packages

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt->bind_param('sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query ($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query ($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = maxdb_prepare($link, "INSERT INTO temp.mycity VALUES (?, ?, ?)");
maxdb_stmt_bind_param($stmt, 'sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
maxdb_stmt_execute($stmt);

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

/* close statement and connection */
maxdb_stmt_close($stmt);

/* Clean up table CountryLanguage */
maxdb_query($link, "DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", maxdb_affected_rows($link));

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

1 Row inserted.
1 Row deleted.

Esempio 3. Procedural style (SELECT INTO)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
   
/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT price INTO ? FROM hotel.room where hno = ? and type = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$hno = "50";
$rtype = "suite";

maxdb_stmt_bind_param($stmt, 'dss', $price, $hno, $rtype);
maxdb_stmt_execute($stmt);

printf ("%f\n", $price);

maxdb_stmt_close ($stmt);
?>

The above examples would produce the following output:

21.600000

Esempio 4. Procedural style (DB procedure)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

The above examples would produce the following output:

a

maxdb_stmt_bind_result

(PECL)

maxdb_stmt_bind_result

(no version information, might be only in CVS)

stmt->bind_result -- Binds variables to a prepared statement for result storage

Description

Procedural style:

bool maxdb_stmt_bind_result ( resource stmt, mixed &var1 [, mixed &...] )

Object oriented style (method):

class stmt {

bool bind_result ( mixed &var1 [, mixed &...] )

}

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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = $maxdb->prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
   $stmt->execute();

   /* bind variables to prepared statement */
   $stmt->bind_result($col1, $col2);

   /* fetch values */
   while ($stmt->fetch()) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   $stmt->close();
}
/* close connection */
$maxdb->close();

?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = maxdb_prepare($link, "SELECT zip, name FROM hotel.city ORDER BY name")) {
   maxdb_stmt_execute($stmt);

   /* bind variables to prepared statement */
   maxdb_stmt_bind_result($stmt, $col1, $col2);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

maxdb_stmt_close_long_data

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

Description

Procedural style:

bool maxdb_stmt_close_long_data ( resource stmt, int param_nr )

Object oriented style (method):

class maxdb_stmt {

bool maxdb_stmt->close_long_data ( void )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

maxdb_stmt_close

(PECL)

maxdb_stmt_close

(no version information, might be only in CVS)

maxdb_stmt->close -- Closes a prepared statement

Description

Procedural style:

bool maxdb_stmt_close ( resource stmt )

Object oriented style (method):

class maxdb_stmt {

bool maxdb_stmt->close ( void )

}

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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also

maxdb_prepare(),

maxdb_stmt_data_seek

(PECL)

maxdb_stmt_data_seek

(no version information, might be only in CVS)

stmt->data_seek -- Seeks to an arbitray row in statement result set

Description

Procedural style:

bool maxdb_stmt_data_seek ( resource statement, int offset )

Object oriented style (method):

class stmt {

bool data_seek ( int offset )

}

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also

maxdb_prepare()

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* store result */
   $stmt->store_result();

   /* seek to row no. 5 */
   $stmt->data_seek(5);

   /* fetch values */
   $stmt->fetch();

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* store result */
   maxdb_stmt_store_result($stmt);

   /* seek to row no. 400 */
   maxdb_stmt_data_seek($stmt, 5);

   /* fetch values */
   maxdb_stmt_fetch($stmt);

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

City: Dallas  Zip: 75243

maxdb_stmt_errno

(PECL)

maxdb_stmt_errno

(no version information, might be only in CVS)

maxdb_stmt->errno -- Returns the error code for the most recent statement call

Description

Procedural style :

int maxdb_stmt_errno ( resource stmt )

Object oriented style (property):

class stmt {

int errno

}

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

Return values

An error code value. Zero means no error occurred.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");


$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %d.\n", $stmt->errno);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");


$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %d.\n", maxdb_stmt_errno($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

maxdb_stmt_error

(PECL)

maxdb_stmt_error

(no version information, might be only in CVS)

maxdb_stmt->error -- Returns a string description for last statement error

Description

Procedural style:

string maxdb_stmt_error ( resource stmt )

Object oriented style (property):

class stmt {

string error

}

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.

Return values

A string that describes the error. An empty string if no error occurred.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");


$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->error);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");


$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_error($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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.

maxdb_stmt_execute

(PECL)

maxdb_stmt_execute

(no version information, might be only in CVS)

stmt->execute -- Executes a prepared Query

Description

Procedural style:

bool maxdb_stmt_execute ( resource stmt )

Object oriented style (method):

class stmt {

bool execute ( void )

}

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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");
   
/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
   
$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
 
/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';
   
/* Execute the statement */
$stmt->execute();

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';
   
/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb->query($query)) {
   while ($row = $result->fetch_row()) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   $result->close();
}

/* remove table */
$maxdb->query("DROP TABLE temp.mycity");

/* close connection */    
$maxdb->close(); 
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");
   
/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
   
maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
 
/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = maxdb_prepare($link, $query);

maxdb_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';
   
/* Execute the statement */
maxdb_stmt_execute($stmt);

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';
   
/* Execute the statement */
maxdb_stmt_execute($stmt);

/* close statement */
maxdb_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = maxdb_query($link, $query)) {
   while ($row = maxdb_fetch_row($result)) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   maxdb_free_result($result);
}

/* remove table */
maxdb_query($link, "DROP TABLE temp.mycity");

/* close connection */    
maxdb_close($link); 
?>

The above examples would produce the following output:

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

maxdb_stmt_fetch

(PECL)

maxdb_stmt_fetch

(no version information, might be only in CVS)

stmt->fetch --  Fetch results from a prepared statement into the bound variables

Description

Procedural style:

bool maxdb_stmt_fetch ( resource stmt )

Object oriented style (method):

class stmt {

bool fetch ( void )

}

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

Return values

Tabella 1. Return values

ValueDescription
TRUESuccess. Data has been fetched
FALSEError occured
NULLNo more rows/data exists

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}
 
$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = $maxdb->prepare($query)) {

   /* execute statement */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* fetch values */
   while ($stmt->fetch()) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = maxdb_prepare($link, $query)) {

   /* execute statement */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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)

maxdb_stmt_free_result

(PECL)

maxdb_stmt_free_result

(no version information, might be only in CVS)

stmt->free_result -- Frees stored result memory for the given statement handle

Description

Procedural style:

void maxdb_stmt_free_result ( resource stmt )

Object oriented style (method):

class stmt {

void free_result ( void )

}

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

Valori restituiti

This function doesn't return any value.

maxdb_stmt_init

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

Description

Procedural style :

resource maxdb_stmt_init ( resource link )

Object oriented style (property):

class maxdb {

object stmt_init ( void )

}

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.

Valori restituiti

Returns an resource.

Vedere anche:

maxdb_stmt_prepare()

maxdb_stmt_num_rows

(PECL)

maxdb_stmt_num_rows

(no version information, might be only in CVS)

stmt->num_rows -- Return the number of rows in statements result set

Description

Procedural style :

int maxdb_stmt_num_rows ( resource stmt )

Object oriented style (property):

class stmt {

int num_rows

}

Returns the number of rows in the result set.

Return values

An integer representing the number of rows in result set.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Number of rows: 25.

maxdb_stmt_param_count

(PECL)

maxdb_stmt_param_count

(no version information, might be only in CVS)

stmt->param_count -- Returns the number of parameter for the given statement

Description

Procedural style:

int maxdb_stmt_param_count ( resource stmt )

Object oriented style (property):

class stmt {

int param_count

}

maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Valori restituiti

returns an integer representing the number of parameters.

Vedere anche:

maxdb_prepare()

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = $maxdb->prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = $stmt->param_count;
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = maxdb_prepare($link, "SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = maxdb_stmt_param_count($stmt);
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Statement has 2 markers.

maxdb_stmt_prepare

(PECL)

maxdb_stmt_prepare

(no version information, might be only in CVS)

stmt->prepare --  Prepare a SQL statement for execution

Description

Procedure style:

bool maxdb_stmt_prepare ( resource stmt, string query )

Object oriented style (method)

class stmt {

mixed prepare ( string query )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt =  $maxdb->stmt_init();
if ($stmt->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
} 

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt = maxdb_stmt_init($link);
if (maxdb_stmt_prepare($stmt, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
} 

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Portland is in district OR

maxdb_stmt_reset

(PECL)

maxdb_stmt_reset

(no version information, might be only in CVS)

stmt->reset -- Resets a prepared statement

Description

Procedural style:

bool maxdb_stmt_reset ( resource stmt )

Object oriented style (method):

class stmt {

bool reset ( void )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

maxdb_stmt_result_metadata

(PECL)

maxdb_stmt_result_metadata -- Returns result set metadata from a prepared statement

Description

Procedural style:

resource maxdb_stmt_result_metadata ( resource stmt )

Object oriented style (method):

class stmt {

resource result_metadata ( void )

}

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

Valori restituiti

maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occured.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

$maxdb->query("CREATE TABLE temp.friends (id int, name varchar(20))"); 
 
$maxdb->query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb->query("INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = $maxdb->prepare("SELECT id, name FROM temp.friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_query($link, "CREATE TABLE temp.friends (id int, name varchar(20))"); 
 
maxdb_query($link, "INSERT INTO temp.friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = maxdb_prepare($link, "SELECT id, name FROM temp.friends");
maxdb_stmt_execute($stmt);

/* get resultset for metadata */
$result = maxdb_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = maxdb_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Fieldname: ID

maxdb_stmt_send_long_data

(PECL)

maxdb_stmt_send_long_data

(no version information, might be only in CVS)

stmt->send_long_data -- Send data in blocks

Description

Procedural style:

bool maxdb_stmt_send_long_data ( resource stmt, int param_nr, string data )

Object oriented style (method)

class stmt {

bool stmt_send_long_data ( int param_nr, string data )

}

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

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

maxdb_stmt_sqlstate

(PECL)

maxdb_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation

Description

string maxdb_stmt_sqlstate ( resource stmt )

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.

Return values

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->sqlstate);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_sqlstate($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

maxdb_stmt_store_result

(PECL)

maxdb_stmt_store_result

(no version information, might be only in CVS)

maxdb->store_result -- Transfers a result set from a prepared statement

Description

Procedural style:

bool maxdb_stmt_store_result ( resource stmt )

Object oriented style (method):

class maxdb {

object store_result ( void )

}

maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

Esempio 1. Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* free result */
   $stmt->free_result();

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */ 
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* free result */
   maxdb_stmt_free_result($stmt);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Number of rows: 25.

maxdb_store_result

(PECL)

maxdb_store_result

(no version information, might be only in CVS)

maxdb->store_result -- Transfers a result set from the last query

Description

Procedural style:

resource maxdb_store_result ( resource link )

Object oriented style (method):

class maxdb {

object store_result ( void )

}

This function has no functionally effect.

Return values

Returns a result resource or FALSE if an error occurred.

Example

See maxdb_multi_query().

maxdb_thread_id

(PECL)

maxdb_thread_id

(no version information, might be only in CVS)

maxdb->thread_id -- Returns the thread ID for the current connection

Description

Procedural style:

int maxdb_thread_id ( resource link )

Object oriented style (property):

class maxdb {

int thread_id

}

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.

Return values

maxdb_thread_id() returns the Thread ID for the current connection.

See also

maxdb_kill()

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

maxdb_thread_safe

(no version information, might be only in CVS)

maxdb_thread_safe -- Returns whether thread safety is given or not

Description

Procedural style:

bool maxdb_thread_safe ( void )

maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.

Return values

TRUE if the client library is thread-safe, otherwise FALSE.

maxdb_use_result

(PECL)

maxdb_use_result

(no version information, might be only in CVS)

maxdb->use_result -- Initiate a result set retrieval

Description

Procedural style:

resource maxdb_use_result ( resource link )

Object oriented style (method):

class maxdb {

resource use_result ( void )

}

maxdb_use_result() has no effect.

Return values

Returns result or FALSE in case of error.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->use_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_use_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

The above examples would produce the following output:

a

maxdb_warning_count

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

Description

Procedural style:

int maxdb_warning_count ( resource link )

Object oriented style (property):

class maxdb {

int warning_count

}

maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Return values

Number of warnings or zero if there are no warnings.

Example

Esempio 1. Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$maxdb->query($query);

printf ("Number of warning: %d\n", $maxdb->warning_count);

/* close connection */
$maxdb->close();
?>

Esempio 2. Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable long city name in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

maxdb_query($link, $query);

printf ("Number of warning: %d\n", maxdb_warning_count($link));

/* close connection */
maxdb_close($link);
?>

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

LXXI. MCAL Functions

Introduzione

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.


Requisiti

This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.


Installazione

After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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

MCAL_MONDAY (integer)

MCAL_TUESDAY (integer)

MCAL_WEDNESDAY (integer)

MCAL_THURSDAY (integer)

MCAL_FRIDAY (integer)

MCAL_SATURDAY (integer)

MCAL_JANUARY (integer)

MCAL_FEBRUARY (integer)

MCAL_MARCH (integer)

MCAL_APRIL (integer)

MCAL_MAY (integer)

MCAL_JUNE (integer)

MCAL_JULY (integer)

MCAL_AUGUST (integer)

MCAL_SEPTEMBER (integer)

MCAL_OCTOBER (integer)

MCAL_NOVEMBER (integer)

MCAL_DECEMBER (integer)

MCAL_RECUR_NONE (integer)

MCAL_RECUR_DAILY (integer)

MCAL_RECUR_WEEKLY (integer)

MCAL_RECUR_MONTHLY_MDAY (integer)

MCAL_RECUR_MONTHLY_WDAY (integer)

MCAL_RECUR_YEARLY (integer)

MCAL_M_SUNDAY (integer)

MCAL_M_MONDAY (integer)

MCAL_M_TUESDAY (integer)

MCAL_M_WEDNESDAY (integer)

MCAL_M_THURSDAY (integer)

MCAL_M_FRIDAY (integer)

MCAL_M_SATURDAY (integer)

MCAL_M_WEEKDAYS (integer)

MCAL_M_WEEKEND (integer)

MCAL_M_ALLDAYS (integer)

Sommario
mcal_append_event -- Store a new event into an MCAL calendar
mcal_close -- Close an MCAL stream
mcal_create_calendar -- Create a new MCAL calendar
mcal_date_compare -- Compares two dates
mcal_date_valid --  Returns TRUE if the given year, month, day is a valid date
mcal_day_of_week --  Returns the day of the week of the given date
mcal_day_of_year --  Returns the day of the year of the given date
mcal_days_in_month --  Returns the number of days in a month
mcal_delete_calendar -- Delete an MCAL calendar
mcal_delete_event -- Delete an event from an MCAL calendar
mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure
mcal_event_init --  Initializes a streams global event structure
mcal_event_set_alarm --  Sets the alarm of the streams global event structure
mcal_event_set_category --  Sets the category of the streams global event structure
mcal_event_set_class --  Sets the class of the streams global event structure
mcal_event_set_description --  Sets the description of the streams global event structure
mcal_event_set_end --  Sets the end date and time of the streams global event structure
mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure
mcal_event_set_start --  Sets the start date and time of the streams global event structure
mcal_event_set_title --  Sets the title of the streams global event structure
mcal_expunge --  Deletes all events marked for being expunged
mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure
mcal_fetch_event --  Fetches an event from the calendar stream
mcal_is_leap_year --  Returns if the given year is a leap year or not
mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime
mcal_list_events --  Return a list of IDs for a date or a range of dates
mcal_next_recurrence -- Returns the next recurrence of the event
mcal_open -- Opens up an MCAL connection
mcal_popen -- Opens up a persistent MCAL connection
mcal_rename_calendar -- Rename an MCAL calendar
mcal_reopen -- Reopens an MCAL connection
mcal_snooze -- Turn off an alarm for an event
mcal_store_event -- Modify an existing event in an MCAL calendar
mcal_time_valid --  Returns TRUE if the given hour, minutes and seconds is a valid time
mcal_week_of_year --  Returns the week number of the given date

mcal_append_event

(PHP 4, PECL)

mcal_append_event -- Store a new event into an MCAL calendar

Description

int mcal_append_event ( int mcal_stream )

mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_stream.

Returns the id of the newly inserted event.

mcal_close

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_close -- Close an MCAL stream

Description

bool mcal_close ( int mcal_stream [, int flags] )

Closes the given mcal stream.

mcal_create_calendar

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_create_calendar -- Create a new MCAL calendar

Description

bool mcal_create_calendar ( int stream, string calendar )

Creates a new calendar named calendar.

mcal_date_compare

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_date_compare -- Compares two dates

Description

int mcal_date_compare ( int a_year, int a_month, int a_day, int b_year, int b_month, int b_day )

mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.

mcal_date_valid

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_date_valid --  Returns TRUE if the given year, month, day is a valid date

Description

bool mcal_date_valid ( int year, int month, int day )

mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.

mcal_day_of_week

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_day_of_week --  Returns the day of the week of the given date

Description

int mcal_day_of_week ( int year, int month, int day )

mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.

mcal_day_of_year

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_day_of_year --  Returns the day of the year of the given date

Description

int mcal_day_of_year ( int year, int month, int day )

mcal_day_of_year() returns the day of the year of the given date.

mcal_days_in_month

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_days_in_month --  Returns the number of days in a month

Description

int mcal_days_in_month ( int month, int leap_year )

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.

mcal_delete_calendar

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_delete_calendar -- Delete an MCAL calendar

Description

bool mcal_delete_calendar ( int stream, string calendar )

Deletes the calendar named calendar.

mcal_delete_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_delete_event -- Delete an event from an MCAL calendar

Description

bool mcal_delete_event ( int mcal_stream, int event_id )

mcal_delete_event() deletes the calendar event specified by the event_id.

Returns TRUE.

mcal_event_add_attribute

(PHP 3 >= 3.0.15, PHP 4, PECL)

mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure

Description

bool mcal_event_add_attribute ( int stream, string attribute, string value )

mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".

mcal_event_init

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_init --  Initializes a streams global event structure

Description

void mcal_event_init ( int stream )

mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.

mcal_event_set_alarm

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_alarm --  Sets the alarm of the streams global event structure

Description

void mcal_event_set_alarm ( int stream, int alarm )

mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.

mcal_event_set_category

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_category --  Sets the category of the streams global event structure

Description

void mcal_event_set_category ( int stream, string category )

mcal_event_set_category() sets the streams global event structure's category to the given string.

mcal_event_set_class

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_class --  Sets the class of the streams global event structure

Description

void mcal_event_set_class ( int stream, int class )

mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.

mcal_event_set_description

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_description --  Sets the description of the streams global event structure

Description

void mcal_event_set_description ( int stream, string description )

mcal_event_set_description() sets the streams global event structure's description to the given string.

mcal_event_set_end

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_end --  Sets the end date and time of the streams global event structure

Description

void mcal_event_set_end ( int stream, int year, int month, int day [, int hour [, int min [, int sec]]] )

mcal_event_set_end() sets the streams global event structure's end date and time to the given values.

mcal_event_set_recur_daily

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_daily ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccurring on a daily basis, ending at the given date.

mcal_event_set_recur_monthly_mday

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_monthly_mday ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by month day basis, ending at the given date.

mcal_event_set_recur_monthly_wday

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_monthly_wday ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by week basis, ending at the given date.

mcal_event_set_recur_none

(PHP 3 >= 3.0.15, PHP 4, PECL)

mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_none ( int stream )

mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).

mcal_event_set_recur_weekly

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_weekly ( int stream, int year, int month, int day, int interval, int weekdays )

mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccurring on a weekly basis, ending at the given date.

mcal_event_set_recur_yearly

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure

Description

void mcal_event_set_recur_yearly ( int stream, int year, int month, int day, int interval )

mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccurring on a yearly basis,ending at the given date.

mcal_event_set_start

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_start --  Sets the start date and time of the streams global event structure

Description

void mcal_event_set_start ( int stream, int year, int month, int day [, int hour [, int min [, int sec]]] )

mcal_event_set_start() sets the streams global event structure's start date and time to the given values.

mcal_event_set_title

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_event_set_title --  Sets the title of the streams global event structure

Description

void mcal_event_set_title ( int stream, string title )

mcal_event_set_title() sets the streams global event structure's title to the given string.

mcal_expunge

(no version information, might be only in CVS)

mcal_expunge --  Deletes all events marked for being expunged

Description

bool mcal_expunge ( int stream )

mcal_expunge() deletes all events which have been previously marked for deletion.

mcal_fetch_current_stream_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure

Description

object mcal_fetch_current_stream_event ( int stream )

mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

mcal_fetch_event

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_fetch_event --  Fetches an event from the calendar stream

Description

object mcal_fetch_event ( int mcal_stream, int event_id [, int options] )

mcal_fetch_event() fetches an event from the calendar stream specified by id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

The possible values for recur_type are:

  • 0 - Indicates that this event does not recur

  • 1 - This event recurs daily

  • 2 - This event recurs on a weekly basis

  • 3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)

  • 4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)

  • 5 - This event recurs on an annual basis

mcal_is_leap_year

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_is_leap_year --  Returns if the given year is a leap year or not

Description

bool mcal_is_leap_year ( int year )

mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.

mcal_list_alarms

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime

Description

array mcal_list_alarms ( int mcal_stream [, int begin_year, int begin_month, int begin_day, int end_year, int end_month, int end_day] )

Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_list_events

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_list_events --  Return a list of IDs for a date or a range of dates

Description

array mcal_list_events ( int mcal_stream [, int begin_year, int begin_month, int begin_day, int end_year, int end_month, int end_day] )

Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_next_recurrence

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_next_recurrence -- Returns the next recurrence of the event

Description

object mcal_next_recurrence ( int stream, int weekstart, array next )

mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.

mcal_open

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_open -- Opens up an MCAL connection

Description

int mcal_open ( string calendar, string username, string password [, int options] )

Returns an MCAL stream on success, FALSE on error.

mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_popen

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_popen -- Opens up a persistent MCAL connection

Description

int mcal_popen ( string calendar, string username, string password [, int options] )

Returns an MCAL stream on success, FALSE on error.

mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_rename_calendar

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_rename_calendar -- Rename an MCAL calendar

Description

bool mcal_rename_calendar ( int stream, string old_name, string new_name )

Renames the calendar old_name to new_name.

mcal_reopen

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_reopen -- Reopens an MCAL connection

Description

bool mcal_reopen ( int mcal_stream, string calendar [, int options] )

Reopens an MCAL stream to a new calendar.

mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

mcal_snooze

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_snooze -- Turn off an alarm for an event

Description

bool mcal_snooze ( int stream_id, int event_id )

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

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_store_event -- Modify an existing event in an MCAL calendar

Description

int mcal_store_event ( int mcal_stream )

mcal_store_event() stores the modifications to the current global event for the given stream.

Returns the event id of the modified event on success and FALSE on error.

mcal_time_valid

(PHP 3 >= 3.0.13, PHP 4, PECL)

mcal_time_valid --  Returns TRUE if the given hour, minutes and seconds is a valid time

Description

bool mcal_time_valid ( int hour, int minutes, int seconds )

mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.

mcal_week_of_year

(PHP 4, PECL)

mcal_week_of_year --  Returns the week number of the given date

Description

int mcal_week_of_year ( int day, int month, int year )

mcal_week_of_year() returns the week number of the given date.

LXXII. Mcrypt Encryption Functions

Introduzione

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


Requisiti

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.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Mcrypt configuration options

NameDefaultChangeableChangelog
mcrypt.algorithms_dirNULLPHP_INI_ALLAvailable since PHP 4.0.2.
mcrypt.modes_dirNULLPHP_INI_ALLAvailable since PHP 4.0.2.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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:

MCRYPT_ENCRYPT (integer)

MCRYPT_DECRYPT (integer)

MCRYPT_DEV_RANDOM (integer)

MCRYPT_DEV_URANDOM (integer)

MCRYPT_RAND (integer)


Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES

  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)

  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)

  • MCRYPT_BLOWFISH

  • MCRYPT_CAST_128

  • MCRYPT_CAST_256

  • MCRYPT_CRYPT

  • MCRYPT_DES

  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)

  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)

  • MCRYPT_GOST

  • MCRYPT_IDEA (non-free)

  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)

  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)

  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)

  • MCRYPT_RC2

  • MCRYPT_RC4 (libmcrypt 2.2.x only)

  • MCRYPT_RC6 (libmcrypt > 2.4.x only)

  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)

  • MCRYPT_SAFER64

  • MCRYPT_SAFER128

  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)

  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)

  • MCRYPT_TEAN (libmcrypt 2.2.x only)

  • MCRYPT_THREEWAY

  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)

  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )

  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)

  • MCRYPT_TWOFISH192

  • MCRYPT_TWOFISH256

  • MCRYPT_WAKE (libmcrypt > 2.4.x only)

  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).


Esempi

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.

Esempio 1. Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Esempio 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Sommario
mcrypt_cbc -- Encrypt/decrypt data in CBC mode
mcrypt_cfb -- Encrypt/decrypt data in CFB mode
mcrypt_create_iv --  Create an initialization vector (IV) from a random source
mcrypt_decrypt -- Decrypts crypttext with given parameters
mcrypt_ecb -- Deprecated: Encrypt/decrypt data in ECB mode
mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm
mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm
mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm
mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode
mcrypt_enc_get_modes_name -- Returns the name of the opened mode
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm
mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks
mcrypt_enc_self_test -- This function runs a self test on the opened module
mcrypt_encrypt -- Encrypts plaintext with given parameters
mcrypt_generic_deinit --  This function deinitializes an encryption module
mcrypt_generic_end -- This function terminates encryption
mcrypt_generic_init -- This function initializes all buffers needed for encryption
mcrypt_generic -- This function encrypts data
mcrypt_get_block_size -- Get the block size of the specified cipher
mcrypt_get_cipher_name -- Get the name of the specified cipher
mcrypt_get_iv_size --  Returns the size of the IV belonging to a specific cipher/mode combination
mcrypt_get_key_size -- Get the key size of the specified cipher
mcrypt_list_algorithms -- Get an array of all supported ciphers
mcrypt_list_modes -- Get an array of all supported modes
mcrypt_module_close --  Close the mcrypt module
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm
mcrypt_module_is_block_algorithm_mode -- Returns if the specified module is a block algorithm or not
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm
mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or not
mcrypt_module_open -- Opens the module of the algorithm and the mode to be used
mcrypt_module_self_test -- This function runs a self test on the specified module
mcrypt_ofb -- Encrypt/decrypt data in OFB mode
mdecrypt_generic -- Decrypt data

mcrypt_cbc

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

mcrypt_cbc -- Encrypt/decrypt data in CBC mode

Description

string mcrypt_cbc ( int cipher, string key, string data, int mode [, string iv] )

string mcrypt_cbc ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. 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.

mcrypt_cfb

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

mcrypt_cfb -- Encrypt/decrypt data in CFB mode

Description

string mcrypt_cfb ( int cipher, string key, string data, int mode, string iv )

string mcrypt_cfb ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. 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.

mcrypt_create_iv

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

mcrypt_create_iv --  Create an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int size [, int source] )

mcrypt_create_iv() is used to create an IV.

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.

Esempio 1. mcrypt_create_iv() example

<?php
    $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without 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

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_decrypt -- Decrypts crypttext with given parameters

Description

string mcrypt_decrypt ( string cipher, string key, string data, string mode [, string iv] )

mcrypt_decrypt() decrypts the data and returns the unencrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.

Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

mcrypt_ecb

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

mcrypt_ecb -- Deprecated: Encrypt/decrypt data in ECB mode

Description

string mcrypt_ecb ( int cipher, string key, string data, int mode )

string mcrypt_ecb ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. 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.

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm

Description

string mcrypt_enc_get_algorithms_name ( resource td )

This function returns the name of the algorithm.

Esempio 1. mcrypt_enc_get_algorithms_name() example

<?php
$td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
  
$td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?>

Il precedente esempio visualizzerà:

CAST-256
CAST-256

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm

Description

int mcrypt_enc_get_block_size ( resource td )

This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm

Description

int mcrypt_enc_get_iv_size ( resource td )

This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_enc_get_key_size ( resource td )

This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_modes_name -- Returns the name of the opened mode

Description

string mcrypt_enc_get_modes_name ( resource td )

This function returns the name of the mode.

Esempio 1. mcrypt_enc_get_modes_name() example

<?php
    $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
    echo mcrypt_enc_get_modes_name($td). "\n";
  
    $td = mcrypt_module_open ('cast-256', '', 'ecb', '');
    echo mcrypt_enc_get_modes_name($td). "\n";
?>

Prints:

CFB
ECB

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_enc_get_supported_key_sizes ( resource td )

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

Esempio 1. mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
    var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>

This will print:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks

Description

bool mcrypt_enc_is_block_algorithm_mode ( resource td )

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).

mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm

Description

bool mcrypt_enc_is_block_algorithm ( resource td )

This function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks

Description

bool mcrypt_enc_is_block_mode ( resource td )

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_self_test -- This function runs a self test on the opened module

Description

int mcrypt_enc_self_test ( resource td )

This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_encrypt -- Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string cipher, string key, string data, string mode [, string iv] )

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Esempio 1. mcrypt_encrypt() Example

<?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen($text) . "\n";

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
?>

Il precedente esempio visualizzerà:

42
64

See also mcrypt_module_open() for a more advanced API and an example.

mcrypt_generic_deinit

(PHP 4 >= 4.1.1, PHP 5)

mcrypt_generic_deinit --  This function deinitializes an encryption module

Description

bool mcrypt_generic_deinit ( resource td )

This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.) Returns FALSE on error, or TRUE on success.

See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().

mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_end -- This function terminates encryption

Description

bool mcrypt_generic_end ( resource td )

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.

mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_init -- This function initializes all buffers needed for encryption

Description

int mcrypt_generic_init ( resource td, string key, string iv )

The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.

The function returns a negative value on error, -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().

mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic -- This function encrypts data

Description

string mcrypt_generic ( resource td, string data )

This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.

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

mcrypt_get_block_size

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

mcrypt_get_block_size -- Get the block size of the specified cipher

Description

int mcrypt_get_block_size ( int cipher )

int mcrypt_get_block_size ( string cipher, string module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

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.

Esempio 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_block_size('tripledes', 'ecb');
?>

Prints:
8

See also: mcrypt_get_key_size(), mcrypt_enc_get_block_size() and mcrypt_encrypt().

mcrypt_get_cipher_name

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

mcrypt_get_cipher_name -- Get the name of the specified cipher

Description

string mcrypt_get_cipher_name ( int cipher )

string mcrypt_get_cipher_name ( string cipher )

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.

Esempio 1. mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?>

Il precedente esempio visualizzerà:

3DES

mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_get_iv_size --  Returns the size of the IV belonging to a specific cipher/mode combination

Description

int mcrypt_get_iv_size ( string cipher, string mode )

mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode is one of the MCRYPT_MODE_modename constants 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().

Esempio 1. mcrypt_get_iv_size() example

<?php
    echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";

    echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?>

See also mcrypt_get_block_size(), mcrypt_enc_get_iv_size() and mcrypt_create_iv().

mcrypt_get_key_size

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

mcrypt_get_key_size -- Get the key size of the specified cipher

Description

int mcrypt_get_key_size ( int cipher )

int mcrypt_get_key_size ( string cipher, string module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x. 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

<?php
    echo mcrypt_get_key_size('tripledes', 'ecb');
?>

Prints:
24

See also: mcrypt_get_block_size(), mcrypt_end_get_key_size() and mcrypt_encrypt().

mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_algorithms -- Get an array of all supported ciphers

Description

array mcrypt_list_algorithms ( [string lib_dir] )

mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.

mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.

Esempio 1. mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_modes -- Get an array of all supported modes

Description

array mcrypt_list_modes ( [string lib_dir] )

mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.

mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.

Esempio 1. mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_close --  Close the mcrypt module

Description

bool mcrypt_module_close ( resource td )

This function closes the specified encryption handle.

See mcrypt_module_open() for an example.

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm

Description

int mcrypt_module_get_algo_block_size ( string algorithm [, string lib_dir] )

This function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_module_get_algo_key_size ( string algorithm [, string lib_dir] )

This function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_module_get_supported_key_sizes ( string algorithm [, string lib_dir] )

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.

See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm_mode -- Returns if the specified module is a block algorithm or not

Description

bool mcrypt_module_is_block_algorithm_mode ( string mode [, string lib_dir] )

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (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.

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm

Description

bool mcrypt_module_is_block_algorithm ( string algorithm [, string lib_dir] )

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or not

Description

bool mcrypt_module_is_block_mode ( string mode [, string lib_dir] )

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (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.

mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_open -- Opens the module of the algorithm and the mode to be used

Description

resource mcrypt_module_open ( string algorithm, string algorithm_directory, string mode, string mode_directory )

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, 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).

Esempio 1. mcrypt_module_open() examples

<?php
    $td = mcrypt_module_open(MCRYPT_DES, '',
        MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher 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

<?php
    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length, used MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key = substr(md5('very secret key'), 0, $ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, 'This is very important data');

    /* Terminate encryption handler */
    mcrypt_generic_deinit($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    /* Show string */
    echo trim($decrypted) . "\n";
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher 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().

mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_self_test -- This function runs a self test on the specified module

Description

bool mcrypt_module_self_test ( string algorithm [, string lib_dir] )

This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

The function returns TRUE if the self test succeeds, or FALSE when if fails.

Esempio 1. mcrypt_module_self_test() example

<?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?>

Il precedente esempio visualizzerà:

bool(true)
bool(false)

mcrypt_ofb

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

mcrypt_ofb -- Encrypt/decrypt data in OFB mode

Description

string mcrypt_ofb ( int cipher, string key, string data, int mode, string iv )

string mcrypt_ofb ( string cipher, string key, string data, int mode [, string iv] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. 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.

mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mdecrypt_generic -- Decrypt data

Description

string mdecrypt_generic ( resource td, string data )

This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.

Esempio 1. mdecrypt_generic() example

<?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';
   
    /* Open module, and create IV */ 
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic($td, $plain_text);
        mcrypt_generic_deinit($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init($td, $key, $iv);
        $p_t = mdecrypt_generic($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
    }

    if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?>

The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should 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().

LXXIII. MCVE Payment Functions

Introduzione

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.


Installazione

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/.


Vedere anche:

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.


Costanti predefinite

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.

MC_TRANTYPE (integer)

MC_USERNAME (integer)

MC_PASSWORD (integer)

MC_ACCOUNT (integer)

MC_TRACKDATA (integer)

MC_EXPDATE (integer)

MC_STREET (integer)

MC_ZIP (integer)

MC_CV (integer)

MC_COMMENTS (integer)

MC_CLERKID (integer)

MC_STATIONID (integer)

MC_APPRCODE (integer)

MC_AMOUNT (integer)

MC_PTRANNUM (integer)

MC_TTID (integer)

MC_USER (integer)

MC_PWD (integer)

MC_ACCT (integer)

MC_BDATE (integer)

MC_EDATE (integer)

MC_BATCH (integer)

MC_FILE (integer)

MC_ADMIN (integer)

MC_AUDITTYPE (integer)

MC_CUSTOM (integer)

MC_EXAMOUNT (integer)

MC_EXCHARGES (integer)

MC_RATE (integer)

MC_RENTERNAME (integer)

MC_RETURNCITY (integer)

MC_RETURNSTATE (integer)

MC_RETURNLOCATION (integer)

MC_PRIORITY (integer)

MC_INQUIRY (integer)

MC_CARDTYPES (integer)

MC_SUB (integer)

MC_MARKER (integer)

MC_DEVICETYPE (integer)

MC_ERRORCODE (integer)

MC_NEWBATCH (integer)

MC_CURR (integer)

MC_DESCMERCH (integer)

MC_DESCLOC (integer)

MC_ORIGTYPE (integer)

MC_PIN (integer)

MC_VOIDORIGTYPE (integer)

MC_TIMESTAMP (integer)

MC_PRIO_HIGH (integer)

MC_PRIO_NORMAL (integer)

MC_PRIO_LOW (integer)

MC_USER_PROC (integer)

MC_USER_USER (integer)

MC_USER_PWD (integer)

MC_USER_INDCODE (integer)

MC_USER_MERCHID (integer)

MC_USER_BANKID (integer)

MC_USER_TERMID (integer)

MC_USER_CLIENTNUM (integer)

MC_USER_STOREID (integer)

MC_USER_AGENTID (integer)

MC_USER_CHAINID (integer)

MC_USER_ZIPCODE (integer)

MC_USER_TIMEZONE (integer)

MC_USER_MERCHCAT (integer)

MC_USER_MERNAME (integer)

MC_USER_MERCHLOC (integer)

MC_USER_STATECODE (integer)

MC_USER_PHONE (integer)

MC_USER_SUB (integer)

MC_USER_CARDTYPES (integer)

MC_USER_MODE (integer)

MC_USER_VNUMBER (integer)

MC_USER_ROUTINGID (integer)

MC_USER_PPROPERTY (integer)

MC_USER_PID (integer)

MC_USER_PIDPWD (integer)

MC_USER_SMID (integer)

MC_USER_SMIDPWD (integer)

MC_USER_USDDIV (integer)

MC_USER_AUDDIV (integer)

MC_USER_DKKDIV (integer)

MC_USER_GBPDIV (integer)

MC_USER_HKDDIV (integer)

MC_USER_JPYDIV (integer)

MC_USER_NZDDIV (integer)

MC_USER_NOKDIV (integer)

MC_USER_SGDDIV (integer)

MC_USER_ZARDIV (integer)

MC_USER_SEKDIV (integer)

MC_USER_CHFDIV (integer)

MC_USER_CADDIV (integer)

MC_USER_DIVNUM (integer)

MC_CARD_VISA (integer)

MC_CARD_MC (integer)

MC_CARD_AMEX (integer)

MC_CARD_DISC (integer)

MC_CARD_JCB (integer)

MC_CARD_CB (integer)

MC_CARD_DC (integer)

MC_CARD_GIFT (integer)

MC_CARD_OTHER (integer)

MC_CARD_ALL (integer)

MC_MODE_AUTH (integer)

MC_MODE_SETTLE (integer)

MC_MODE_BOTH (integer)

MC_MODE_ALL (integer)

MC_EXCHARGES_REST (integer)

MC_EXCHARGES_GIFT (integer)

MC_EXCHARGES_MINI (integer)

MC_EXCHARGES_TELE (integer)

MC_EXCHARGES_OTHER (integer)

MC_EXCHARGES_LAUND (integer)

MC_EXCHARGES_NONE (integer)

MC_EXCHARGES_GAS (integer)

MC_EXCHARGES_MILE (integer)

MC_EXCHARGES_LATE (integer)

MC_EXCHARGES_1WAY (integer)

MC_EXCHARGES_VIOL (integer)

MC_TRAN_SALE (integer)

MC_TRAN_REDEMPTION (integer)

MC_TRAN_PREAUTH (integer)

MC_TRAN_VOID (integer)

MC_TRAN_PREAUTHCOMPLETE (integer)

MC_TRAN_FORCE (integer)

MC_TRAN_OVERRIDE (integer)

MC_TRAN_RETURN (integer)

MC_TRAN_RELOAD (integer)

MC_TRAN_CREDIT (integer)

MC_TRAN_SETTLE (integer)

MC_TRAN_INCREMENTAL (integer)

MC_TRAN_REVERSAL (integer)

MC_TRAN_ACTIVATE (integer)

MC_TRAN_BALANCEINQ (integer)

MC_TRAN_CASHOUT (integer)

MC_TRAN_TOREVERSAL (integer)

MC_TRAN_SETTLERFR (integer)

MC_TRAN_ISSUE (integer)

MC_TRAN_TIP (integer)

MC_TRAN_MERCHRETURN (integer)

MC_TRAN_IVRREQ (integer)

MC_TRAN_IVRRESP (integer)

MC_TRAN_ADMIN (integer)

MC_TRAN_PING (integer)

MC_TRAN_CHKPWD (integer)

MC_TRAN_CHNGPWD (integer)

MC_TRAN_LISTSTATS (integer)

MC_TRAN_LISTUSERS (integer)

MC_TRAN_GETUSERINFO (integer)

MC_TRAN_ADDUSER (integer)

MC_TRAN_EDITUSER (integer)

MC_TRAN_DELUSER (integer)

MC_TRAN_ENABLEUSER (integer)

MC_TRAN_DISABLEUSER (integer)

MC_TRAN_IMPORT (integer)

MC_TRAN_EXPORT (integer)

MC_TRAN_ERRORLOG (integer)

MC_TRAN_CLEARERRORLOG (integer)

MC_TRAN_GETSUBACCTS (integer)

MC_ADMIN_GUT (integer)

MC_ADMIN_GL (integer)

MC_ADMIN_GFT (integer)

MC_ADMIN_BT (integer)

MC_ADMIN_UB (integer)

MC_ADMIN_QC (integer)

MC_ADMIN_RS (integer)

MC_ADMIN_CTH (integer)

MC_ADMIN_CFH (integer)

MC_ADMIN_FORCESETTLE (integer)

MC_ADMIN_SETBATCHNUM (integer)

MC_ADMIN_RENUMBERBATCH (integer)

MC_ADMIN_FIELDEDIT (integer)

MC_ADMIN_CLOSEBATCH (integer)

MCVE_UNUSED (integer)

MCVE_NEW (integer)

MCVE_PENDING (integer)

MCVE_DONE (integer)

MCVE_GOOD (integer)

MCVE_BAD (integer)

MCVE_STREET (integer)

MCVE_ZIP (integer)

MCVE_UNKNOWN (integer)

MCVE_ERROR (integer)

MCVE_FAIL (integer)

MCVE_SUCCESS (integer)

MCVE_AUTH (integer)

MCVE_DENY (integer)

MCVE_CALL (integer)

MCVE_DUPL (integer)

MCVE_PKUP (integer)

MCVE_RETRY (integer)

MCVE_SETUP (integer)

MCVE_TIMEOUT (integer)

MCVE_SALE (integer)

MCVE_PREAUTH (integer)

MCVE_FORCE (integer)

MCVE_OVERRIDE (integer)

MCVE_RETURN (integer)

MCVE_SETTLE (integer)

MCVE_PROC (integer)

MCVE_USER (integer)

MCVE_PWD (integer)

MCVE_INDCODE (integer)

MCVE_MERCHID (integer)

MCVE_BANKID (integer)

MCVE_TERMID (integer)

MCVE_CLIENTNUM (integer)

MCVE_STOREID (integer)

MCVE_AGENTID (integer)

MCVE_CHAINID (integer)

MCVE_ZIPCODE (integer)

MCVE_TIMEZONE (integer)

MCVE_MERCHCAT (integer)

MCVE_MERNAME (integer)

MCVE_MERCHLOC (integer)

MCVE_STATECODE (integer)

MCVE_SERVICEPHONE (integer)

Sommario
mcve_adduser --  Add an MCVE user using usersetup structure
mcve_adduserarg --  Add a value to user configuration structure
mcve_bt --  Get unsettled batch totals
mcve_checkstatus --  Check to see if a transaction has completed
mcve_chkpwd --  Verify Password
mcve_chngpwd --  Change the system administrator's password
mcve_completeauthorizations --  Number of complete authorizations in queue, returning an array of their identifiers
mcve_connect --  Establish the connection to MCVE
mcve_connectionerror --  Get a textual representation of why a connection failed
mcve_deleteresponse --  Delete specified transaction from MCVE_CONN structure
mcve_deletetrans --  Delete specified transaction from MCVE_CONN structure
mcve_deleteusersetup --  Deallocate data associated with usersetup structure
mcve_deluser --  Delete an MCVE user account
mcve_destroyconn --  Destroy the connection and MCVE_CONN structure
mcve_destroyengine --  Free memory associated with IP/SSL connectivity
mcve_disableuser --  Disable an active MCVE user account
mcve_edituser --  Edit MCVE user using usersetup structure
mcve_enableuser --  Enable an inactive MCVE user account
mcve_force --  Send a FORCE to MCVE (typically, a phone-authorization)
mcve_getcell --  Get a specific cell from a comma delimited response by column name
mcve_getcellbynum --  Get a specific cell from a comma delimited response by column number
mcve_getcommadelimited --  Get the RAW comma delimited data returned from MCVE
mcve_getheader --  Get the name of the column in a comma-delimited response
mcve_getuserarg --  Grab a value from usersetup structure
mcve_getuserparam --  Get a user response parameter
mcve_gft --  Audit MCVE for Failed transactions
mcve_gl --  Audit MCVE for settled transactions
mcve_gut --  Audit MCVE for Unsettled Transactions
mcve_initconn --  Create and initialize an MCVE_CONN structure
mcve_initengine --  Ready the client for IP/SSL Communication
mcve_initusersetup --  Initialize structure to store user data
mcve_iscommadelimited --  Checks to see if response is comma delimited
mcve_liststats --  List statistics for all users on MCVE system
mcve_listusers --  List all users on MCVE system
mcve_maxconntimeout --  The maximum amount of time the API will attempt a connection to MCVE
mcve_monitor --  Perform communication with MCVE (send/receive data) Non-blocking
mcve_numcolumns --  Number of columns returned in a comma delimited response
mcve_numrows --  Number of rows returned in a comma delimited response
mcve_override --  Send an OVERRIDE to MCVE
mcve_parsecommadelimited --  Parse the comma delimited response so mcve_getcell, etc will work
mcve_ping --  Send a ping request to MCVE
mcve_preauth --  Send a PREAUTHORIZATION to MCVE
mcve_preauthcompletion --  Complete a PREAUTHORIZATION, ready it for settlement
mcve_qc --  Audit MCVE for a list of transactions in the outgoing queue
mcve_responseparam --  Get a custom response parameter
mcve_return --  Issue a RETURN or CREDIT to MCVE
mcve_returncode --  Grab the exact return code from the transaction
mcve_returnstatus --  Check to see if the transaction was successful
mcve_sale --  Send a SALE to MCVE
mcve_setblocking --  Set blocking/non-blocking mode for connection
mcve_setdropfile --  Set the connection method to Drop-File
mcve_setip --  Set the connection method to IP
mcve_setssl_files --  Set certificate key files and certificates if server requires client certificate verification
mcve_setssl --  Set the connection method to SSL
mcve_settimeout --  Set maximum transaction time (per trans)
mcve_settle --  Issue a settlement command to do a batch deposit
mcve_text_avs --  Get a textual representation of the return_avs
mcve_text_code --  Get a textual representation of the return_code
mcve_text_cv --  Get a textual representation of the return_cv
mcve_transactionauth --  Get the authorization number returned for the transaction (alpha-numeric)
mcve_transactionavs --  Get the Address Verification return status
mcve_transactionbatch --  Get the batch number associated with the transaction
mcve_transactioncv --  Get the CVC2/CVV2/CID return status
mcve_transactionid --  Get the unique system id for the transaction
mcve_transactionitem --  Get the ITEM number in the associated batch for this transaction
mcve_transactionssent --  Check to see if outgoing buffer is clear
mcve_transactiontext --  Get verbiage (text) return from MCVE or processing institution
mcve_transinqueue --  Number of transactions in client-queue
mcve_transnew --  Start a new transaction
mcve_transparam --  Add a parameter to a transaction
mcve_transsend --  Finalize and send the transaction
mcve_ub --  Get a list of all Unsettled batches
mcve_uwait --  Wait x microsecs
mcve_verifyconnection --  Set whether or not to PING upon connect to verify connection
mcve_verifysslcert --  Set whether or not to verify the server ssl certificate
mcve_void --  VOID a transaction in the settlement queue

mcve_adduser

(PHP 4 >= 4.2.0, PHP 5)

mcve_adduser --  Add an MCVE user using usersetup structure

Description

int mcve_adduser ( resource conn, string admin_password, int usersetup )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_adduserarg

(PHP 4 >= 4.2.0, PHP 5)

mcve_adduserarg --  Add a value to user configuration structure

Description

int mcve_adduserarg ( resource usersetup, int argtype, string argval )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_bt

(PHP 4 >= 4.2.0, PHP 5)

mcve_bt --  Get unsettled batch totals

Description

int mcve_bt ( resource conn, string username, string password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_checkstatus

(PHP 4 >= 4.2.0, PHP 5)

mcve_checkstatus --  Check to see if a transaction has completed

Description

int mcve_checkstatus ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_chkpwd

(PHP 4 >= 4.2.0, PHP 5)

mcve_chkpwd --  Verify Password

Description

int mcve_chkpwd ( resource conn, string username, string password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_chngpwd

(PHP 4 >= 4.2.0, PHP 5)

mcve_chngpwd --  Change the system administrator's password

Description

int mcve_chngpwd ( resource conn, string admin_password, string new_password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_completeauthorizations

(PHP 4 >= 4.2.0, PHP 5)

mcve_completeauthorizations --  Number of complete authorizations in queue, returning an array of their identifiers

Description

int mcve_completeauthorizations ( resource conn, int &array )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_connect

(PHP 4 >= 4.2.0, PHP 5)

mcve_connect --  Establish the connection to MCVE

Description

int mcve_connect ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_connectionerror

(PHP 4 >= 4.3.0, PHP 5)

mcve_connectionerror --  Get a textual representation of why a connection failed

Description

string mcve_connectionerror ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_deleteresponse

(PHP 4 >= 4.2.0, PHP 5)

mcve_deleteresponse --  Delete specified transaction from MCVE_CONN structure

Description

bool mcve_deleteresponse ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_deletetrans

(PHP 4 >= 4.3.0, PHP 5)

mcve_deletetrans --  Delete specified transaction from MCVE_CONN structure

Description

bool mcve_deletetrans ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_deleteusersetup

(PHP 4 >= 4.2.0, PHP 5)

mcve_deleteusersetup --  Deallocate data associated with usersetup structure

Description

void mcve_deleteusersetup ( resource usersetup )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_deluser

(PHP 4 >= 4.2.0, PHP 5)

mcve_deluser --  Delete an MCVE user account

Description

int mcve_deluser ( resource conn, string admin_password, string username )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_destroyconn

(PHP 4 >= 4.2.0, PHP 5)

mcve_destroyconn --  Destroy the connection and MCVE_CONN structure

Description

void mcve_destroyconn ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_destroyengine

(PHP 4 >= 4.2.0, PHP 5)

mcve_destroyengine --  Free memory associated with IP/SSL connectivity

Description

void mcve_destroyengine ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_disableuser

(PHP 4 >= 4.2.0, PHP 5)

mcve_disableuser --  Disable an active MCVE user account

Description

int mcve_disableuser ( resource conn, string admin_password, string username )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_edituser

(PHP 4 >= 4.2.0, PHP 5)

mcve_edituser --  Edit MCVE user using usersetup structure

Description

int mcve_edituser ( resource conn, string admin_password, int usersetup )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_enableuser

(PHP 4 >= 4.2.0, PHP 5)

mcve_enableuser --  Enable an inactive MCVE user account

Description

int mcve_enableuser ( resource conn, string admin_password, string username )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_force

(PHP 4 >= 4.2.0, PHP 5)

mcve_force --  Send a FORCE to MCVE (typically, a phone-authorization)

Description

int mcve_force ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string authcode, string comments, string clerkid, string stationid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_getcell

(PHP 4 >= 4.2.0, PHP 5)

mcve_getcell --  Get a specific cell from a comma delimited response by column name

Description

string mcve_getcell ( resource conn, int identifier, string column, int row )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_getcellbynum

(PHP 4 >= 4.2.0, PHP 5)

mcve_getcellbynum --  Get a specific cell from a comma delimited response by column number

Description

string mcve_getcellbynum ( resource conn, int identifier, int column, int row )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_getcommadelimited

(PHP 4 >= 4.2.0, PHP 5)

mcve_getcommadelimited --  Get the RAW comma delimited data returned from MCVE

Description

string mcve_getcommadelimited ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_getheader

(PHP 4 >= 4.2.0, PHP 5)

mcve_getheader --  Get the name of the column in a comma-delimited response

Description

string mcve_getheader ( resource conn, int identifier, int column_num )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_getuserarg

(PHP 4 >= 4.2.0, PHP 5)

mcve_getuserarg --  Grab a value from usersetup structure

Description

string mcve_getuserarg ( resource usersetup, int argtype )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_getuserparam

(PHP 4 >= 4.3.0, PHP 5)

mcve_getuserparam --  Get a user response parameter

Description

string mcve_getuserparam ( resource conn, int identifier, int key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_gft

(PHP 4 >= 4.2.0, PHP 5)

mcve_gft --  Audit MCVE for Failed transactions

Description

int mcve_gft ( resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_gl

(PHP 4 >= 4.2.0, PHP 5)

mcve_gl --  Audit MCVE for settled transactions

Description

int mcve_gl ( int conn, string username, string password, int type, string account, string batch, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_gut

(PHP 4 >= 4.2.0, PHP 5)

mcve_gut --  Audit MCVE for Unsettled Transactions

Description

int mcve_gut ( resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_initconn

(PHP 4 >= 4.2.0, PHP 5)

mcve_initconn --  Create and initialize an MCVE_CONN structure

Description

resource mcve_initconn ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_initengine

(PHP 4 >= 4.2.0, PHP 5)

mcve_initengine --  Ready the client for IP/SSL Communication

Description

int mcve_initengine ( string location )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_initusersetup

(PHP 4 >= 4.2.0, PHP 5)

mcve_initusersetup --  Initialize structure to store user data

Description

resource mcve_initusersetup ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_iscommadelimited

(PHP 4 >= 4.2.0, PHP 5)

mcve_iscommadelimited --  Checks to see if response is comma delimited

Description

int mcve_iscommadelimited ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_liststats

(PHP 4 >= 4.2.0, PHP 5)

mcve_liststats --  List statistics for all users on MCVE system

Description

int mcve_liststats ( resource conn, string admin_password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_listusers

(PHP 4 >= 4.2.0, PHP 5)

mcve_listusers --  List all users on MCVE system

Description

int mcve_listusers ( resource conn, string admin_password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_maxconntimeout

(PHP 4 >= 4.3.0, PHP 5)

mcve_maxconntimeout --  The maximum amount of time the API will attempt a connection to MCVE

Description

bool mcve_maxconntimeout ( resource conn, int secs )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_monitor

(PHP 4 >= 4.2.0, PHP 5)

mcve_monitor --  Perform communication with MCVE (send/receive data) Non-blocking

Description

int mcve_monitor ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_numcolumns

(PHP 4 >= 4.2.0, PHP 5)

mcve_numcolumns --  Number of columns returned in a comma delimited response

Description

int mcve_numcolumns ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_numrows

(PHP 4 >= 4.2.0, PHP 5)

mcve_numrows --  Number of rows returned in a comma delimited response

Description

int mcve_numrows ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_override

(PHP 4 >= 4.2.0, PHP 5)

mcve_override --  Send an OVERRIDE to MCVE

Description

int mcve_override ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_parsecommadelimited

(PHP 4 >= 4.2.0, PHP 5)

mcve_parsecommadelimited --  Parse the comma delimited response so mcve_getcell, etc will work

Description

int mcve_parsecommadelimited ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_ping

(PHP 4 >= 4.3.0, PHP 5)

mcve_ping --  Send a ping request to MCVE

Description

int mcve_ping ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_preauth

(PHP 4 >= 4.2.0, PHP 5)

mcve_preauth --  Send a PREAUTHORIZATION to MCVE

Description

int mcve_preauth ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_preauthcompletion

(PHP 4 >= 4.2.0, PHP 5)

mcve_preauthcompletion --  Complete a PREAUTHORIZATION, ready it for settlement

Description

int mcve_preauthcompletion ( resource conn, string username, string password, float finalamount, int sid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_qc

(PHP 4 >= 4.2.0, PHP 5)

mcve_qc --  Audit MCVE for a list of transactions in the outgoing queue

Description

int mcve_qc ( resource conn, string username, string password, string clerkid, string stationid, string comments, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_responseparam

(PHP 4 >= 4.3.0, PHP 5)

mcve_responseparam --  Get a custom response parameter

Description

string mcve_responseparam ( resource conn, int identifier, string key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_return

(PHP 4 >= 4.2.0, PHP 5)

mcve_return --  Issue a RETURN or CREDIT to MCVE

Description

int mcve_return ( int conn, string username, string password, string trackdata, string account, string expdate, float amount, string comments, string clerkid, string stationid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_returncode

(PHP 4 >= 4.2.0, PHP 5)

mcve_returncode --  Grab the exact return code from the transaction

Description

int mcve_returncode ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_returnstatus

(PHP 4 >= 4.2.0, PHP 5)

mcve_returnstatus --  Check to see if the transaction was successful

Description

int mcve_returnstatus ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_sale

(PHP 4 >= 4.2.0, PHP 5)

mcve_sale --  Send a SALE to MCVE

Description

int mcve_sale ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_setblocking

(PHP 4 >= 4.3.0, PHP 5)

mcve_setblocking --  Set blocking/non-blocking mode for connection

Description

int mcve_setblocking ( resource conn, int tf )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_setdropfile

(PHP 4 >= 4.2.0, PHP 5)

mcve_setdropfile --  Set the connection method to Drop-File

Description

int mcve_setdropfile ( resource conn, string directory )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_setip

(PHP 4 >= 4.2.0, PHP 5)

mcve_setip --  Set the connection method to IP

Description

int mcve_setip ( resource conn, string host, int port )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_setssl_files

(PHP 4 >= 4.3.3, PHP 5)

mcve_setssl_files --  Set certificate key files and certificates if server requires client certificate verification

Description

int mcve_setssl_files ( string sslkeyfile, string sslcertfile )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_setssl

(PHP 4 >= 4.2.0, PHP 5)

mcve_setssl --  Set the connection method to SSL

Description

int mcve_setssl ( resource conn, string host, int port )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_settimeout

(PHP 4 >= 4.2.0, PHP 5)

mcve_settimeout --  Set maximum transaction time (per trans)

Description

int mcve_settimeout ( resource conn, int seconds )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_settle

(PHP 4 >= 4.2.0, PHP 5)

mcve_settle --  Issue a settlement command to do a batch deposit

Description

int mcve_settle ( resource conn, string username, string password, string batch )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_text_avs

(PHP 4 >= 4.3.0, PHP 5)

mcve_text_avs --  Get a textual representation of the return_avs

Description

string mcve_text_avs ( string code )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_text_code

(PHP 4 >= 4.3.0, PHP 5)

mcve_text_code --  Get a textual representation of the return_code

Description

string mcve_text_code ( string code )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_text_cv

(PHP 4 >= 4.3.0, PHP 5)

mcve_text_cv --  Get a textual representation of the return_cv

Description

string mcve_text_cv ( int code )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactionauth

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactionauth --  Get the authorization number returned for the transaction (alpha-numeric)

Description

string mcve_transactionauth ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactionavs

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactionavs --  Get the Address Verification return status

Description

int mcve_transactionavs ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactionbatch

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactionbatch --  Get the batch number associated with the transaction

Description

int mcve_transactionbatch ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactioncv

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactioncv --  Get the CVC2/CVV2/CID return status

Description

int mcve_transactioncv ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactionid

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactionid --  Get the unique system id for the transaction

Description

int mcve_transactionid ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactionitem

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactionitem --  Get the ITEM number in the associated batch for this transaction

Description

int mcve_transactionitem ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactionssent

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactionssent --  Check to see if outgoing buffer is clear

Description

int mcve_transactionssent ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transactiontext

(PHP 4 >= 4.2.0, PHP 5)

mcve_transactiontext --  Get verbiage (text) return from MCVE or processing institution

Description

string mcve_transactiontext ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transinqueue

(PHP 4 >= 4.2.0, PHP 5)

mcve_transinqueue --  Number of transactions in client-queue

Description

int mcve_transinqueue ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transnew

(PHP 4 >= 4.3.0, PHP 5)

mcve_transnew --  Start a new transaction

Description

int mcve_transnew ( resource conn )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transparam

(PHP 4 >= 4.3.0, PHP 5)

mcve_transparam --  Add a parameter to a transaction

Description

int mcve_transparam ( resource conn, int identifier, int key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_transsend

(PHP 4 >= 4.3.0, PHP 5)

mcve_transsend --  Finalize and send the transaction

Description

int mcve_transsend ( resource conn, int identifier )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_ub

(PHP 4 >= 4.2.0, PHP 5)

mcve_ub --  Get a list of all Unsettled batches

Description

int mcve_ub ( resource conn, string username, string password )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_uwait

(PHP 4 >= 4.3.0, PHP 5)

mcve_uwait --  Wait x microsecs

Description

int mcve_uwait ( int microsecs )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_verifyconnection

(PHP 4 >= 4.3.0, PHP 5)

mcve_verifyconnection --  Set whether or not to PING upon connect to verify connection

Description

bool mcve_verifyconnection ( resource conn, int tf )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_verifysslcert

(PHP 4 >= 4.3.0, PHP 5)

mcve_verifysslcert --  Set whether or not to verify the server ssl certificate

Description

bool mcve_verifysslcert ( resource conn, int tf )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mcve_void

(PHP 4 >= 4.2.0, PHP 5)

mcve_void --  VOID a transaction in the settlement queue

Description

int mcve_void ( resource conn, string username, string password, int sid, int ptrannum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LXXIV. Memcache Functions

Introduzione

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/.


Requisiti

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.


Installazione

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/.


Costanti predefinite

Tabella 1. MemCache Constants

NameDescription
MEMCACHE_COMPRESSED (integer) Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() e Memcache::replace().

Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.


Esempi

Esempio 1. memcache extension overview example

<?php

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";

var_dump($get_result);

?>

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.

Sommario
Memcache::add -- Add an item to the server
Memcache::close -- Close memcached server connection
Memcache::connect -- Open memcached server connection
memcache_debug -- Turn debug output on/off
Memcache::decrement -- Decrement item's value
Memcache::delete -- Delete item from the server
Memcache::flush -- Flush all existing items at the server
Memcache::get -- Retrieve item from the server
Memcache::getStats -- Get statistics of the server
Memcache::getVersion -- Return version of the server
Memcache::increment -- Increment item's value
Memcache::pconnect -- Open memcached server persistent connection
Memcache::replace -- Replace value of the existing item
Memcache::set -- Store data at the server

Memcache::add

(no version information, might be only in CVS)

Memcache::add -- Add an item to the server

Description

bool Memcache::add ( string key, mixed var [, int flag [, int expire]] )

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.

Esempio 1. Memcache::add() example

<?php

$memcache_obj = memcache_connect("localhost", 11211);

/* procedural API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);

/* OO API */
$memcache_obj->add('var_key', 'test variable', false, 30);

?>

Memcache::add() returns TRUE on success or FALSE on failure.

See also Memcache::set(), Memcache::replace().

Memcache::close

(no version information, might be only in CVS)

Memcache::close -- Close memcached server connection

Description

bool Memcache::close ( void )

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

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* 
do something here ..
*/
memcache_close($memcache_obj);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* 
do something here ..
*/
$memcache_obj->close();

?>

Memcache::close() returns FALSE if an error occured.

See also Memcache::connect(), Memcache::pconnect().

Memcache::connect

(no version information, might be only in CVS)

Memcache::connect -- Open memcached server connection

Description

bool Memcache::connect ( string host [, int port [, int timeout]] )

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.

Esempio 1. Memcache::connect() example

<?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also Memcache::pconnect() and Memcache::close().

memcache_debug

(PECL)

memcache_debug -- Turn debug output on/off

Description

bool memcache_debug ( int on_off )

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

(no version information, might be only in CVS)

Memcache::decrement -- Decrement item's value

Description

int Memcache::decrement ( string key [, int value] )

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

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* decrement item by 2 */
$new_value = memcache_decrement($memcache_obj, 'test_item', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* decrement item by 3 */
$new_value = $memcache_obj->decrement('test_item', 3);
?>

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

(no version information, might be only in CVS)

Memcache::delete -- Delete item from the server

Description

bool Memcache::delete ( string key [, int timeout] )

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

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

/* after 10 seconds item will be deleted by the server */
memcache_delete('key_to_delete', 10);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->delete('key_to_delete', 10);

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Memcache::flush

(no version information, might be only in CVS)

Memcache::flush -- Flush all existing items at the server

Description

bool Memcache::flush ( void )

Memcache::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.

Esempio 1. Memcache::flush() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

memcache_flush($memcache_obj);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->flush();

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Memcache::get

(no version information, might be only in CVS)

Memcache::get -- Retrieve item from the server

Description

string Memcache::get ( string key )

string Memcache::get ( array keys )

Memcache::get() returns previously stored data if an item with such key exists on the server at this moment.

Esempio 1. Memcache::get() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get('some_key');

/* 
You also can use array of keys as a parameter.
If such item wasn't found at the server, the result
array simply will not include such key.
*/

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, Array('some_key', 'another_key'));

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get(Array('some_key', 'second_key'));

?>

Memcache::get() returns FALSE on failure or if such key was not found.

Memcache::getStats

(no version information, might be only in CVS)

Memcache::getStats -- Get statistics of the server

Description

array Memcache::getStats ( void )

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

(no version information, might be only in CVS)

Memcache::getVersion -- Return version of the server

Description

string Memcache::getVersion ( void )

Memcache::getVersion() returns a string with server's version number.

Also you can use memcache_get_version() function. See example below.

Esempio 1. Memcache::getVersion() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

echo memcache_get_version($memcache_obj);

/* OO API */
$memcache_obj = new Memcache;
echo $memcache_obj->getVersion();

?>

Memcache::getVersion() returns FALSE if an error occured.

See also Memcache::getStats().

Memcache::increment

(no version information, might be only in CVS)

Memcache::increment -- Increment item's value

Description

int Memcache::increment ( string key [, int value] )

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

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);

?>

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().

Memcache::pconnect

(no version information, might be only in CVS)

Memcache::pconnect -- Open memcached server persistent connection

Description

bool Memcache::pconnect ( string host [, int port [, int timeout]] )

Memcache::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.

Esempio 1. Memcache::pconnect() example

<?php

/* procedural API */
$memcache_obj = memcache_pconnect('memcache_host', 11211);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->pconnect('memcache_host', 11211);

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also Memcache::connect().

Memcache::replace

(no version information, might be only in CVS)

Memcache::replace -- Replace value of the existing item

Description

bool Memcache::replace ( string key, mixed var [, int flag [, int expire]] )

Memcache::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.

Esempio 1. Memcache::replace() example

<?php

$memcache_obj = memcache_connect('memcache_host', 11211);

/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", false, 30);

/* OO API */
$memcache_obj->replace("test_key", "some variable", false, 30);

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also Memcache::set(), Memcache::add().

Memcache::set

(no version information, might be only in CVS)

Memcache::set -- Store data at the server

Description

bool Memcache::set ( string key, mixed var [, int flag [, int expire]] )

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

<?php
/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect('memcache_host', 11211);

/*
set value of item with key 'var_key'
using 0 as flag value, compression is not used
expire time is 30 seconds
*/
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);

echo memcache_get($memcache_obj, 'var_key');

?>

Esempio 2. Memcache::set() example

<?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host', 11211);

/*
set value of item with key 'var_key', using on-the-fly compression
expire time is 50 seconds
*/
$memcache_obj->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo $memcache_obj->get('var_key');

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also Memcache::add(), Memcache::replace().

LXXV. Mhash Functions

Introduzione

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.


Requisiti

To use it, download the mhash distribution from its web site and follow the included installation instructions.


Installazione

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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


Esempi

Esempio 1. Compute the MD5 digest and hmac and print it out as hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "<br />\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "<br />\n";
?>

This will produce:
The hash is d03cb659cbf9192dcd066272249f8412 
The hmac is 750c783e6ab0b503eaa86e310a5db738

Sommario
mhash_count -- Get the highest available hash id
mhash_get_block_size -- Get the block size of the specified hash
mhash_get_hash_name -- Get the name of the specified hash
mhash_keygen_s2k -- Generates a key
mhash -- Compute hash

mhash_count

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash_count -- Get the highest available hash id

Description

int mhash_count ( void )

mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.

Esempio 1. Traversing all hashes

<?php

$nr = mhash_count();

for ($i = 0; $i <= $nr; $i++) {
    echo sprintf("The blocksize of %s is %d\n", 
        mhash_get_hash_name($i),
        mhash_get_block_size($i));
}
?>

mhash_get_block_size

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash_get_block_size -- Get the block size of the specified hash

Description

int mhash_get_block_size ( int hash )

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

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash_get_hash_name -- Get the name of the specified hash

Description

string mhash_get_hash_name ( int hash )

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.

Esempio 1. mhash_get_hash_name() example

<?php
$hash = MHASH_MD5;

echo mhash_get_hash_name($hash);
?>

Il precedente esempio visualizzerà:

MD5

mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5)

mhash_keygen_s2k -- Generates a key

Description

string mhash_keygen_s2k ( int hash, string password, string salt, int bytes )

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

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

mhash -- Compute hash

Description

string mhash ( int hash, string data [, string 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.

LXXVI. Mimetype Functions

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

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.

Esempio 1. Setting the path to magic.mime

mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"

Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Mimetype configuration options

NameDefaultChangeableChangelog
mime_magic.debug"0"PHP_INI_SYSTEMAvailable since PHP 5.0.0.
mime_magic.magicfile"/path/to/php/magic.mime"PHP_INI_SYSTEMAvailable since PHP 4.3.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
mime_content_type -- Detect MIME Content-type for a file

mime_content_type

(PHP 4 >= 4.3.0, PHP 5)

mime_content_type -- Detect MIME Content-type for a file

Description

string mime_content_type ( string filename )

Returns the MIME content type for a file as determined by using information from the magic.mime file. Content types are returned in MIME format, like text/plain or application/octet-stream.

Esempio 1. mime_content_type() example

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

Il precedente esempio visualizzerà:

image/gif
text/plain

LXXVII. Ming functions for Flash

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.


Introduzione

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.


Requisiti

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.


Installazione

Esempio 1. built into PHP (Unix)



    mkdir <phpdir>/ext/ming
    cp php_ext/* <phpdir>/ext/ming
    cd <phpdir>
    ./buildconf 
    ./configure --with-ming <other config options>

    

Build and install PHP as usual, restart web server if necessary.

Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

SWFBUTTON_HIT (integer)

SWFBUTTON_DOWN (integer)

SWFBUTTON_OVER (integer)

SWFBUTTON_UP (integer)

SWFBUTTON_MOUSEUPOUTSIDE (integer)

SWFBUTTON_DRAGOVER (integer)

SWFBUTTON_DRAGOUT (integer)

SWFBUTTON_MOUSEUP (integer)

SWFBUTTON_MOUSEDOWN (integer)

SWFBUTTON_MOUSEOUT (integer)

SWFBUTTON_MOUSEOVER (integer)

SWFFILL_RADIAL_GRADIENT (integer)

SWFFILL_LINEAR_GRADIENT (integer)

SWFFILL_TILED_BITMAP (integer)

SWFFILL_CLIPPED_BITMAP (integer)

SWFTEXTFIELD_HASLENGTH (integer)

SWFTEXTFIELD_NOEDIT (integer)

SWFTEXTFIELD_PASSWORD (integer)

SWFTEXTFIELD_MULTILINE (integer)

SWFTEXTFIELD_WORDWRAP (integer)

SWFTEXTFIELD_DRAWBOX (integer)

SWFTEXTFIELD_NOSELECT (integer)

SWFTEXTFIELD_HTML (integer)

SWFTEXTFIELD_ALIGN_LEFT (integer)

SWFTEXTFIELD_ALIGN_RIGHT (integer)

SWFTEXTFIELD_ALIGN_CENTER (integer)

SWFTEXTFIELD_ALIGN_JUSTIFY (integer)

SWFACTION_ONLOAD (integer)

SWFACTION_ENTERFRAME (integer)

SWFACTION_UNLOAD (integer)

SWFACTION_MOUSEMOVE (integer)

SWFACTION_MOUSEDOWN (integer)

SWFACTION_MOUSEUP (integer)

SWFACTION_KEYDOWN (integer)

SWFACTION_KEYUP (integer)

SWFACTION_DATA (integer)


Classi predefinite

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.

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite

Sommario
ming_setcubicthreshold --  Set cubic threshold (?)
ming_setscale --  Set scale (?)
ming_useswfversion --  Use SWF version (?)
SWFAction -- Creates a new Action
SWFBitmap->getHeight -- Returns the bitmap's height
SWFBitmap->getWidth -- Returns the bitmap's width
SWFBitmap -- Loads Bitmap object
swfbutton_keypress --  Returns the action flag for keyPress(char)
SWFbutton->addAction -- Adds an action
SWFbutton->addShape -- Adds a shape to a button
SWFbutton->setAction -- Sets the action
SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN)
SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)
SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)
SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)
SWFbutton -- Creates a new Button
SWFDisplayItem->addColor -- Adds the given color to this item's color transform
SWFDisplayItem->move -- Moves object in relative coordinates
SWFDisplayItem->moveTo -- Moves object in global coordinates
SWFDisplayItem->multColor -- Multiplies the item's color transform
SWFDisplayItem->remove -- Removes the object from the movie
SWFDisplayItem->Rotate -- Rotates in relative coordinates
SWFDisplayItem->rotateTo -- Rotates the object in global coordinates
SWFDisplayItem->scale -- Scales the object in relative coordinates
SWFDisplayItem->scaleTo -- Scales the object in global coordinates
SWFDisplayItem->setDepth -- Sets z-order
SWFDisplayItem->setName -- Sets the object's name
SWFDisplayItem->setRatio -- Sets the object's ratio
SWFDisplayItem->skewX -- Sets the X-skew
SWFDisplayItem->skewXTo -- Sets the X-skew
SWFDisplayItem->skewY -- Sets the Y-skew
SWFDisplayItem->skewYTo -- Sets the Y-skew
SWFDisplayItem -- Creates a new displayitem object
SWFFill->moveTo -- Moves fill origin
SWFFill->rotateTo -- Sets fill's rotation
SWFFill->scaleTo -- Sets fill's scale
SWFFill->skewXTo -- Sets fill x-skew
SWFFill->skewYTo -- Sets fill y-skew
SWFFill -- Loads SWFFill object
swffont->getwidth -- Returns the string's width
SWFFont -- Loads a font definition
SWFGradient->addEntry -- Adds an entry to the gradient list
SWFGradient -- Creates a gradient object
SWFMorph->getshape1 -- Gets a handle to the starting shape
SWFMorph->getshape2 -- Gets a handle to the ending shape
SWFMorph -- Creates a new SWFMorph object
SWFMovie->add -- Adds any type of data to a movie
SWFMovie->nextframe -- Moves to the next frame of the animation
SWFMovie->output -- Dumps your lovingly prepared movie out
swfmovie->remove -- Removes the object instance from the display list
SWFMovie->save -- Saves your movie in a file
SWFMovie->setbackground -- Sets the background color
SWFMovie->setdimension -- Sets the movie's width and height
SWFMovie->setframes -- Sets the total number of frames in the animation
SWFMovie->setrate -- Sets the animation's frame rate
SWFMovie->streammp3 -- Streams a MP3 file
SWFMovie -- Creates a new movie object, representing an SWF version 4 movie
SWFShape->addFill -- Adds a solid fill to the shape
SWFShape->drawCurve -- Draws a curve (relative)
SWFShape->drawCurveTo -- Draws a curve
SWFShape->drawLine -- Draws a line (relative)
SWFShape->drawLineTo -- Draws a line
SWFShape->movePen -- Moves the shape's pen (relative)
SWFShape->movePenTo -- Moves the shape's pen
SWFShape->setLeftFill -- Sets left rasterizing color
SWFShape->setLine -- Sets the shape's line style
SWFShape->setRightFill -- Sets right rasterizing color
SWFShape -- Creates a new shape object
swfsprite->add -- Adds an object to a sprite
SWFSprite->nextframe -- Moves to the next frame of the animation
SWFSprite->remove -- Removes an object to a sprite
SWFSprite->setframes -- Sets the total number of frames in the animation
SWFSprite -- Creates a movie clip (a sprite)
SWFText->addString -- Draws a string
SWFText->getWidth -- Computes string's width
SWFText->moveTo -- Moves the pen
SWFText->setColor -- Sets the current font color
SWFText->setFont -- Sets the current font
SWFText->setHeight -- Sets the current font height
SWFText->setSpacing -- Sets the current font spacing
SWFText -- Creates a new SWFText object
SWFTextField->addstring -- Concatenates the given string to the text field
SWFTextField->align -- Sets the text field alignment
SWFTextField->setbounds -- Sets the text field width and height
SWFTextField->setcolor -- Sets the color of the text field
SWFTextField->setFont -- Sets the text field font
SWFTextField->setHeight -- Sets the font height of this text field font
SWFTextField->setindentation -- Sets the indentation of the first line
SWFTextField->setLeftMargin -- Sets the left margin width of the text field
SWFTextField->setLineSpacing -- Sets the line spacing of the text field
SWFTextField->setMargins -- Sets the margins width of the text field
SWFTextField->setname -- Sets the variable name
SWFTextField->setrightMargin -- Sets the right margin width of the text field
SWFTextField -- Creates a text field object

ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5)

ming_setcubicthreshold --  Set cubic threshold (?)

Description

void ming_setcubicthreshold ( int threshold )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ming_setscale

(PHP 4 >= 4.0.5, PHP 5)

ming_setscale --  Set scale (?)

Description

void ming_setscale ( int scale )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5)

ming_useswfversion --  Use SWF version (?)

Description

void ming_useswfversion ( int version )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SWFAction

(PHP 4 >= 4.0.5)

SWFAction -- Creates a new Action

Description

SWFAction swfaction ( string script )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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:

time()

Returns the number of milliseconds (?) elapsed since the movie started.

random(seed)

Returns a pseudo-random number in the range 0-seed.

length(expr)

Returns the length of the given expression.

int(number)

Returns the given number rounded down to the nearest integer.

concat(expr, expr)

Returns the concatenation of the given expressions.

ord(expr)

Returns the ASCII code for the given character

chr(num)

Returns the character for the given ASCII code

substr(string, location, length)

Returns the substring of length length at location location of the given string string.

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)

Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.

removeClip(expr)

Removes the named movie clip.

trace(expr)

Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.

startDrag(target, lock, [left, top, right, bottom])

Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.

stopDrag()

Stop dragging my heart around. And this movie clip, too.

callFrame(expr)

Call the named frame as a function.

getURL(url, target, [method])

Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.

loadMovie(url, target)

Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).

nextFrame()

Go to the next frame.

prevFrame()

Go to the last (or, rather, previous) frame.

play()

Start playing the movie.

stop()

Stop playing the movie.

toggleQuality()

Toggle between high and low quality.

stopSounds()

Stop playing all sounds.

gotoFrame(num)

Go to frame number num. Frame numbers start at 0.

gotoFrame(name)

Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.

setTarget(expr)

Sets the context for action. Or so they say- I really have no idea what this does.

And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x

  • y

  • xScale

  • yScale

  • currentFrame - (read-only)

  • totalFrames - (read-only)

  • alpha - transparency level

  • visible - 1=on, 0=off (?)

  • width - (read-only)

  • height - (read-only)

  • rotation

  • target - (read-only) (???)

  • framesLoaded - (read-only)

  • name

  • dropTarget - (read-only) (???)

  • url - (read-only) (???)

  • highQuality - 1=high, 0=low (?)

  • focusRect - (???)

  • soundBufTime - (???)

So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a Unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

This simple example will move the red square across the window.

Esempio 1. swfaction() example

<?php
  $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500, -500);
  $s->drawLineTo(500, -500);
  $s->drawLineTo(500, 500);
  $s->drawLineTo(-500, 500);
  $s->drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for ($n=0; $n<5; ++$n) {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000, 4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

Esempio 2. swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for ($n=0; $n<=20; ++$n) {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for ($x=0; $x<12; ++$x) {
    for ($y=0; $y<8; ++$y) {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

Esempio 3. swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if (num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFBitmap->getHeight

(no version information, might be only in CVS)

SWFBitmap->getHeight -- Returns the bitmap's height

Description

float swfbitmap->getheight ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFBitmap->getWidth

(no version information, might be only in CVS)

SWFBitmap->getWidth -- Returns the bitmap's width

Description

float swfbitmap->getwidth ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFBitmap

(PHP 4 >= 4.0.5)

SWFBitmap -- Loads Bitmap object

Description

SWFBitmap swfbitmap ( mixed file [, mixed alphafile] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
  $s = new SWFShape();
  $f = $s->addFill(new SWFBitmap(file_get_contents("png.dbl")));
  $s->setRightFill($f);

  $s->drawLine(32, 0);
  $s->drawLine(0, 32);
  $s->drawLine(-32, 0);
  $s->drawLine(0, -32);

  $m = new SWFMovie();
  $m->setDimension(32, 32);
  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

And you can put an alpha mask on a jpeg fill.

Esempio 2. swfbitmap() example

<?php

  $s = new SWFShape();

  // .msk file generated with "gif2mask" utility
  $f = $s->addFill(new SWFBitmap(file_get_contents("alphafill.jpg"), file_get_contents("alphafill.msk")));
  $s->setRightFill($f);

  $s->drawLine(640, 0);
  $s->drawLine(0, 480);
  $s->drawLine(-640, 0);
  $s->drawLine(0, -480);

  $c = new SWFShape();
  $c->setRightFill($c->addFill(0x99, 0x99, 0x99));
  $c->drawLine(40, 0);
  $c->drawLine(0, 40);
  $c->drawLine(-40, 0);
  $c->drawLine(0, -40);

  $m = new SWFMovie();
  $m->setDimension(640, 480);
  $m->setBackground(0xcc, 0xcc, 0xcc);

  // draw checkerboard background
  for ($y=0; $y<480; $y+=40) {
    for ($x=0; $x<640; $x+=80) {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }

    $y+=40;

    for ($x=40; $x<640; $x+=80) {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }
  }

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

swfbutton_keypress

(PHP 4 >= 4.0.5)

swfbutton_keypress --  Returns the action flag for keyPress(char)

Description

int swfbutton_keypress ( string str )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SWFbutton->addAction

(no version information, might be only in CVS)

SWFbutton->addAction -- Adds an action

Description

void swfbutton->addaction ( resource action, int flags )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFbutton->addShape

(no version information, might be only in CVS)

SWFbutton->addShape -- Adds a shape to a button

Description

void swfbutton->addshape ( resource shape, int flags )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFbutton->setAction

(no version information, might be only in CVS)

SWFbutton->setAction -- Sets the action

Description

void swfbutton->setaction ( resource action )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFbutton->setdown

(no version information, might be only in CVS)

SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN)

Description

void swfbutton->setdown ( resource shape )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFbutton->setHit

(no version information, might be only in CVS)

SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)

Description

void swfbutton->sethit ( resource shape )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFbutton->setOver

(no version information, might be only in CVS)

SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)

Description

void swfbutton->setover ( resource shape )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFbutton->setUp

(no version information, might be only in CVS)

SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)

Description

void swfbutton->setup ( resource shape )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFbutton

(PHP 4 >= 4.0.5)

SWFbutton -- Creates a new Button

Description

SWFButton swfbutton ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

  $f = new SWFFont("_serif");

  $p = new SWFSprite();

  function label($string) 
  {
    global $f;

    $t = new SWFTextField();
    $t->setFont($f);
    $t->addString($string);
    $t->setHeight(200);
    $t->setBounds(3200, 200);
    return $t;
  }
  
  function addLabel($string) 
  {
    global $p;

    $i = $p->add(label($string));
    $p->nextFrame();
    $p->remove($i);
  }

  $p->add(new SWFAction("stop();"));
  addLabel("NO ACTION");
  addLabel("SWFBUTTON_MOUSEUP");
  addLabel("SWFBUTTON_MOUSEDOWN");
  addLabel("SWFBUTTON_MOUSEOVER");
  addLabel("SWFBUTTON_MOUSEOUT");
  addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
  addLabel("SWFBUTTON_DRAGOVER");
  addLabel("SWFBUTTON_DRAGOUT");

  function rect($r, $g, $b) 
  {
    $s = new SWFShape();
    $s->setRightFill($s->addFill($r, $g, $b));
    $s->drawLine(600, 0);
    $s->drawLine(0, 600);
    $s->drawLine(-600, 0);
    $s->drawLine(0, -600);

    return $s;
  }

  $b = new SWFButton();
  $b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
  $b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
  $b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
            SWFBUTTON_MOUSEUP);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
        SWFBUTTON_MOUSEDOWN);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
        SWFBUTTON_MOUSEOVER);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
        SWFBUTTON_MOUSEOUT);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
        SWFBUTTON_MOUSEUPOUTSIDE);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
        SWFBUTTON_DRAGOVER);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
        SWFBUTTON_DRAGOUT);

  $m = new SWFMovie();
  $m->setDimension(4000, 3000);

  $i = $m->add($p);
  $i->setName("label");
  $i->moveTo(400, 1900);

  $i = $m->add($b);
  $i->moveTo(400, 900);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Esempio 2. swfbutton->addaction() example

<?php

  $s = new SWFShape();
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->drawLine(1000,0);
  $s->drawLine(0,1000);
  $s->drawLine(-1000,0);
  $s->drawLine(0,-1000);

  $b = new SWFButton();
  $b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

  $b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
        SWFBUTTON_MOUSEDOWN);

  $b->addAction(new SWFAction("stopDrag();"),
        SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

  $p = new SWFSprite();
  $p->add($b);
  $p->nextFrame();

  $m = new SWFMovie();
  $i = $m->add($p);
  $i->setName('test');
  $i->moveTo(1000,1000);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->addColor

(no version information, might be only in CVS)

SWFDisplayItem->addColor -- Adds the given color to this item's color transform

Description

void swfdisplayitem->addcolor ( int red, int green, int blue [, int a] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->move

(no version information, might be only in CVS)

SWFDisplayItem->move -- Moves object in relative coordinates

Description

void swfdisplayitem->move ( int dx, int dy )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->moveTo

(no version information, might be only in CVS)

SWFDisplayItem->moveTo -- Moves object in global coordinates

Description

void swfdisplayitem->moveto ( int x, int y )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->multColor

(no version information, might be only in CVS)

SWFDisplayItem->multColor -- Multiplies the item's color transform

Description

void swfdisplayitem->multcolor ( int red, int green, int blue [, int a] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

  $b = new SWFBitmap(file_get_contents("backyard.jpg"));
  // note use your own picture :-)
  $s = new SWFShape();
  $s->setRightFill($s->addFill($b));
  $s->drawLine($b->getWidth(), 0);
  $s->drawLine(0, $b->getHeight());
  $s->drawLine(-$b->getWidth(), 0);
  $s->drawLine(0, -$b->getHeight());

  $m = new SWFMovie();
  $m->setDimension($b->getWidth(), $b->getHeight());

  $i = $m->add($s);

  for ($n=0; $n<=20; ++$n) {
    $i->multColor(1.0-$n/10, 1.0, 1.0);
    $i->addColor(0xff*$n/20, 0, 0);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->remove

(no version information, might be only in CVS)

SWFDisplayItem->remove -- Removes the object from the movie

Description

void swfdisplayitem->remove ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->Rotate

(no version information, might be only in CVS)

SWFDisplayItem->Rotate -- Rotates in relative coordinates

Description

void swfdisplayitem->rotate ( float ddegrees )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->rotateTo

(no version information, might be only in CVS)

SWFDisplayItem->rotateTo -- Rotates the object in global coordinates

Description

void swfdisplayitem->rotateto ( float 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.

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

<?php
  $thetext =  "ming!";

  $f = new SWFFont("Bauhaus 93.fdb");

  $m = new SWFMovie();
  $m->setRate(24.0);
  $m->setDimension(2400, 1600);
  $m->setBackground(0xff, 0xff, 0xff);

  // functions with huge numbers of arbitrary
  // arguments are always a good idea!  Really!

  function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string) 
  {
    global $f, $m;

    $t = new SWFText();
    $t->setFont($f);
    $t->setColor($r, $g, $b, $a);
    $t->setHeight(960);
    $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
    $t->addString($string);

    // we can add properties just like a normal PHP var,
    // as long as the names aren't already used.
    // e.g., we can't set $i->scale, because that's a function

    $i = $m->add($t);
    $i->x = $x;
    $i->y = $y;
    $i->rot = $rot;
    $i->s = $scale;
    $i->rotateTo($rot);
    $i->scale($scale, $scale);

    // but the changes are local to the function, so we have to
    // return the changed object.  kinda weird..

    return $i;
 }

  function step($i) 
  {
    $oldrot = $i->rot;
    $i->rot = 19*$i->rot/20;
    $i->x = (19*$i->x + 1200)/20;
    $i->y = (19*$i->y + 800)/20;
    $i->s = (19*$i->s + 1.0)/20;

    $i->rotateTo($i->rot);
    $i->scaleTo($i->s, $i->s);
    $i->moveTo($i->x, $i->y);

    return $i;
  }

  // see?  it sure paid off in legibility:

  $i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
  $i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
  $i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

  for ($i=1; $i<=100; ++$i) {
    $i1 = step($i1);
    $i2 = step($i2);
    $i3 = step($i3);

    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

See also swfdisplayitem->rotate().

SWFDisplayItem->scale

(no version information, might be only in CVS)

SWFDisplayItem->scale -- Scales the object in relative coordinates

Description

void swfdisplayitem->scale ( int dx, int dy )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->scaleTo

(no version information, might be only in CVS)

SWFDisplayItem->scaleTo -- Scales the object in global coordinates

Description

void swfdisplayitem->scaleto ( int x [, int y] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->setDepth

(no version information, might be only in CVS)

SWFDisplayItem->setDepth -- Sets z-order

Description

void swfdisplayitem->setdepth ( float depth )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->setName

(no version information, might be only in CVS)

SWFDisplayItem->setName -- Sets the object's name

Description

void swfdisplayitem->setname ( string 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.

swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

SWFDisplayItem->setRatio

(no version information, might be only in CVS)

SWFDisplayItem->setRatio -- Sets the object's ratio

Description

void swfdisplayitem->setratio ( float ratio )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

  $p = new SWFMorph();

  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(0.16, 0xff, 0xff, 0xff);
  $g->addEntry(0.32, 0, 0, 0);
  $g->addEntry(0.48, 0xff, 0xff, 0xff);
  $g->addEntry(0.64, 0, 0, 0);
  $g->addEntry(0.80, 0xff, 0xff, 0xff);
  $g->addEntry(1.00, 0, 0, 0);

  $s = $p->getShape1();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.05);
  $s->setLeftFill($f);
  $s->movePenTo(-160, -120);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(0.16, 0xff, 0, 0);
  $g->addEntry(0.32, 0, 0, 0);
  $g->addEntry(0.48, 0, 0xff, 0);
  $g->addEntry(0.64, 0, 0, 0);
  $g->addEntry(0.80, 0, 0, 0xff);
  $g->addEntry(1.00, 0, 0, 0);

  $s = $p->getShape2();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.05);
  $f->skewXTo(1.0);
  $s->setLeftFill($f);
  $s->movePenTo(-160, -120);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m = new SWFMovie();
  $m->setDimension(320, 240);
  $i = $m->add($p);
  $i->moveTo(160, 120);

  for ($n=0; $n<=1.001; $n+=0.01) {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->skewX

(no version information, might be only in CVS)

SWFDisplayItem->skewX -- Sets the X-skew

Description

void swfdisplayitem->skewx ( float ddegrees )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->skewXTo

(no version information, might be only in CVS)

SWFDisplayItem->skewXTo -- Sets the X-skew

Description

void swfdisplayitem->skewxto ( float 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.

swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().

SWFDisplayItem->skewY

(no version information, might be only in CVS)

SWFDisplayItem->skewY -- Sets the Y-skew

Description

void swfdisplayitem->skewy ( float ddegrees )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFDisplayItem->skewYTo

(no version information, might be only in CVS)

SWFDisplayItem->skewYTo -- Sets the Y-skew

Description

void swfdisplayitem->skewyto ( float 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.

swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().

SWFDisplayItem

(no version information, might be only in CVS)

SWFDisplayItem -- Creates a new displayitem object

Description

SWFDisplayItem swfdisplayitem ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFFill->moveTo

(no version information, might be only in CVS)

SWFFill->moveTo -- Moves fill origin

Description

void swffill->moveto ( int x, int y )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFFill->rotateTo

(no version information, might be only in CVS)

SWFFill->rotateTo -- Sets fill's rotation

Description

void swffill->rotateto ( float 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->rotateto() sets fill's rotation to degrees degrees.

SWFFill->scaleTo

(no version information, might be only in CVS)

SWFFill->scaleTo -- Sets fill's scale

Description

void swffill->scaleto ( int x [, int y] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFFill->skewXTo

(no version information, might be only in CVS)

SWFFill->skewXTo -- Sets fill x-skew

Description

void swffill->skewxto ( float x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFFill->skewYTo

(no version information, might be only in CVS)

SWFFill->skewYTo -- Sets fill y-skew

Description

void swffill->skewyto ( float y )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFFill

(PHP 4 >= 4.0.5)

SWFFill -- Loads SWFFill object

Description

SWFFill swffill ( void )

The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.

SWFFill has the following methods: swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().

swffont->getwidth

(no version information, might be only in CVS)

swffont->getwidth -- Returns the string's width

Description

float swffont->getwidth ( string string )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFFont

(PHP 4 >= 4.0.5)

SWFFont -- Loads a font definition

Description

SWFFont swffont ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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"); 
?>
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

swffont() returns a reference to the font definition, for use in the swftext->setfont() and the swftextfield->setfont() methods.

SWFFont has the following methods : swffont->getwidth().

SWFGradient->addEntry

(no version information, might be only in CVS)

SWFGradient->addEntry -- Adds an entry to the gradient list

Description

void swfgradient->addentry ( float ratio, int red, int green, int blue [, int a] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFGradient

(PHP 4 >= 4.0.5)

SWFGradient -- Creates a gradient object

Description

SWFGradient swfgradient ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMorph->getshape1

(no version information, might be only in CVS)

SWFMorph->getshape1 -- Gets a handle to the starting shape

Description

mixed swfmorph->getshape1 ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFMorph->getshape2

(no version information, might be only in CVS)

SWFMorph->getshape2 -- Gets a handle to the ending shape

Description

mixed swfmorph->getshape2 ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFMorph

(PHP 4 >= 4.0.5)

SWFMorph -- Creates a new SWFMorph object

Description

SWFMorph swfmorph ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0, 0, 0, 0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for ($r=0.0; $r<=1.0; $r+=0.1) {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMovie->add

(no version information, might be only in CVS)

SWFMovie->add -- Adds any type of data to a movie

Description

void swfmovie->add ( resource instance )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFMovie->nextframe

(no version information, might be only in CVS)

SWFMovie->nextframe -- Moves to the next frame of the animation

Description

void swfmovie->nextframe ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFMovie->output

(no version information, might be only in CVS)

SWFMovie->output -- Dumps your lovingly prepared movie out

Description

int swfmovie->output ( [int compression] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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'); 
?>
convinces the browser to display this as a flash movie.

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.

swfmovie->remove

(no version information, might be only in CVS)

swfmovie->remove -- Removes the object instance from the display list

Description

void swfmovie->remove ( resource instance )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFMovie->save

(no version information, might be only in CVS)

SWFMovie->save -- Saves your movie in a file

Description

int swfmovie->save ( string filename [, int compression] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFMovie->setbackground

(no version information, might be only in CVS)

SWFMovie->setbackground -- Sets the background color

Description

void swfmovie->setbackground ( int red, int green, int blue )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.)

SWFMovie->setdimension

(no version information, might be only in CVS)

SWFMovie->setdimension -- Sets the movie's width and height

Description

void swfmovie->setdimension ( int width, int height )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFMovie->setframes

(no version information, might be only in CVS)

SWFMovie->setframes -- Sets the total number of frames in the animation

Description

void swfmovie->setframes ( string numberofframes )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFMovie->setrate

(no version information, might be only in CVS)

SWFMovie->setrate -- Sets the animation's frame rate

Description

void swfmovie->setrate ( int rate )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFMovie->streammp3

(no version information, might be only in CVS)

SWFMovie->streammp3 -- Streams a MP3 file

Description

void swfmovie->streammp3 ( mixed mp3File )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

Esempio 1. swfmovie->streammp3() example

<?php
  $m = new SWFMovie();
  $m->setRate(12.0);
  $m->streamMp3(file_get_contents("distortobass.mp3"));
  // use your own MP3

  // 11.85 seconds at 12.0 fps = 142 frames
  $m->setFrames(142);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMovie

(PHP 4 >= 4.0.5)

SWFMovie -- Creates a new movie object, representing an SWF version 4 movie

Description

SWFMovie swfmovie ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFShape->addFill

(no version information, might be only in CVS)

SWFShape->addFill -- Adds a solid fill to the shape

Description

SWFFill SWFShape->addFill ( int red, int green, int blue [, int a] )

SWFFill SWFShape->addFill ( SWFBitmap bitmap [, int flags] )

SWFFill SWFShape->addFill ( SWFGradient gradient [, int flags] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php

  $p = new SWFMorph();

  $b = new SWFBitmap(file_get_contents("alphafill.jpg"));
  // use your own bitmap
  $width = $b->getWidth();
  $height = $b->getHeight();

  $s = $p->getShape1();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);
  $f->moveTo(-$width/2, -$height/4);
  $f->scaleTo(1.0, 0.5);
  $s->setLeftFill($f);
  $s->movePenTo(-$width/2, -$height/4);
  $s->drawLine($width, 0);
  $s->drawLine(0, $height/2);
  $s->drawLine(-$width, 0);
  $s->drawLine(0, -$height/2);

  $s = $p->getShape2();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);

  // these two have no effect!
  $f->moveTo(-$width/4, -$height/2);
  $f->scaleTo(0.5, 1.0);

  $s->setLeftFill($f);
  $s->movePenTo(-$width/4, -$height/2);
  $s->drawLine($width/2, 0);
  $s->drawLine(0, $height);
  $s->drawLine(-$width/2, 0);
  $s->drawLine(0, -$height);

  $m = new SWFMovie();
  $m->setDimension($width, $height);
  $i = $m->add($p);
  $i->moveTo($width/2, $height/2);

  for ($n=0; $n<1.001; $n+=0.03) {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

See also SWFShape->setLeftFill() and SWFShape->setRightFill().

SWFShape->drawCurve

(no version information, might be only in CVS)

SWFShape->drawCurve -- Draws a curve (relative)

Description

int swfshape->drawcurve ( int controldx, int controldy, int anchordx, int anchordy [, int targetdx, int targetdy] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFShape->drawCurveTo

(no version information, might be only in CVS)

SWFShape->drawCurveTo -- Draws a curve

Description

int swfshape->drawcurveto ( int controlx, int controly, int anchorx, int anchory [, int targetx, int targety] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFShape->drawLine

(no version information, might be only in CVS)

SWFShape->drawLine -- Draws a line (relative)

Description

void swfshape->drawline ( int dx, int dy )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFShape->drawLineTo

(no version information, might be only in CVS)

SWFShape->drawLineTo -- Draws a line

Description

void swfshape->drawlineto ( int x, int y )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFShape->movePen

(no version information, might be only in CVS)

SWFShape->movePen -- Moves the shape's pen (relative)

Description

void swfshape->movepen ( int dx, int dy )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFShape->movePenTo

(no version information, might be only in CVS)

SWFShape->movePenTo -- Moves the shape's pen

Description

void swfshape->movepento ( int x, int y )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

SWFShape->setLeftFill

(no version information, might be only in CVS)

SWFShape->setLeftFill -- Sets left rasterizing color

Description

void swfshape->setleftfill ( swfgradient fill )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

void swfshape->setleftfill ( int red, int green, int blue [, int 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.

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

See also swfshape->setrightfill().

SWFShape->setLine

(no version information, might be only in CVS)

SWFShape->setLine -- Sets the shape's line style

Description

void swfshape->setline ( swfshape shape )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

void swfshape->setline ( int width, int red, int green, int blue [, int 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->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

<?php
  $s = new SWFShape();
  $f1 = $s->addFill(0xff, 0, 0);
  $f2 = $s->addFill(0xff, 0x7f, 0);
  $f3 = $s->addFill(0xff, 0xff, 0);
  $f4 = $s->addFill(0, 0xff, 0);
  $f5 = $s->addFill(0, 0, 0xff);

  // bug: have to declare all line styles before you use them
  $s->setLine(40, 0x7f, 0, 0);
  $s->setLine(40, 0x7f, 0x3f, 0);
  $s->setLine(40, 0x7f, 0x7f, 0);
  $s->setLine(40, 0, 0x7f, 0);
  $s->setLine(40, 0, 0, 0x7f);

  $f = new SWFFont('Techno.fdb');

  $s->setRightFill($f1);
  $s->setLine(40, 0x7f, 0, 0);
  $s->drawGlyph($f, '!');
  $s->movePen($f->getWidth('!'), 0);

  $s->setRightFill($f2);
  $s->setLine(40, 0x7f, 0x3f, 0);
  $s->drawGlyph($f, '#');
  $s->movePen($f->getWidth('#'), 0);

  $s->setRightFill($f3);
  $s->setLine(40, 0x7f, 0x7f, 0);
  $s->drawGlyph($f, '%');
  $s->movePen($f->getWidth('%'), 0);

  $s->setRightFill($f4);
  $s->setLine(40, 0, 0x7f, 0);
  $s->drawGlyph($f, '*');
  $s->movePen($f->getWidth('*'), 0);

  $s->setRightFill($f5);
  $s->setLine(40, 0, 0, 0x7f);
  $s->drawGlyph($f, '@');

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setRate(12.0);
  $i = $m->add($s);
  $i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFShape->setRightFill

(no version information, might be only in CVS)

SWFShape->setRightFill -- Sets right rasterizing color

Description

void swfshape->setrightfill ( swfgradient fill )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

void swfshape->setrightfill ( int red, int green, int blue [, int 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.

See also swfshape->setleftfill().

Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

SWFShape

(PHP 4 >= 4.0.5)

SWFShape -- Creates a new shape object

Description

SWFShape swfshape ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
  $s = new SWFShape();
  $s->setLine(40, 0x7f, 0, 0);
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(200, 200);
  $s->drawLineTo(6200, 200);
  $s->drawLineTo(6200, 4600);
  $s->drawCurveTo(200, 4600, 200, 200);

  $m = new SWFMovie();
  $m->setDimension(6400, 4800);
  $m->setRate(12.0);
  $m->add($s);
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

swfsprite->add

(no version information, might be only in CVS)

swfsprite->add -- Adds an object to a sprite

Description

void swfsprite->add ( resource object )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFSprite->nextframe

(no version information, might be only in CVS)

SWFSprite->nextframe -- Moves to the next frame of the animation

Description

void swfsprite->nextframe ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFSprite->remove

(no version information, might be only in CVS)

SWFSprite->remove -- Removes an object to a sprite

Description

void swfsprite->remove ( resource 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.

swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the sprite.

SWFSprite->setframes

(no version information, might be only in CVS)

SWFSprite->setframes -- Sets the total number of frames in the animation

Description

void swfsprite->setframes ( int numberofframes )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFSprite

(PHP 4 >= 4.0.5)

SWFSprite -- Creates a movie clip (a sprite)

Description

SWFSprite swfsprite ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
  $s = new SWFShape();
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-500, -500);
  $s->drawLineTo(500, -500);
  $s->drawLineTo(500, 500);
  $s->drawLineTo(-500, 500);
  $s->drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();

  $m = new SWFMovie();
  $i = $m->add($p);
  $i->moveTo(1500, 1000);
  $i->setName("blah");

  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(3000, 2000);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFText->addString

(no version information, might be only in CVS)

SWFText->addString -- Draws a string

Description

void swftext->addstring ( string string )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFText->getWidth

(no version information, might be only in CVS)

SWFText->getWidth -- Computes string's width

Description

float swftext->getwidth ( string string )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFText->moveTo

(no version information, might be only in CVS)

SWFText->moveTo -- Moves the pen

Description

void swftext->moveto ( int x, int y )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFText->setColor

(no version information, might be only in CVS)

SWFText->setColor -- Sets the current font color

Description

void swftext->setcolor ( int red, int green, int blue [, int a] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFText->setFont

(no version information, might be only in CVS)

SWFText->setFont -- Sets the current font

Description

void swftext->setfont ( string 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->setfont() sets the current font to font.

SWFText->setHeight

(no version information, might be only in CVS)

SWFText->setHeight -- Sets the current font height

Description

void swftext->setheight ( int height )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFText->setSpacing

(no version information, might be only in CVS)

SWFText->setSpacing -- Sets the current font spacing

Description

void swftext->setspacing ( float spacing )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFText

(PHP 4 >= 4.0.5)

SWFText -- Creates a new SWFText object

Description

SWFText swftext ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

<?php
  $f = new SWFFont("Techno.fdb");
  $t = new SWFText();
  $t->setFont($f);
  $t->moveTo(200, 2400);
  $t->setColor(0xff, 0xff, 0);
  $t->setHeight(1200);
  $t->addString("PHP generates Flash with Ming!!");

  $m = new SWFMovie();
  $m->setDimension(5400, 3600);

  $m->add($t);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFTextField->addstring

(no version information, might be only in CVS)

SWFTextField->addstring -- Concatenates the given string to the text field

Description

void swftextfield->addstring ( string string )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->align

(no version information, might be only in CVS)

SWFTextField->align -- Sets the text field alignment

Description

void swftextfield->align ( int alignement )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setbounds

(no version information, might be only in CVS)

SWFTextField->setbounds -- Sets the text field width and height

Description

void swftextfield->setbounds ( int width, int height )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setcolor

(no version information, might be only in CVS)

SWFTextField->setcolor -- Sets the color of the text field

Description

void swftextfield->setcolor ( int red, int green, int blue [, int a] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setFont

(no version information, might be only in CVS)

SWFTextField->setFont -- Sets the text field font

Description

void swftextfield->setfont ( string 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.

swftextfield->setfont() sets the text field font to the [browser-defined?] font font.

SWFTextField->setHeight

(no version information, might be only in CVS)

SWFTextField->setHeight -- Sets the font height of this text field font

Description

void swftextfield->setheight ( int height )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setindentation

(no version information, might be only in CVS)

SWFTextField->setindentation -- Sets the indentation of the first line

Description

void swftextfield->setindentation ( int width )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setLeftMargin

(no version information, might be only in CVS)

SWFTextField->setLeftMargin -- Sets the left margin width of the text field

Description

void swftextfield->setleftmargin ( int width )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setLineSpacing

(no version information, might be only in CVS)

SWFTextField->setLineSpacing -- Sets the line spacing of the text field

Description

void swftextfield->setlinespacing ( int height )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setMargins

(no version information, might be only in CVS)

SWFTextField->setMargins -- Sets the margins width of the text field

Description

void swftextfield->setmargins ( int left, int right )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField->setname

(no version information, might be only in CVS)

SWFTextField->setname -- Sets the variable name

Description

void swftextfield->setname ( string 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.

swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

SWFTextField->setrightMargin

(no version information, might be only in CVS)

SWFTextField->setrightMargin -- Sets the right margin width of the text field

Description

void swftextfield->setrightmargin ( int width )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

SWFTextField

(PHP 4 >= 4.0.5)

SWFTextField -- Creates a text field object

Description

SWFTextField swftextfield ( [int flags] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

Flags are combined with the bitwise OR operation. For example,
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); 
?>
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield->setfont(), swftextfield->setbounds(), swftextfield->align(), swftextfield->setheight(), swftextfield->setleftmargin(), swftextfield->setrightmargin(), swftextfield->setmargins(), swftextfield->setindentation(), swftextfield->setlinespacing(), swftextfield->setcolor(), swftextfield->setname() and swftextfield->addstring().

LXXVIII. Miscellaneous Functions

Introduzione

These functions were placed here because none of the other categories seemed to fit.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Misc. Configuration Options

NameDefaultChangeableChangelog
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 
browscapNULLPHP_INI_SYSTEM 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

ignore_user_abort boolean

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().

highlight.bg string, highlight.comment string, highlight.default string, highlight.html string, highlight.keyword string, highlight.string string

Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.

browscap string

Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

__COMPILER_HALT_OFFSET__ (integer)

Added in PHP 5.1.

Sommario
connection_aborted -- Returns TRUE if client disconnected
connection_status -- Returns connection status bitfield
connection_timeout -- Return TRUE if script timed out
constant -- Returns the value of a constant
define -- Defines a named constant
defined --  Checks whether a given named constant exists
die -- Equivalent to exit()
eval -- Evaluate a string as PHP code
exit -- Output a message and terminate the current script
get_browser --  Tells what the user's browser is capable of
__halt_compiler --  Halts the compiler execution
highlight_file -- Syntax highlighting of a file
highlight_string -- Syntax highlighting of a string
ignore_user_abort --  Set whether a client disconnect should abort script execution
pack -- Pack data into binary string
php_check_syntax --  Check the PHP syntax of (and execute) the specified file
php_strip_whitespace --  Return source with stripped comments and whitespace
show_source -- Alias di highlight_file()
sleep -- Delay execution
time_nanosleep --  Delay for a number of seconds and nanoseconds
time_sleep_until --  Make the script sleep until the specified time
uniqid -- Generate a unique ID
unpack -- Unpack data from binary string
usleep -- Delay execution in microseconds

connection_aborted

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

connection_aborted -- Returns TRUE if client disconnected

Description

int connection_aborted ( void )

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().

connection_status

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

connection_status -- Returns connection status bitfield

Description

int connection_status ( void )

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().

connection_timeout

(PHP 3 >= 3.0.7, PHP 4 <= 4.0.4)

connection_timeout -- Return TRUE if script timed out

Description

bool connection_timeout ( void )

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

(PHP 4 >= 4.0.4, PHP 5)

constant -- Returns the value of a constant

Description

mixed constant ( string name )

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.

Esempio 1. constant() example

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

?>

See also define(), defined() and the section on Constants.

define

(PHP 3, PHP 4, PHP 5)

define -- Defines a named constant

Description

bool define ( string name, mixed value [, bool case_insensitive] )

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.

Esempio 1. Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.

define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also defined(), constant() and the section on Constants.

defined

(PHP 3, PHP 4, PHP 5)

defined --  Checks whether a given named constant exists

Description

bool defined ( string name )

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Esempio 1. Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking 
 * if the string 'CONSTANT' is the name of a constant named CONSTANT */
if (defined('CONSTANT')) {
    echo CONSTANT;
}
?>

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.

die

(PHP 3, PHP 4, PHP 5)

die -- Equivalent to exit()

Description

This language construct is equivalent to exit().

eval

(PHP 3, PHP 4, PHP 5)

eval -- Evaluate a string as PHP code

Description

mixed eval ( string code_str )

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

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>

Il precedente esempio visualizzerà:

This is a $string with my $name in it.
This is a cup with my coffee in it.

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().

exit

(PHP 3, PHP 4, PHP 5)

exit -- Output a message and terminate the current script

Description

void exit ( [string status] )

void exit ( int status )

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.

Esempio 1. exit() example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Esempio 2. exit() status example

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Nota: The die() function is an alias for exit().

See also: register_shutdown_function().

get_browser

(PHP 3, PHP 4, PHP 5)

get_browser --  Tells what the user's browser is capable of

Description

mixed get_browser ( [string user_agent [, bool return_array]] )

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

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

Il precedente esempio visualizzerà qualcosa simile a:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [css] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] => 
    [vbscript] => 
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] => 
    [cdf] => 
    [aol] => 
    [beta] => 1
    [win16] => 
    [crawler] => 
    [stripper] => 
    [wap] => 
    [netclr] => 
)

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.

__halt_compiler

(no version information, might be only in CVS)

__halt_compiler --  Halts the compiler execution

Descrizione

void __halt_compiler ( void )

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.

Esempi

Esempio 1. A __halt_compiler() example

<?php

// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler();the instalation data (eg. tar, gz, PHP, etc..)

highlight_file

(PHP 4, PHP 5)

highlight_file -- Syntax highlighting of a file

Description

mixed highlight_file ( string filename [, bool return] )

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().

highlight_string

(PHP 4, PHP 5)

highlight_string -- Syntax highlighting of a string

Description

mixed highlight_string ( string str [, bool return] )

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

<?php
highlight_string('<?php phpinfo(); ?>');
?>

The above example will output (in PHP 4):

<code><font color="#000000">
<font color="#0000BB">&lt;?php phpinfo</font><font color="#007700">(); </font><font color="#0000BB">?&gt;</font>
</font>
</code>

The above example will output (in PHP 5):

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

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().

ignore_user_abort

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ignore_user_abort --  Set whether a client disconnect should abort script execution

Description

int ignore_user_abort ( [bool setting] )

This 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

(PHP 3, PHP 4, PHP 5)

pack -- Pack data into binary string

Description

string pack ( string format [, mixed args [, mixed ...]] )

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

CodeDescription
aNUL-padded string
ASPACE-padded string
hHex string, low nibble first
HHex string, high nibble first
csigned char
Cunsigned char
ssigned short (always 16 bit, machine byte order)
Sunsigned short (always 16 bit, machine byte order)
nunsigned short (always 16 bit, big endian byte order)
vunsigned short (always 16 bit, little endian byte order)
isigned integer (machine dependent size and byte order)
Iunsigned integer (machine dependent size and byte order)
lsigned long (always 32 bit, machine byte order)
Lunsigned long (always 32 bit, machine byte order)
Nunsigned long (always 32 bit, big endian byte order)
Vunsigned long (always 32 bit, little endian byte order)
ffloat (machine dependent size and representation)
ddouble (machine dependent size and representation)
xNUL byte
XBack up one byte
@NUL-fill to absolute position

Esempio 1. pack() example

<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

See also unpack().

php_check_syntax

(PHP 5 <= 5.0.4)

php_check_syntax --  Check the PHP syntax of (and execute) the specified file

Descrizione

bool php_check_syntax ( string file_name [, string &error_message] )

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.

Elenco dei parametri

file_name

The name of the file being checked.

error_message

If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.

Valori restituiti

Returns TRUE if the lint check passed, and FALSE if the link check failed or if file_name cannot be opened.

Log delle modifiche

VersioneDescrizione
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.

Esempi

php -l somefile.php

Il precedente esempio visualizzerà qualcosa simile a:

PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81

Vedere anche:

include()
is_readable()

php_strip_whitespace

(PHP 5)

php_strip_whitespace --  Return source with stripped comments and whitespace

Descrizione

string php_strip_whitespace ( string filename )

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.

Valori restituiti

The stripped source code will be returned on success, or an empty string on failure.

Esempi

Esempio 1. php_strip_whitespace() example

<?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

Il precedente esempio visualizzerà:

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement.

show_source

(PHP 4, PHP 5)

show_source -- Alias di highlight_file()

Descrizione

This function is an alias of: highlight_file().

sleep

(PHP 3, PHP 4, PHP 5)

sleep -- Delay execution

Description

int sleep ( int seconds )

The sleep() function delays program execution for the given number of seconds.

Esempio 1. sleep() example

<?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?>

This example will output (after 10 seconds)

05:31:23
05:31:33

See also usleep() and set_time_limit()

time_nanosleep

(PHP 5)

time_nanosleep --  Delay for a number of seconds and nanoseconds

Descrizione

mixed time_nanosleep ( int seconds, int nanoseconds )

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.

Valori restituiti

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

Esempi

Esempio 1. time_nanosleep() example

<?php
// Careful! This won't work as expected if an array is returned
if (time_nanosleep(0, 500000000)) {
    echo "Slept for half a second.\n";
}

// This is better:
if (time_nanosleep(0, 500000000) === true) {
    echo "Slept for half a second.\n";
}

// And this is the best:
$nano = time_nanosleep(2, 100000);

if ($nano === true) {
    echo "Slept for 2 seconds, 100 milliseconds.\n";
} elseif ($nano === false) {
    echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
    $seconds = $nano['seconds'];
    $nanoseconds = $nano['nanoseconds'];
    echo "Interrupted by a signal.\n";
    echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

Nota: Questa funzione non è implementata su piattaforme Windows

time_sleep_until

(PHP 5 >= 5.1.0RC1)

time_sleep_until --  Make the script sleep until the specified time

Descrizione

bool time_sleep_until ( float timestamp )

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

Elenco dei parametri

timestamp

The timestamp when the script should wake.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A time_sleep_until() example

<?php

//returns false and generates a warning
var_dump(time_sleep_until(time()-1));

// may only work on faster computers, will sleep up to 0.2 seconds
var_dump(time_sleep_until(time()+0.2));

?>

uniqid

(PHP 3, PHP 4, PHP 5)

uniqid -- Generate a unique ID

Description

string uniqid ( [string prefix [, bool more_entropy]] )

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

(PHP 3, PHP 4, PHP 5)

unpack -- Unpack data from binary string

Description

array unpack ( string format, string data )

unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.

unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.

Esempio 1. unpack() example

<?php
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

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.

usleep

(PHP 3, PHP 4, PHP 5)

usleep -- Delay execution in microseconds

Description

void usleep ( int micro_seconds )

The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.

Esempio 1. usleep() example

<?php

// Current time
echo date('h:i:s') . "\n";

// wait for 2 secondes
usleep(2000000);

// back!
echo date('h:i:s') . "\n";

?>

This script will output :

11:13:28
11:13:30

Nota: This function did not work on Windows systems until PHP 5.0.0

See also sleep() and set_time_limit().

LXXIX. mnoGoSearch Functions

Introduzione

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.


Requisiti

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.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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_FIELD_URLID (integer)

UDM_FIELD_URL (integer)

UDM_FIELD_CONTENT (integer)

UDM_FIELD_TITLE (integer)

UDM_FIELD_KEYWORDS (integer)

UDM_FIELD_DESC (integer)

UDM_FIELD_DESCRIPTION (integer)

UDM_FIELD_TEXT (integer)

UDM_FIELD_SIZE (integer)

UDM_FIELD_RATING (integer)

UDM_FIELD_SCORE (integer)

UDM_FIELD_MODIFIED (integer)

UDM_FIELD_ORDER (integer)

UDM_FIELD_CRC (integer)

UDM_FIELD_CATEGORY (integer)

UDM_FIELD_LANG (integer)

UDM_FIELD_CHARSET (integer)

UDM_PARAM_PAGE_SIZE (integer)

UDM_PARAM_PAGE_NUM (integer)

UDM_PARAM_SEARCH_MODE (integer)

UDM_PARAM_CACHE_MODE (integer)

UDM_PARAM_TRACK_MODE (integer)

UDM_PARAM_PHRASE_MODE (integer)

UDM_PARAM_CHARSET (integer)

UDM_PARAM_LOCAL_CHARSET (integer)

UDM_PARAM_BROWSER_CHARSET (integer)

UDM_PARAM_STOPTABLE (integer)

UDM_PARAM_STOP_TABLE (integer)

UDM_PARAM_STOPFILE (integer)

UDM_PARAM_STOP_FILE (integer)

UDM_PARAM_WEIGHT_FACTOR (integer)

UDM_PARAM_WORD_MATCH (integer)

UDM_PARAM_MAX_WORD_LEN (integer)

UDM_PARAM_MAX_WORDLEN (integer)

UDM_PARAM_MIN_WORD_LEN (integer)

UDM_PARAM_MIN_WORDLEN (integer)

UDM_PARAM_ISPELL_PREFIXES (integer)

UDM_PARAM_ISPELL_PREFIX (integer)

UDM_PARAM_PREFIXES (integer)

UDM_PARAM_PREFIX (integer)

UDM_PARAM_CROSS_WORDS (integer)

UDM_PARAM_CROSSWORDS (integer)

UDM_PARAM_VARDIR (integer)

UDM_PARAM_DATADIR (integer)

UDM_PARAM_HLBEG (integer)

UDM_PARAM_HLEND (integer)

UDM_PARAM_SYNONYM (integer)

UDM_PARAM_SEARCHD (integer)

UDM_PARAM_QSTRING (integer)

UDM_PARAM_REMOTE_ADDR (integer)

UDM_LIMIT_CAT (integer)

UDM_LIMIT_URL (integer)

UDM_LIMIT_TAG (integer)

UDM_LIMIT_LANG (integer)

UDM_LIMIT_DATE (integer)

UDM_PARAM_FOUND (integer)

UDM_PARAM_NUM_ROWS (integer)

UDM_PARAM_WORDINFO (integer)

UDM_PARAM_WORD_INFO (integer)

UDM_PARAM_SEARCHTIME (integer)

UDM_PARAM_SEARCH_TIME (integer)

UDM_PARAM_FIRST_DOC (integer)

UDM_PARAM_LAST_DOC (integer)

UDM_MODE_ALL (integer)

UDM_MODE_ANY (integer)

UDM_MODE_BOOL (integer)

UDM_MODE_PHRASE (integer)

UDM_CACHE_ENABLED (integer)

UDM_CACHE_DISABLED (integer)

UDM_TRACK_ENABLED (integer)

UDM_TRACK_DISABLED (integer)

UDM_PHRASE_ENABLED (integer)

UDM_PHRASE_DISABLED (integer)

UDM_CROSS_WORDS_ENABLED (integer)

UDM_CROSSWORDS_ENABLED (integer)

UDM_CROSS_WORDS_DISABLED (integer)

UDM_CROSSWORDS_DISABLED (integer)

UDM_PREFIXES_ENABLED (integer)

UDM_PREFIX_ENABLED (integer)

UDM_ISPELL_PREFIXES_ENABLED (integer)

UDM_ISPELL_PREFIX_ENABLED (integer)

UDM_PREFIXES_DISABLED (integer)

UDM_PREFIX_DISABLED (integer)

UDM_ISPELL_PREFIXES_DISABLED (integer)

UDM_ISPELL_PREFIX_DISABLED (integer)

UDM_ISPELL_TYPE_AFFIX (integer)

UDM_ISPELL_TYPE_SPELL (integer)

UDM_ISPELL_TYPE_DB (integer)

UDM_ISPELL_TYPE_SERVER (integer)

UDM_MATCH_WORD (integer)

UDM_MATCH_BEGIN (integer)

UDM_MATCH_SUBSTR (integer)

UDM_MATCH_END (integer)

Sommario
udm_add_search_limit -- Add various search limits
udm_alloc_agent_array -- Allocate mnoGoSearch session
udm_alloc_agent -- Allocate mnoGoSearch session
udm_api_version -- Get mnoGoSearch API version
udm_cat_list -- Get all the categories on the same level with the current one
udm_cat_path -- Get the path to the current category
udm_check_charset --  Check if the given charset is known to mnogosearch
udm_check_stored --  Check connection to stored
udm_clear_search_limits -- Clear all mnoGoSearch search restrictions
udm_close_stored --  Close connection to stored
udm_crc32 --  Return CRC32 checksum of given string
udm_errno -- Get mnoGoSearch error number
udm_error -- Get mnoGoSearch error message
udm_find -- Perform search
udm_free_agent -- Free mnoGoSearch session
udm_free_ispell_data -- Free memory allocated for ispell data
udm_free_res -- Free mnoGoSearch result
udm_get_doc_count -- Get total number of documents in database
udm_get_res_field -- Fetch mnoGoSearch result field
udm_get_res_param -- Get mnoGoSearch result parameters
udm_hash32 -- Return Hash32 checksum of gived string
udm_load_ispell_data -- Load ispell data
udm_open_stored --  Open connection to stored
udm_set_agent_param -- Set mnoGoSearch agent session parameters

udm_add_search_limit

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_add_search_limit -- Add various search limits

Description

bool udm_add_search_limit ( resource agent, int var, string val )

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:

    Esempio 1.

    <?php
          Udm_Add_Search_Limit($udm, UDM_LIMIT_DATE, "&lt;908012006");
    ?>

    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

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

udm_alloc_agent_array -- Allocate mnoGoSearch session

Description

resource udm_alloc_agent_array ( array databases )

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().

udm_alloc_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_alloc_agent -- Allocate mnoGoSearch session

Description

resource udm_alloc_agent ( string dbaddr [, string dbmode] )

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

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_api_version -- Get mnoGoSearch API version

Description

int udm_api_version ( void )

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.

Esempio 1. udm_api_version() example

<?php
if (udm_api_version() >= 30111) {
    echo  "Total number of URLs in database: " . udm_get_doc_count($udm) . "<br />\n";
}
?>

udm_cat_list

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

udm_cat_list -- Get all the categories on the same level with the current one

Description

array udm_cat_list ( resource agent, string category )

Returns 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
  ...

Esempio 1. udm_cat_list()example

<?php
 $cat_list_arr = udm_cat_list($udm_agent, $cat);
 $cat_list = '';
 for ($i=0; $i<count($cat_list_arr); $i+=2) {
    $path = $cat_list_arr[$i];
    $name = $cat_list_arr[$i+1];
    $cat_list .= "<a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a><br />";
 }
?>

See also udm_cat_path().

udm_cat_path

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

udm_cat_path -- Get the path to the current category

Description

array udm_cat_path ( resource agent, string category )

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'

<?php
  $cat_path_arr = udm_cat_path($udm_agent, $cat);
  $cat_path = '';
  for ($i=0; $i<count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " > <a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a> ";
  }
?>

See also udm_cat_list().

udm_check_charset

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

udm_check_charset --  Check if the given charset is known to mnogosearch

Description

bool udm_check_charset ( resource agent, string charset )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored --  Check connection to stored

Description

int udm_check_stored ( resource agent, int link, string doc_id )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

udm_clear_search_limits

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_clear_search_limits -- Clear all mnoGoSearch search restrictions

Description

bool udm_clear_search_limits ( resource agent )

udm_clear_search_limits() resets defined search limitations and returns TRUE.

See also udm_add_search_limit().

udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored --  Close connection to stored

Description

int udm_close_stored ( resource agent, int link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

udm_crc32

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)

udm_crc32 --  Return CRC32 checksum of given string

Description

int udm_crc32 ( resource agent, string str )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

udm_errno

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_errno -- Get mnoGoSearch error number

Description

int udm_errno ( resource agent )

udm_errno() returns mnoGoSearch error number, zero if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving numeric agent error code.

udm_error

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_error -- Get mnoGoSearch error message

Description

string udm_error ( resource agent )

udm_error() returns mnoGoSearch error message, empty string if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving agent error message.

udm_find

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_find -- Perform search

Description

resource udm_find ( resource agent, string query )

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.

udm_free_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_free_agent -- Free mnoGoSearch session

Description

int udm_free_agent ( resource agent )

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

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_free_ispell_data -- Free memory allocated for ispell data

Description

bool udm_free_ispell_data ( int agent )

udm_free_ispell_data() always returns TRUE.

agent - agent link identifier, received after call to udm_alloc_agent().

Nota: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

udm_free_res

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_free_res -- Free mnoGoSearch result

Description

bool udm_free_res ( resource res )

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

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_get_doc_count -- Get total number of documents in database

Description

int udm_get_doc_count ( resource agent )

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

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_get_res_field -- Fetch mnoGoSearch result field

Description

string udm_get_res_field ( resource res, int row, int field )

udm_get_res_field() returns result field value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field - field identifier, may have the following values:

  • UDM_FIELD_URL - document URL field

  • UDM_FIELD_CONTENT - document Content-type field (for example, text/html).

  • UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).

  • UDM_FIELD_TITLE - document title field.

  • UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).

  • UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).

  • UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).

  • UDM_FIELD_SIZE - document size.

  • UDM_FIELD_URLID - unique URL ID of the link.

  • UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).

  • UDM_FIELD_MODIFIED - last-modified field in unixtime format.

  • UDM_FIELD_ORDER - the number of the current document in set of found documents.

  • UDM_FIELD_CRC - document CRC.

udm_get_res_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_get_res_param -- Get mnoGoSearch result parameters

Description

string udm_get_res_param ( resource res, int param )

udm_get_res_param() returns result parameter value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

param - parameter identifier, may have the following values:

  • UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.

  • UDM_PARAM_FOUND - total number of results matching the query.

  • UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"

  • UDM_PARAM_SEARCHTIME - search time in seconds.

  • UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.

  • UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.

udm_hash32

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.4)

udm_hash32 -- Return Hash32 checksum of gived string

Description

int udm_hash32 ( resource agent, string str )

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

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_load_ispell_data -- Load ispell data

Description

bool udm_load_ispell_data ( resource agent, int var, string val1, string val2, int flag )

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().

    Esempio 1. udm_load_ispell_data()example

    <?php
    if (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_DB, '', '', 1)) {
      printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
      exit;
    }
    ?>

  • UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    Esempio 2. udm_load_ispell_data() example

    <?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_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:

    <?php
    if (!udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SERVER, '', '', 1)) {
        echo "Error loading ispell data from server<br />\n";
        exit;
    }
    ?>

udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored --  Open connection to stored

Description

int udm_open_stored ( resource agent, string storedaddr )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

udm_set_agent_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)

udm_set_agent_param -- Set mnoGoSearch agent session parameters

Description

bool udm_set_agent_param ( resource agent, int var, string val )

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.

LXXX. Funzioni per Microsoft SQL Server

Introduzione

Queste funzioni permettono di accedere ad un database MS SQL Server.


Requisiti

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.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione per il modulo MS SQL Server

NomeDefaultModificabileLog 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_ALLDisponibile da PHP 4.1.0
mssql.textsize"-1"PHP_INI_ALL 
mssql.textlimit"-1"PHP_INI_ALL 
mssql.batchsize"0"PHP_INI_ALLDisponibile da PHP 4.0.4
mssql.datetimeconvert"1"PHP_INI_ALLDisponibile da PHP 4.2.0
mssql.secure_connection"0"PHP_INI_SYSTEMDisponibile da PHP 4.3.0
mssql.max_procs"25"PHP_INI_ALLDisponibile da PHP 4.3.0
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Costanti predefinite

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.

MSSQL_ASSOC (integer)

MSSQL_NUM (integer)

MSSQL_BOTH (integer)

SQLTEXT (integer)

SQLVARCHAR (integer)

SQLCHAR (integer)

SQLINT1 (integer)

SQLINT2 (integer)

SQLINT4 (integer)

SQLBIT (integer)

SQLFLT8 (integer)

Sommario
mssql_bind --  Aggiunge un parametro ad una procedura memorizzata (stored procedure) locale o remota
mssql_close -- Chiude la connessione con MS SQL Server
mssql_connect -- Apre una connessione con un server MS SQL
mssql_data_seek -- Sposta il puntatore di riga interno
mssql_execute --  Esegue una procedura memorizzata su un database MS SQL
mssql_fetch_array --  Restituisce una riga in un array associativo, numerico o entrambi
mssql_fetch_assoc --  Restituisce un array associativo con i dati di una riga dal set di risultati indicato da id_risultato
mssql_fetch_batch --  Restituisce il successivo gruppo di record
mssql_fetch_field -- Restituisce le informazioni di un campo
mssql_fetch_object -- Restituisce una riga come oggetto
mssql_fetch_row -- Restituisce una riga come array numerato
mssql_field_length -- Restituisce la lunghezza di un campo
mssql_field_name -- Restituisce il nome di un campo
mssql_field_seek -- Ricerca il campo con l'offset specificato
mssql_field_type -- Restituisce il tipo di un campo
mssql_free_result -- Libera la memoria di un risultato
mssql_free_statement -- Free statement memory
mssql_get_last_message --  Restituisce l'ultimo messaggio dal server
mssql_guid_string --  Converte il GUID dal formato binario a 16 bit al formato stringa
mssql_init --  Inizializza una procedura memorizata locale o remota
mssql_min_error_severity -- Setta il livello minimo di errori critici.
mssql_min_message_severity -- Setta li livello critico minimo di messaggi
mssql_next_result -- Muove il puntatore interno al risultato successivo
mssql_num_fields -- Restituisce il numero di campi in un risultato
mssql_num_rows -- Restituisce il numero di righe
mssql_pconnect -- Apre una connessione persistente con MS SQL
mssql_query -- Invia una query a MS SQL
mssql_result -- Restituisce i dati di un risultato
mssql_rows_affected --  Restituisce il numero di record coinvolti dalla query
mssql_select_db -- Seleziona un database MS SQL

mssql_bind

(PHP 4 >= 4.1.0, PHP 5)

mssql_bind --  Aggiunge un parametro ad una procedura memorizzata (stored procedure) locale o remota

Descrizione

bool mssql_bind ( resource stmt, string param_name, mixed &var, int type [, int is_output [, int is_null [, int maxlen]]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche mssql_execute(), mssql_free_statement() e mssql_init().

mssql_close

(PHP 3, PHP 4, PHP 5)

mssql_close -- Chiude la connessione con MS SQL Server

Descrizione

bool mssql_close ( [resource id_connessione] )

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().

mssql_connect

(PHP 3, PHP 4, PHP 5)

mssql_connect -- Apre una connessione con un server MS SQL

Descrizione

resource mssql_connect ( [string nome_server [, string nome_utente [, string password]]] )

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().

mssql_data_seek

(PHP 3, PHP 4, PHP 5)

mssql_data_seek -- Sposta il puntatore di riga interno

Descrizione

bool mssql_data_seek ( resource id_risultato, int numero_riga )

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.

mssql_execute

(PHP 4 >= 4.1.0, PHP 5)

mssql_execute --  Esegue una procedura memorizzata su un database MS SQL

Descrizione

mixed mssql_execute ( resource stmt [, bool skip_results] )

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().

mssql_fetch_array

(PHP 3, PHP 4, PHP 5)

mssql_fetch_array --  Restituisce una riga in un array associativo, numerico o entrambi

Descrizione

array mssql_fetch_array ( resource id_risultato [, int tipo_array] )

La 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().

mssql_fetch_assoc

(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_risultato

Descrizione

array mssql_fetch_assoc ( resource id_risultato )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_fetch_batch

(PHP 4 >= 4.0.4, PHP 5)

mssql_fetch_batch --  Restituisce il successivo gruppo di record

Descrizione

int mssql_fetch_batch ( resoure indice_risultato )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_fetch_field

(PHP 3, PHP 4, PHP 5)

mssql_fetch_field -- Restituisce le informazioni di un campo

Descrizione

object mssql_fetch_field ( resource id_risultato [, int offset_campo] )

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().

mssql_fetch_object

(PHP 3, PHP 4, PHP 5)

mssql_fetch_object -- Restituisce una riga come oggetto

Descrizione

object mssql_fetch_object ( resource id_risultato )

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().

mssql_fetch_row

(PHP 3, PHP 4, PHP 5)

mssql_fetch_row -- Restituisce una riga come array numerato

Descrizione

array mssql_fetch_row ( resource id_risultato )

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().

mssql_field_length

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

mssql_field_length -- Restituisce la lunghezza di un campo

Descrizione

int mssql_field_length ( resource id_risultato [, int offset] )

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

mssql_field_name

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

mssql_field_name -- Restituisce il nome di un campo

Descrizione

string mssql_field_name ( resource id_risultato [, int offset] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_field_seek

(PHP 3, PHP 4, PHP 5)

mssql_field_seek -- Ricerca il campo con l'offset specificato

Descrizione

bool mssql_field_seek ( resource id_risultato, int offset_campo )

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().

mssql_field_type

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

mssql_field_type -- Restituisce il tipo di un campo

Descrizione

string mssql_field_type ( resource id_risultato [, int offset] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_free_result

(PHP 3, PHP 4, PHP 5)

mssql_free_result -- Libera la memoria di un risultato

Descrizione

bool mssql_free_result ( resource id_risultato )

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

(PHP 4 >= 4.3.2, PHP 5)

mssql_free_statement -- Free statement memory

Description

bool mssql_free_statement ( resource statement )

mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.

See also mssql_bind(), mssql_execute(), and mssql_init()

mssql_get_last_message

(PHP 3, PHP 4, PHP 5)

mssql_get_last_message --  Restituisce l'ultimo messaggio dal server

Descrizione

string mssql_get_last_message ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_guid_string

(PHP 4 >= 4.1.0, PHP 5)

mssql_guid_string --  Converte il GUID dal formato binario a 16 bit al formato stringa

Descrizione

string mssql_guid_string ( string binary [, int short_format] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_init

(PHP 4 >= 4.1.0, PHP 5)

mssql_init --  Inizializza una procedura memorizata locale o remota

Descrizione

int mssql_init ( string sp_name [, resource id_connessione] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche: mssql_bind(), mssql_execute() e mssql_free_statement()

mssql_min_error_severity

(PHP 3, PHP 4, PHP 5)

mssql_min_error_severity -- Setta il livello minimo di errori critici.

Descrizione

void mssql_min_error_severity ( int livello_critico )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_min_message_severity

(PHP 3, PHP 4, PHP 5)

mssql_min_message_severity -- Setta li livello critico minimo di messaggi

Descrizione

void mssql_min_message_severity ( int livello_critico )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_next_result

(PHP 4 >= 4.0.5, PHP 5)

mssql_next_result -- Muove il puntatore interno al risultato successivo

Descrizione

bool mssql_next_result ( resource id_risultato )

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

<?php
    $link = mssql_connect("localhost", "utente", "password");
    mssql_select_db("MyDB", $link);
    $SQL = "Select * from tabella1 select * from tabella2";
    $rs = mssql_query($SQL, $link);
    do {
        while ($row = mssql_fetch_row($rs)) {
        }
    } while (mssql_next_result($rs));
    mssql_free_result($rs);
    mssql_close($link);
?>

mssql_num_fields

(PHP 3, PHP 4, PHP 5)

mssql_num_fields -- Restituisce il numero di campi in un risultato

Descrizione

int mssql_num_fields ( resource id_risultato )

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().

mssql_num_rows

(PHP 3, PHP 4, PHP 5)

mssql_num_rows -- Restituisce il numero di righe

Descrizione

int mssql_num_rows ( resource id_risultato )

La funzione mssql_num_rows() restituisce il numero di righe presenti in un risultato.

Vedere anche: mssql_query() e mssql_fetch_row().

mssql_pconnect

(PHP 3, PHP 4, PHP 5)

mssql_pconnect -- Apre una connessione persistente con MS SQL

Descrizione

int mssql_pconnect ( [string nome_server [, string nome_utente [, string password]]] )

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'.

mssql_query

(PHP 3, PHP 4, PHP 5)

mssql_query -- Invia una query a MS SQL

Descrizione

resource mssql_query ( string testo_query [, resource id_connessione [, int batch_size]] )

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().

mssql_result

(PHP 3, PHP 4, PHP 5)

mssql_result -- Restituisce i dati di un risultato

Descrizione

string mssql_result ( resource id_risultato, int row, mixed campo )

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().

mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5)

mssql_rows_affected --  Restituisce il numero di record coinvolti dalla query

Descrizione

int mssql_rows_affected ( resource id_connessione )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mssql_select_db

(PHP 3, PHP 4, PHP 5)

mssql_select_db -- Seleziona un database MS SQL

Descrizione

bool mssql_select_db ( string Nome_database [, resource id_connessione] )

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:

Esempio 1. Esempio di mssql_select_db()

<?php
  $conn = mssql_connect('MYSQLSERVER', 'sa', 'password');
  mssql_select_db('[my data-base]', $conn);
?>

Vedere anche: mssql_connect(), mssql_pconnect(), e mssql_query()

LXXXI. Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

Introduzione

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.

PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS libary.

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.

Sommario
PDO_DBLIB DSN -- Connecting to Microsoft SQL Server and Sybase databases

PDO_DBLIB DSN

(no version information, might be only in CVS)

PDO_DBLIB DSN -- Connecting to Microsoft SQL Server and Sybase databases

Descrizione

The PDO_DBLIB Data Source Name (DSN) is composed of the following elements:

DSN prefix

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.

host

The hostname on which the database server resides.

dbname

The name of the database.

Esempi

Esempio 1. PDO_DBLIB DSN examples

The following examples show a PDO_DBLIB DSN for connecting to Microsoft SQL Server and Sybase databases:
mssql:host=localhost;dbname=testdb
sybase:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb

LXXXII. Mohawk Software Session Handler Functions

Introduzione

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.


Installazione

To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.

Sommario
msession_connect -- Connect to msession server
msession_count -- Get session count
msession_create -- Create a session
msession_destroy -- Destroy a session
msession_disconnect -- Close connection to msession server
msession_find -- Find all sessions with name and value
msession_get_array -- Get array of msession variables
msession_get_data -- Get data session unstructured data
msession_get -- Get value from session
msession_inc -- Increment value in session
msession_list -- List all sessions
msession_listvar -- List sessions with variable
msession_lock -- Lock a session
msession_plugin -- Call an escape function within the msession personality plugin
msession_randstr -- Get random string
msession_set_array -- Set msession variables from an array
msession_set_data -- Set data session unstructured data
msession_set -- Set value in session
msession_timeout -- Set/get session timeout
msession_uniq -- Get unique id
msession_unlock -- Unlock a session

msession_connect

(PHP 4 >= 4.2.0, PHP 5)

msession_connect -- Connect to msession server

Description

bool msession_connect ( string host, string port )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_count

(PHP 4 >= 4.2.0, PHP 5)

msession_count -- Get session count

Description

int msession_count ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_create

(PHP 4 >= 4.2.0, PHP 5)

msession_create -- Create a session

Description

bool msession_create ( string session )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_destroy

(PHP 4 >= 4.2.0, PHP 5)

msession_destroy -- Destroy a session

Description

bool msession_destroy ( string name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_disconnect

(PHP 4 >= 4.2.0, PHP 5)

msession_disconnect -- Close connection to msession server

Description

void msession_disconnect ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_find

(PHP 4 >= 4.2.0, PHP 5)

msession_find -- Find all sessions with name and value

Description

array msession_find ( string name, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_get_array

(PHP 4 >= 4.2.0, PHP 5)

msession_get_array -- Get array of msession variables

Description

array msession_get_array ( string session )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_get_data

(PHP 4 >= 4.2.0, PHP 5)

msession_get_data -- Get data session unstructured data

Description

string msession_get_data ( string session )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_get

(PHP 4 >= 4.2.0, PHP 5)

msession_get -- Get value from session

Description

string msession_get ( string session, string name, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_inc

(PHP 4 >= 4.2.0, PHP 5)

msession_inc -- Increment value in session

Description

string msession_inc ( string session, string name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_list

(PHP 4 >= 4.2.0, PHP 5)

msession_list -- List all sessions

Description

array msession_list ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_listvar

(PHP 4 >= 4.2.0, PHP 5)

msession_listvar -- List sessions with variable

Description

array msession_listvar ( string name )

Returns an associative array of value/session for all sessions with a variable named name.

Used for searching sessions with common attributes.

msession_lock

(PHP 4 >= 4.2.0, PHP 5)

msession_lock -- Lock a session

Description

int msession_lock ( string name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_plugin

(PHP 4 >= 4.2.0, PHP 5)

msession_plugin -- Call an escape function within the msession personality plugin

Description

string msession_plugin ( string session, string val [, string param] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_randstr

(PHP 4 >= 4.2.0, PHP 5)

msession_randstr -- Get random string

Description

string msession_randstr ( int param )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_set_array

(PHP 4 >= 4.2.0, PHP 5)

msession_set_array -- Set msession variables from an array

Description

void msession_set_array ( string session, array tuples )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_set_data

(PHP 4 >= 4.2.0, PHP 5)

msession_set_data -- Set data session unstructured data

Description

bool msession_set_data ( string session, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_set

(PHP 4 >= 4.2.0, PHP 5)

msession_set -- Set value in session

Description

bool msession_set ( string session, string name, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_timeout

(PHP 4 >= 4.2.0, PHP 5)

msession_timeout -- Set/get session timeout

Description

int msession_timeout ( string session [, int param] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_uniq

(PHP 4 >= 4.2.0, PHP 5)

msession_uniq -- Get unique id

Description

string msession_uniq ( int param )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

msession_unlock

(PHP 4 >= 4.2.0, PHP 5)

msession_unlock -- Unlock a session

Description

int msession_unlock ( string session, int key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LXXXIII. mSQL Functions

Introduzione

These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.


Installazione

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)


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. mSQL configuration options

NameDefaultChangeableChangelog
msql.allow_persistent"1"PHP_INI_ALL 
msql.max_persistent"-1"PHP_INI_ALL 
msql.max_links"-1"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.


Tipi di risorse

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.


Costanti predefinite

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.

MSQL_ASSOC (integer)

MSQL_NUM (integer)

MSQL_BOTH (integer)


Esempi

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.

Esempio 1. mSQL usage example

<?php
/* Connecting, selecting database */
$link = msql_connect('localhost', 'username', 'password')
    or die('Could not connect : ' . msql_error($link));

msql_select_db('database', $link)
    or die('Could not select database');

/* Issue SQL query */
$query = 'SELECT * FROM my_table';
$result = msql_query($query, $link) or die('Query failed : ' . msql_error($link));

/* Printing results in HTML */
echo "<table>\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($row as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

/* Free result set */
msql_free_result($result);

/* Close connection */
msql_close($link);
?>

Sommario
msql_affected_rows -- Returns number of affected rows
msql_close -- Close mSQL connection
msql_connect -- Open mSQL connection
msql_create_db -- Create mSQL database
msql_createdb -- Alias di msql_create_db()
msql_data_seek -- Move internal row pointer
msql_db_query -- Send mSQL query
msql_dbname -- Alias di msql_result()
msql_drop_db -- Drop (delete) mSQL database
msql_error -- Returns error message of last msql call
msql_fetch_array -- Fetch row as array
msql_fetch_field -- Get field information
msql_fetch_object -- Fetch row as object
msql_fetch_row -- Get row as enumerated array
msql_field_flags -- Get field flags
msql_field_len -- Get field length
msql_field_name -- Get the name of the specified field in a result
msql_field_seek -- Set field offset
msql_field_table -- Get table name for field
msql_field_type -- Get field type
msql_fieldflags -- Alias of msql_field_flags()
msql_fieldlen -- Alias of msql_field_len()
msql_fieldname -- Alias of msql_field_name()
msql_fieldtable -- Alias of msql_field_table()
msql_fieldtype -- Alias of msql_field_type()
msql_free_result -- Free result memory
msql_list_dbs -- List mSQL databases on server
msql_list_fields -- List result fields
msql_list_tables -- List tables in an mSQL database
msql_num_fields -- Get number of fields in result
msql_num_rows -- Get number of rows in result
msql_numfields -- Alias of msql_num_fields()
msql_numrows -- Alias of msql_num_rows()
msql_pconnect -- Open persistent mSQL connection
msql_query -- Send mSQL query
msql_regcase -- Alias of sql_regcase()
msql_result -- Get result data
msql_select_db -- Select mSQL database
msql_tablename -- Alias of msql_result()
msql -- Alias of msql_db_query()

msql_affected_rows

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

msql_affected_rows -- Returns number of affected rows

Descrizione

int msql_affected_rows ( resource result )

Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Valori restituiti

Returns the number of affected rows on success, or FALSE on error.

Vedere anche:

msql_query()

msql_close

(PHP 3, PHP 4, PHP 5)

msql_close -- Close mSQL connection

Descrizione

bool msql_close ( [resource link_identifier] )

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.

Elenco dei parametri

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

msql_connect

(PHP 3, PHP 4, PHP 5)

msql_connect -- Open mSQL connection

Descrizione

resource msql_connect ( [string hostname] )

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().

Elenco dei parametri

hostname

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.

Valori restituiti

Returns a positive mSQL link identifier on success, or FALSE on error.

msql_create_db

(PHP 3, PHP 4, PHP 5)

msql_create_db -- Create mSQL database

Descrizione

bool msql_create_db ( string database_name [, resource link_identifier] )

msql_create_db() attempts to create a new database on the mSQL server.

Elenco dei parametri

database_name

The name of the mSQL database.

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

msql_drop_db()

msql_createdb

(PHP 3, PHP 4, PHP 5)

msql_createdb -- Alias di msql_create_db()

Descrizione

This function is an alias of: msql_create_db().

msql_data_seek

(PHP 3, PHP 4, PHP 5)

msql_data_seek -- Move internal row pointer

Descrizione

bool msql_data_seek ( resource result, int row_number )

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.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row_number

The seeked row number.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

msql_db_query

(PHP 3, PHP 4, PHP 5)

msql_db_query -- Send mSQL query

Descrizione

resource msql_db_query ( string database, string query [, resource link_identifier] )

msql_db_query() selects a database and executes a query on it.

Elenco dei parametri

database

The name of the mSQL database.

query

The SQL query.

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.

Valori restituiti

Returns a positive mSQL query identifier to the query result, or FALSE on error.

Vedere anche:

msql_query()

msql_dbname

(PHP 3, PHP 4, PHP 5)

msql_dbname -- Alias di msql_result()

Descrizione

This function is an alias of: msql_result().

msql_drop_db

(PHP 3, PHP 4, PHP 5)

msql_drop_db -- Drop (delete) mSQL database

Descrizione

bool msql_drop_db ( string database_name [, resource link_identifier] )

msql_drop_db() attempts to drop (remove) a database from the mSQL server.

Elenco dei parametri

database_name

The name of the database.

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

msql_create_db()

msql_error

(PHP 3, PHP 4, PHP 5)

msql_error -- Returns error message of last msql call

Descrizione

string msql_error ( void )

msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().

Valori restituiti

The last error message or an empty string if no error was issued.

msql_fetch_array

(PHP 3, PHP 4, PHP 5)

msql_fetch_array -- Fetch row as array

Descrizione

array msql_fetch_array ( resource result [, int result_type] )

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.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

result_type

A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.

Valori restituiti

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Esempi

Esempio 1. msql_fetch_array() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo $row['id'] . ': ' . $row['name'] . "\n";
}

msql_free_result($result);
?>

Log delle modifiche

VersioneDescrizione
4.3.11 and 5.0.4 A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

msql_fetch_field

(PHP 3, PHP 4, PHP 5)

msql_fetch_field -- Get field information

Descrizione

object msql_fetch_field ( resource result [, int field_offset] )

msql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

Valori restituiti

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

Vedere anche:

msql_field_seek()

msql_fetch_object

(PHP 3, PHP 4, PHP 5)

msql_fetch_object -- Fetch row as object

Descrizione

object msql_fetch_object ( resource result )

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).

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Valori restituiti

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Esempi

Esempio 1. msql_fetch_object() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_object($result, MSQL_ASSOC)) {
    echo $row->id . ': ' . $row->name . "\n";
}

msql_free_result($result);
?>

Log delle modifiche

VersioneDescrizione
4.3.11 and 5.0.4 A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

msql_fetch_row

(PHP 3, PHP 4, PHP 5)

msql_fetch_row -- Get row as enumerated array

Descrizione

array msql_fetch_row ( resource result )

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.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Valori restituiti

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Esempi

Esempio 1. msql_fetch_row() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_row($result)) {
    echo $row[0] . ': ' . $row[1] . "\n";
}

msql_free_result($result);
?>

Log delle modifiche

VersioneDescrizione
4.3.11 and 5.0.4 A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

msql_field_flags

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_flags -- Get field flags

Descrizione

string msql_field_flags ( resource result, int field_offset )

msql_field_flags() returns the field flags of the specified field.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Valori restituiti

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

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_len -- Get field length

Descrizione

int msql_field_len ( resource result, int field_offset )

msql_field_len() returns the length of the specified field.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Valori restituiti

Returns the length of the specified field or FALSE on error.

msql_field_name

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_name -- Get the name of the specified field in a result

Descrizione

string msql_field_name ( resource result, int field_offset )

msql_field_name() gets the name of the specified field index.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Valori restituiti

The name of the field or FALSE on failure.

Vedere anche:

msql_field_len()

msql_field_seek

(PHP 3, PHP 4, PHP 5)

msql_field_seek -- Set field offset

Descrizione

bool msql_field_seek ( resource result, int field_offset )

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

msql_fetch_field()

msql_field_table

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_table -- Get table name for field

Descrizione

int msql_field_table ( resource result, int field_offset )

Returns the name of the table that the specified field is in.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Valori restituiti

The name of the table on success, or FALSE on failure.

msql_field_type

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

msql_field_type -- Get field type

Descrizione

string msql_field_type ( resource result, int field_offset )

msql_field_type() gets the type of the specified field index.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Valori restituiti

The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.

msql_fieldflags

(PHP 3, PHP 4, PHP 5)

msql_fieldflags -- Alias of msql_field_flags()

Descrizione

This function is an alias of msql_field_flags().

msql_fieldlen

(PHP 3, PHP 4, PHP 5)

msql_fieldlen -- Alias of msql_field_len()

Descrizione

This function is an alias of msql_field_len().

msql_fieldname

(PHP 3, PHP 4, PHP 5)

msql_fieldname -- Alias of msql_field_name()

Descrizione

This function is an alias of msql_field_name().

msql_fieldtable

(PHP 3, PHP 4, PHP 5)

msql_fieldtable -- Alias of msql_field_table()

Descrizione

This function is an alias of msql_field_table().

msql_fieldtype

(PHP 3, PHP 4, PHP 5)

msql_fieldtype -- Alias of msql_field_type()

Descrizione

This function is an alias of msql_field_type().

msql_free_result

(PHP 3, PHP 4, PHP 5)

msql_free_result -- Free result memory

Descrizione

bool msql_free_result ( resource result )

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.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

msql_list_dbs

(PHP 3, PHP 4, PHP 5)

msql_list_dbs -- List mSQL databases on server

Descrizione

resource msql_list_dbs ( [resource link_identifier] )

msql_list_tables() lists the databases available on the specified link_identifier.

Elenco dei parametri

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.

Valori restituiti

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

(PHP 3, PHP 4, PHP 5)

msql_list_fields -- List result fields

Descrizione

resource msql_list_fields ( string database, string tablename [, resource link_identifier] )

msql_list_fields() returns information about the given table.

Elenco dei parametri

database

The name of the database.

tablename

The name of the table.

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.

Valori restituiti

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

(PHP 3, PHP 4, PHP 5)

msql_list_tables -- List tables in an mSQL database

Descrizione

resource msql_list_tables ( string database [, resource link_identifier] )

msql_list_tables() lists the tables on the specified database.

Elenco dei parametri

database

The name of the database.

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.

Valori restituiti

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

(PHP 3, PHP 4, PHP 5)

msql_num_fields -- Get number of fields in result

Descrizione

int msql_num_fields ( resource result )

msql_num_fields() returns the number of fields in a result set.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Valori restituiti

Returns the number of fields in the result set.

msql_num_rows

(PHP 3, PHP 4, PHP 5)

msql_num_rows -- Get number of rows in result

Descrizione

int msql_num_rows ( resource query_identifier )

msql_num_rows() returns the number of rows in a result set.

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Valori restituiti

Returns the number of rows in the result set.

Vedere anche:

msql_num_fields()

msql_numfields

(PHP 3, PHP 4, PHP 5)

msql_numfields -- Alias of msql_num_fields()

Descrizione

This function is an alias of msql_num_fields().

msql_numrows

(PHP 3, PHP 4, PHP 5)

msql_numrows -- Alias of msql_num_rows()

Descrizione

This function is an alias of msql_num_rows().

msql_pconnect

(PHP 3, PHP 4, PHP 5)

msql_pconnect -- Open persistent mSQL connection

Descrizione

resource msql_pconnect ( [string hostname] )

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).

Elenco dei parametri

hostname

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.

Valori restituiti

Returns a positive mSQL link identifier on success, or FALSE on error.

msql_query

(PHP 3, PHP 4, PHP 5)

msql_query -- Send mSQL query

Descrizione

resource msql_query ( string query [, resource link_identifier] )

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Elenco dei parametri

query

The SQL query.

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.

Valori restituiti

Returns a positive mSQL query identifier on success, or FALSE on error.

Esempi

Esempio 1. msql_query() example

<?php 
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: " . msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': " . msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: " . msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

msql_regcase

(PHP 3, PHP 4, PHP 5)

msql_regcase -- Alias of sql_regcase()

Descrizione

This function is an alias of sql_regcase().

msql_result

(PHP 3, PHP 4, PHP 5)

msql_result -- Get result data

Descrizione

string msql_result ( resource result, int row [, mixed field] )

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().

Elenco dei parametri

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row

The row offset.

field

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.

Valori restituiti

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_select_db

(PHP 3, PHP 4, PHP 5)

msql_select_db -- Select mSQL database

Descrizione

bool msql_select_db ( string database_name [, resource link_identifier] )

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.

Elenco dei parametri

database_name

The database name.

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

msql_tablename

(PHP 3, PHP 4, PHP 5)

msql_tablename -- Alias of msql_result()

Descrizione

This function is an alias of msql_result().

msql

(PHP 3, PHP 4, PHP 5)

msql -- Alias of msql_db_query()

Descrizione

This function is an alias of msql_db_query().

LXXXIV. Multibyte String Functions

Introduzione

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.


PHP Character Encoding Requirements

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.

JIS, SJIS, ISO-2022-JP, BIG-5

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.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. mbstring configuration options

NameDefaultChangeableChangelog
mbstring.language"neutral"PHP_INI_PERDIRAvailable since PHP 4.3.0.
mbstring.detect_orderNULLPHP_INI_ALLAvailable since PHP 4.0.6.
mbstring.http_input"pass"PHP_INI_ALLAvailable since PHP 4.0.6.
mbstring.http_output"pass"PHP_INI_ALLAvailable since PHP 4.0.6.
mbstring.internal_encodingNULLPHP_INI_ALLAvailable since PHP 4.0.6.
mbstring.script_encodingNULLPHP_INI_ALLAvailable since PHP 4.3.0.
mbstring.substitute_characterNULLPHP_INI_ALLAvailable since PHP 4.0.6.
mbstring.func_overload"0"PHP_INI_PERDIRPHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.2.0.
mbstring.encoding_translation"0"PHP_INI_PERDIRAvailable since PHP 4.3.0.
For the definition of the PHP_INI_* constants, please refer to ini_set().

Breve descrizione dei parametri di configurazione.

mbstring.language string

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

mbstring.encoding_translation boolean

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.

mbstring.internal_encoding string

Defines the default internal character encoding.

mbstring.http_input string

Defines the default HTTP input character encoding.

mbstring.http_output string

Defines the default HTTP output character encoding.

mbstring.detect_order string

Defines default character code detection order. See also mb_detect_order().

mbstring.substitute_character string

Defines character to substitute for invalid character encoding.

mbstring.func_overload string

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

; Set default language
mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
mbstring.language        = English; Set default language to English 
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion. 
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input           = SJIS    ; Set HTTP2 input to  SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding 
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Esempio 2. php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP    

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto 

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP    

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP    

;; Do not print invalid characters
mbstring.substitute_character = none

Esempio 3. php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto 

;; Convert to SJIS
mbstring.http_output = SJIS    

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP    

;; Do not print invalid characters
mbstring.substitute_character = none


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

MB_OVERLOAD_MAIL (integer)

MB_OVERLOAD_STRING (integer)

MB_OVERLOAD_REGEX (integer)


HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

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.

    Esempio 4. Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
    mbstring.http_input = pass
    ;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
    mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override 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.

Esempio 5. php.ini setting example

;; Enable output character encoding conversion for all PHP pages

;; Enable Output Buffering
output_buffering    = On

;; Set mb_output_handler to enable output conversion
output_handler      = mb_output_handler

Esempio 6. Script example

<?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?>


Supported Character Encodings

Currently the following character 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()


Function Overloading Feature

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.

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.


Basics of Japanese multi-byte encodings

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.


References

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.


Summaries of supported encodings

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:

Sommario
mb_convert_case -- Perform case folding on a string
mb_convert_encoding -- Convert character encoding
mb_convert_kana --  Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
mb_convert_variables -- Convert character code in variable(s)
mb_decode_mimeheader -- Decode string in MIME header field
mb_decode_numericentity --  Decode HTML numeric string reference to character
mb_detect_encoding -- Detect character encoding
mb_detect_order --  Set/Get character encoding detection order
mb_encode_mimeheader -- Encode string for MIME header
mb_encode_numericentity --  Encode character to HTML numeric string reference
mb_ereg_match --  Regular expression match for multibyte string
mb_ereg_replace -- Replace regular expression with multibyte support
mb_ereg_search_getpos --  Returns start point for next regular expression match
mb_ereg_search_getregs --  Retrieve the result from the last multibyte regular expression match
mb_ereg_search_init --  Setup string and regular expression for multibyte regular expression match
mb_ereg_search_pos --  Return position and length of matched part of multibyte regular expression for predefined multibyte string
mb_ereg_search_regs --  Returns the matched part of multibyte regular expression
mb_ereg_search_setpos --  Set start point of next regular expression match
mb_ereg_search --  Multibyte regular expression match for predefined multibyte string
mb_ereg -- Regular expression match with multibyte support
mb_eregi_replace --  Replace regular expression with multibyte support ignoring case
mb_eregi --  Regular expression match ignoring case with multibyte support
mb_get_info -- Get internal settings of mbstring
mb_http_input -- Detect HTTP input character encoding
mb_http_output -- Set/Get HTTP output character encoding
mb_internal_encoding --  Set/Get internal character encoding
mb_language --  Set/Get current language
mb_list_encodings --  Returns an array of all supported encodings
mb_output_handler --  Callback function converts character encoding in output buffer
mb_parse_str --  Parse GET/POST/COOKIE data and set global variable
mb_preferred_mime_name -- Get MIME charset string
mb_regex_encoding --  Returns current encoding for multibyte regex as string
mb_regex_set_options --  Set/Get the default options for mbregex functions
mb_send_mail --  Send encoded mail
mb_split -- Split multibyte string using regular expression
mb_strcut -- Get part of string
mb_strimwidth -- Get truncated string with specified width
mb_strlen -- Get string length
mb_strpos --  Find position of first occurrence of string in a string
mb_strrpos --  Find position of last occurrence of a string in a string
mb_strtolower -- Make a string lowercase
mb_strtoupper -- Make a string uppercase
mb_strwidth -- Return width of string
mb_substitute_character -- Set/Get substitution character
mb_substr_count -- Count the number of substring occurrences
mb_substr -- Get part of string

mb_convert_case

(PHP 4 >= 4.3.0, PHP 5)

mb_convert_case -- Perform case folding on a string

Description

string mb_convert_case ( string str, int mode [, string encoding] )

mb_convert_case() returns case folded version of string converted in the way specified by mode.

mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

The return value is str with the appropriate case folding applied.

By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Esempio 1. mb_convert_case() example

<?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Mary Had A Little Lamb And She Loved It So
?>

See also mb_strtolower(), mb_strtoupper(), strtolower(), strtoupper(), ucfirst() e ucwords()

mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_encoding -- Convert character encoding

Description

string mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )

mb_convert_encoding() converts character encoding of string str from from_encoding to to_encoding.

str : String to be converted.

from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.

Esempio 1. mb_convert_encoding() example

<?php
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>

See also mb_detect_order().

mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_kana --  Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Description

string mb_convert_kana ( string str [, string option [, string encoding]] )

mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.

option is conversion option. Default value is "KV".

encoding is character encoding. If it is omitted, internal character encoding is used.

Specify with combination of following options. Default value is KV.

Tabella 1. Applicable Conversion Options

OptionMeaning
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"

Esempio 1. mb_convert_kana() example

<?php
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana" 
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?>

mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_variables -- Convert character code in variable(s)

Description

string mb_convert_variables ( string to_encoding, mixed from_encoding, mixed &vars [, mixed &...] )

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.

Esempio 1. mb_convert_variables() example

<?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>

mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_mimeheader -- Decode string in MIME header field

Description

string mb_decode_mimeheader ( string str )

mb_decode_mimeheader() decodes encoded-word string str in MIME header.

It returns decoded string in internal character encoding.

See also mb_encode_mimeheader().

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_numericentity --  Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string str, array convmap [, string encoding] )

Convert numeric string reference of string str in specified block to character. It returns converted string.

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

$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, 
// then convert value to numeric string reference.

See also mb_encode_numericentity().

mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_encoding -- Detect character encoding

Description

string mb_detect_encoding ( string str [, mixed encoding_list [, bool strict]] )

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

<?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
?>

See also mb_detect_order().

mb_detect_order

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_order --  Set/Get character encoding detection order

Description

mixed mb_detect_order ( [mixed encoding_list] )

mb_detect_order() sets automatic character encoding detection order to encoding_list. It returns TRUE for success, FALSE for failure.

encoding_list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding_list is omitted, it returns current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

Nota: mbstring currently implements following encoding detection filters. If there is 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 1. Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are 
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Esempio 2. mb_detect_order() examples

<?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());
?>

See also mb_internal_encoding(), mb_http_input(), mb_http_output() and mb_send_mail().

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_mimeheader -- Encode string for MIME header

Description

string mb_encode_mimeheader ( string str [, string charset [, string transfer_encoding [, string linefeed]]] )

mb_encode_mimeheader() 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.

Esempio 1. mb_encode_mimeheader() example

<?php
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;
?>

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

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_numericentity --  Encode character to HTML numeric string reference

Description

string mb_encode_numericentity ( string str, array convmap [, string encoding] )

mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.

convmap is array specifies code area to convert.

encoding is character encoding.

Esempio 1. convmap example

$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.

Esempio 2. mb_encode_numericentity() example

<?php
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
?>

See also mb_decode_numericentity().

mb_ereg_match

(PHP 4 >= 4.2.0)

mb_ereg_match --  Regular expression match for multibyte string

Description

bool mb_ereg_match ( string pattern, string string [, string option] )

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

(PHP 4 >= 4.2.0)

mb_ereg_replace -- Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string pattern, string replacement, string string [, string option] )

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

(PHP 4 >= 4.2.0)

mb_ereg_search_getpos --  Returns start point for next regular expression match

Description

int mb_ereg_search_getpos ( void )

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().

mb_ereg_search_getregs

(PHP 4 >= 4.2.0)

mb_ereg_search_getregs --  Retrieve the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void )

mb_ereg_search_getregs() returns an array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some maches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_init

(PHP 4 >= 4.2.0)

mb_ereg_search_init --  Setup string and regular expression for multibyte regular expression match

Description

bool mb_ereg_search_init ( string string [, string pattern [, string option]] )

mb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_regs().

mb_ereg_search_pos

(PHP 4 >= 4.2.0)

mb_ereg_search_pos --  Return position and length of matched part of multibyte regular expression for predefined multibyte string

Description

array mb_ereg_search_pos ( [string pattern [, string option]] )

mb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the 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

(PHP 4 >= 4.2.0)

mb_ereg_search_regs --  Returns the matched part of multibyte regular expression

Description

array mb_ereg_search_regs ( [string pattern [, string option]] )

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

(PHP 4 >= 4.2.0)

mb_ereg_search_setpos --  Set start point of next regular expression match

Description

bool mb_ereg_search_setpos ( int position )

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().

mb_ereg_search

(PHP 4 >= 4.2.0)

mb_ereg_search --  Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ( [string pattern [, string option]] )

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg

(PHP 4 >= 4.2.0)

mb_ereg -- Regular expression match with multibyte support

Description

int mb_ereg ( string pattern, string string [, array regs] )

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_eregi_replace

(PHP 4 >= 4.2.0)

mb_eregi_replace --  Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string pattern, string replace, string string [, string option] )

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

(PHP 4 >= 4.2.0)

mb_eregi --  Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string pattern, string string [, array regs] )

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

(PHP 4 >= 4.2.0, PHP 5)

mb_get_info -- Get internal settings of mbstring

Description

mixed mb_get_info ( [string type] )

mb_get_info() returns internal setting parameter of mbstring.

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload" will be returned.

If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

See also mb_internal_encoding(), mb_http_output().

mb_http_input

(PHP 4 >= 4.0.6, PHP 5)

mb_http_input -- Detect HTTP input character encoding

Description

mixed mb_http_input ( [string type] )

mb_http_input() returns result of HTTP input character encoding detection.

type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE, "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().

mb_http_output

(PHP 4 >= 4.0.6, PHP 5)

mb_http_output -- Set/Get HTTP output character encoding

Description

mixed mb_http_output ( [string encoding] )

If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.

If encoding is omitted, mb_http_output() returns current HTTP output character encoding.

See also mb_internal_encoding(), mb_http_input(), mb_detect_order().

mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_internal_encoding --  Set/Get internal character encoding

Description

mixed mb_internal_encoding ( [string encoding] )

mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.

encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.

encoding: Character encoding name

Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.

Esempio 1. mb_internal_encoding() example

<?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();
?>

See also mb_http_input(), mb_http_output() and mb_detect_order().

mb_language

(PHP 4 >= 4.0.6, PHP 5)

mb_language --  Set/Get current language

Description

mixed mb_language ( [string language] )

mb_language() sets language. If language is omitted, it returns current language as string.

language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.

See also mb_send_mail().

mb_list_encodings

(PHP 5)

mb_list_encodings --  Returns an array of all supported encodings

Description

array mb_list_encodings ( void )

mb_list_encodings() returns an array with all supported encodings.

Esempio 1. mb_list_encodings() example

<?php

print_r(mb_list_encodings());

?>

Il precedente esempio visualizzerà:

Array
(
    [0] => pass
    [1] => auto
    [2] => wchar
    [3] => byte2be
    [4] => byte2le
    [5] => byte4be
    [6] => byte4le
    [7] => BASE64
    [8] => UUENCODE
    [9] => HTML-ENTITIES
    [10] => Quoted-Printable
    [11] => 7bit
    [12] => 8bit
    [13] => UCS-4
    [14] => UCS-4BE
    [15] => UCS-4LE
    [16] => UCS-2
    [17] => UCS-2BE
    [18] => UCS-2LE
    [19] => UTF-32
    [20] => UTF-32BE
    [21] => UTF-32LE
    [22] => UTF-16
    [23] => UTF-16BE
    [24] => UTF-16LE
    [25] => UTF-8
    [26] => UTF-7
    [27] => UTF7-IMAP
    [28] => ASCII
    [29] => EUC-JP
    [30] => SJIS
    [31] => eucJP-win
    [32] => SJIS-win
    [33] => JIS
    [34] => ISO-2022-JP
    [35] => Windows-1252
    [36] => ISO-8859-1
    [37] => ISO-8859-2
    [38] => ISO-8859-3
    [39] => ISO-8859-4
    [40] => ISO-8859-5
    [41] => ISO-8859-6
    [42] => ISO-8859-7
    [43] => ISO-8859-8
    [44] => ISO-8859-9
    [45] => ISO-8859-10
    [46] => ISO-8859-13
    [47] => ISO-8859-14
    [48] => ISO-8859-15
    [49] => EUC-CN
    [50] => CP936
    [51] => HZ
    [52] => EUC-TW
    [53] => BIG-5
    [54] => EUC-KR
    [55] => UHC
    [56] => ISO-2022-KR
    [57] => Windows-1251
    [58] => CP866
    [59] => KOI8-R
)

mb_output_handler

(PHP 4 >= 4.0.6, PHP 5)

mb_output_handler --  Callback function converts character encoding in output buffer

Description

string mb_output_handler ( string contents, int status )

mb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.

4.1.0 or later version, this 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

Esempio 1. mb_output_handler() example

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

Nota: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.

If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See also ob_start().

mb_parse_str

(PHP 4 >= 4.0.6, PHP 5)

mb_parse_str --  Parse GET/POST/COOKIE data and set global variable

Description

bool mb_parse_str ( string encoded_string [, array &result] )

mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.

encoded_string: URL encoded data.

result: Array contains decoded and character encoding converted values.

Return Value: It returns TRUE for success or FALSE for failure.

See also mb_detect_order(), mb_internal_encoding().

mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5)

mb_preferred_mime_name -- Get MIME charset string

Description

string mb_preferred_mime_name ( string encoding )

mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.

Esempio 1. mb_preferred_mime_string() example

<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>

mb_regex_encoding

(PHP 4 >= 4.2.0)

mb_regex_encoding --  Returns current encoding for multibyte regex as string

Description

mixed mb_regex_encoding ( [string encoding] )

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

(PHP 4 >= 4.3.0)

mb_regex_set_options --  Set/Get the default options for mbregex functions

Description

string mb_regex_set_options ( [string options] )

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

(PHP 4 >= 4.0.6, PHP 5)

mb_send_mail --  Send encoded mail

Description

bool mb_send_mail ( string to, string subject, string message [, string additional_headers [, string additional_parameter]] )

mb_send_mail() sends email. Headers and message are converted and encoded according to mb_language() setting. mb_send_mail() is wrapper function of mail(). See mail() for details.

to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject is subject of mail.

message is mail message.

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

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

(PHP 4 >= 4.2.0)

mb_split -- Split multibyte string using regular expression

Description

array mb_split ( string pattern, string string [, int limit] )

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

(PHP 4 >= 4.0.6, PHP 5)

mb_strcut -- Get part of string

Description

string mb_strcut ( string str, int start [, int length [, string encoding]] )

mb_strcut() returns the portion of str specified by the start and length parameters.

mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.

It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.

encoding is character encoding. If it is not set, internal character encoding is used.

See also mb_substr(), mb_internal_encoding().

mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strimwidth -- Get truncated string with specified width

Description

string mb_strimwidth ( string str, int start, int width [, string trimmarker [, string encoding]] )

mb_strimwidth() truncates string str to specified width. It returns truncated string.

If trimmarker is set, trimmarker is appended to return value.

start is start position offset. Number of characters from the beginning of string. (First character is 0)

trimmarker is string that is added to the end of string when string is truncated.

encoding is character encoding. If it is omitted, internal encoding is used.

Esempio 1. mb_strimwidth() example

<?php
$str = mb_strimwidth($str, 0, 40, "..>");
?>

See also mb_strwidth() and mb_internal_encoding().

mb_strlen

(PHP 4 >= 4.0.6, PHP 5)

mb_strlen -- Get string length

Description

int mb_strlen ( string str [, string encoding] )

mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

encoding is character encoding for str. If encoding is omitted, internal character encoding is used.

See also mb_internal_encoding(), strlen().

mb_strpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strpos --  Find position of first occurrence of string in a string

Description

int mb_strpos ( string haystack, string needle [, int offset [, string encoding]] )

mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.

offset is search offset. If it is not specified, 0 is used.

encoding is character encoding name. If it is omitted, internal character encoding is used.

See also mb_strrpos(), mb_internal_encoding(), strpos()

mb_strrpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strrpos --  Find position of last occurrence of a string in a string

Description

int mb_strrpos ( string haystack, string needle [, string encoding] )

mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.

If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.

encoding is character encoding. If it is not specified, internal character encoding is used.

See also mb_strpos(), mb_internal_encoding(), strrpos().

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5)

mb_strtolower -- Make a string lowercase

Description

string mb_strtolower ( string str [, string encoding] )

mb_strtolower() returns str with all alphabetic characters converted to lowercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

Esempio 1. mb_strtolower() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>

See also strtolower(), mb_strtoupper() and mb_convert_case().

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5)

mb_strtoupper -- Make a string uppercase

Description

string mb_strtoupper ( string str [, string encoding] )

mb_strtoupper() returns str with all alphabetic characters converted to uppercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Esempio 1. mb_strtoupper() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

See also strtoupper(), mb_strtolower() and mb_convert_case().

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strwidth -- Return width of string

Description

int mb_strwidth ( string str [, string encoding] )

mb_strwidth() returns width of string str.

Multi-byte character usually twice of width compare to single byte character.

Tabella 1. Characters width

CharsWidth
U+0000 - U+00190
U+0020 - U+1FFF1
U+2000 - U+FF602
U+FF61 - U+FF9F1
U+FFA0 - 2

encoding is character encoding. If it is omitted, internal encoding is used.

See also: mb_strimwidth(), mb_internal_encoding().

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5)

mb_substitute_character -- Set/Get substitution character

Description

mixed mb_substitute_character ( [mixed substrchar] )

mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).

This setting affects mb_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".

Esempio 1. mb_substitute_character() example

<?php
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* Set hex format */
mb_substitute_character("long");

/* Display current setting */
echo mb_substitute_character();
?>

mb_substr_count

(PHP 4 >= 4.3.0, PHP 5)

mb_substr_count -- Count the number of substring occurrences

Description

int mb_substr_count ( string haystack, string needle [, string encoding] )

mb_substr_count() returns the number of times the needle substring occurs in the haystack string.

encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.

Esempio 1. mb_substr_count() example

<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>

See also substr_count(), mb_strpos(), mb_substr().

mb_substr

(PHP 4 >= 4.0.6, PHP 5)

mb_substr -- Get part of string

Description

string mb_substr ( string str, int start [, int length [, string encoding]] )

mb_substr() returns the portion of str specified by the start and length parameters.

mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal encoding is assumed.

encoding is character encoding. If it is omitted, internal character encoding is used.

See also mb_strcut(), mb_internal_encoding().

LXXXV. muscat Functions

Introduzione

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.


Installazione

These functions are only available if PHP was configured with --with-muscat[=DIR].

Sommario
muscat_close -- Shuts down the muscat session and releases any memory back to PHP
muscat_get -- Gets a line back from the core muscat API
muscat_give -- Sends string to the core muscat API
muscat_setup_net -- Creates a new muscat session and returns the handle
muscat_setup -- Creates a new muscat session and returns the handle

muscat_close

(4.0.5 - 4.2.3 only, PECL)

muscat_close -- Shuts down the muscat session and releases any memory back to PHP

Description

void muscat_close ( resource muscat_handle )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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!]

muscat_get

(4.0.5 - 4.2.3 only, PECL)

muscat_get -- Gets a line back from the core muscat API

Description

string muscat_get ( resource muscat_handle )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

muscat_give

(4.0.5 - 4.2.3 only, PECL)

muscat_give -- Sends string to the core muscat API

Description

void muscat_give ( resource muscat_handle, string string )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

muscat_setup_net

(4.0.5 - 4.2.3 only, PECL)

muscat_setup_net -- Creates a new muscat session and returns the handle

Description

resource muscat_setup_net ( string muscat_host )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

muscat_setup

(4.0.5 - 4.2.3 only, PECL)

muscat_setup -- Creates a new muscat session and returns the handle

Description

resource muscat_setup ( int size [, string muscat_dir] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

LXXXVI. MySQL Functions

Introduzione

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/.


Requisiti

Al fine di rendere queste funzioni disponibili, si deve compilare PHP con il supporto MySQL.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione di MySQL

NomePredefinitoModificabile in
mysql.allow_persistent"On"PHP_INI_SYSTEM
mysql.max_persistent"-1"PHP_INI_SYSTEM
mysql.max_links"-1"PHP_INI_SYSTEM
mysql.default_portNULLPHP_INI_ALL
mysql.default_socketNULLPHP_INI_ALL
mysql.default_hostNULLPHP_INI_ALL
mysql.default_userNULLPHP_INI_ALL
mysql.default_passwordNULLPHP_INI_ALL
mysql.connect_timeout"0"PHP_INI_SYSTEM
Per ulteriori dettagli e definizione delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

mysql.allow_persistent boolean

Determina se consentire le connessioni persistenti a MySQL.

mysql.max_persistent integer

Il numero massimo di connessioni persistenti MySQL per processo.

mysql.max_links integer

Il numero massimo di connessioni MySQL per processo, incluse le connessioni persistenti.

mysql.default_port string

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.

mysql.default_socket string

Il nome del socket predefinito da usare per connettersi ad un server di database locale se nessun altro nome di socket viene specificato.

mysql.default_host string

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.

mysql.default_user string

Il nome utente predefinito da usare per connettersi al server di database se nessun altro nome viene specificato. Non si applica in safe mode.

mysql.default_password string

La password predefinita da usare per connettrsi al server di database se nessuna altra password viene specificata. Non si appplica in safe mode.

mysql.connect_timeout integer

Timeout di connessione in secondi. Per Linux questo timeout è usato anche per attendere la prima risposta dal server.


Tipi di risorse

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.


Costanti predefinite

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

CostanteDescrizione
MYSQL_CLIENT_COMPRESSUsa la compressione del protocollo
MYSQL_CLIENT_IGNORE_SPACEConsente lo spazio dopo i nomi delle funzioni
MYSQL_CLIENT_INTERACTIVELascia 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

CostanteDescrizione
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


Esempi

Questo esempio mostra come connettersi, eseguire una query, stampare le righe risultanti e disconnettersi dal database MySQL.

Esempio 1. Esempio dell'estensione MySQL

<?php
    /* Connessione e selezione del database */
    $connessione = mysql_connect("host_mysql", "utente_mysql", "password_mysql")
        or die("Connessione non riuscita: " . mysql_error());
    print "Connesso con successo";
    mysql_select_db("mio_database") or die("Selezione del database non riuscita");

    /* Esecuzione di una query SQL */
    $query = "SELECT * FROM mia_tabella";
    $risultato = mysql_query($query) or die("Query fallita: " . mysql_error() );

    /* Stampa dei risultati in HTML */
    echo "<table>\n";
    while ($linea = mysql_fetch_array($risultato, MYSQL_ASSOC)) {
        echo "\t<tr>\n";
        foreach ($linea as $valore_colonna) {
            echo "\t\t<td>$valore_colonna</td>\n";
        }
        echo "\t</tr>\n";
    }
    print "</table>\n";

    /* Liberazione delle risorse del risultato */
    mysql_free_result($risultato);

    /* Chiusura della connessione */
    mysql_close($connessione);
?>

Sommario
mysql_affected_rows -- Ottiene il numero di righe coinvolte nelle precedenti operazioni MySQL
mysql_change_user --  Cambia l'utente della connessione attiva
mysql_client_encoding -- Restituisce il nome del set di caratteri
mysql_close -- Chiude una connessione MySQL
mysql_connect -- Apre una connessione ad un server MySQL
mysql_create_db -- Crea un database MySQL
mysql_data_seek -- Muove il puntatore interno del risultato
mysql_db_name -- Ottiene dei dati dal risultato
mysql_db_query -- Invia una query MySQL
mysql_drop_db -- Elimina (cancella) un database MySQL
mysql_errno --  Restituisce il valore numerico del messaggio di errore della precedente operazione MySQL
mysql_error --  Restituisce il testo del messagio di errore della precedente operazione MySQL
mysql_escape_string --  Aggiunge le sequenze di escape in una stringa per l'uso in mysql_query.
mysql_fetch_array --  Carica una riga del risultato come un array associativo, un array numerico o entrambi.
mysql_fetch_assoc --  Carica una riga del risultato come array associativo
mysql_fetch_field --  Ottiene informazioni sulla colonna da un risultato e le restituisce come oggetto
mysql_fetch_lengths --  Ottiene la lunghezza di ogni output nel risultato
mysql_fetch_object -- Carica una riga del risultato come un ogetto
mysql_fetch_row -- Ottiene una riga del risultato come un array enumerato
mysql_field_flags --  Ottine i flag associati al campo specificato di un risultato
mysql_field_len --  Restituisce la lunghezza del campo specificato
mysql_field_name --  Ottiene il nome del campo specificato in un risultato
mysql_field_seek --  Imposta il puntatore al risultato ad un determinato indice di campo
mysql_field_table --  Ottiene il nome della tabella in cui si trova il campo specificato
mysql_field_type --  Ottiene il tipo del campo specificato in un risultato
mysql_free_result -- Libera la memoria occupata dal risultato
mysql_get_client_info -- Ottine informazioni sul client MySQL
mysql_get_host_info -- Ottiene le informazioni sull'host MySQL
mysql_get_proto_info -- Ottiene le informazion sul protocollo MySQL
mysql_get_server_info -- Ottiene le informazioni sul server MySQL
mysql_info --  Ottiene le informazioni relative alla query più recente.
mysql_insert_id --  Ottiene l'identificativo generato dalla precedente operazione INSERT
mysql_list_dbs --  Elenca i database disponibili in un server MySQL
mysql_list_fields -- Elenca i campi di un risultato MySQL
mysql_list_processes -- Elenca i processi MySQL
mysql_list_tables -- Elenca le tabelle in un database MySQL
mysql_num_fields -- Ottiene il numero di campi nel risultato
mysql_num_rows -- Ottiene il numero di righe in un risultato
mysql_pconnect --  Apre una connessione persiostente ad un server MySQL
mysql_ping -- Esegue un ping su una connessione al server o riconnette se non non esiste la connessione
mysql_query -- Invia una query MySQL
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.
mysql_result -- Ottiene i dati dal risultato
mysql_select_db -- Seleziona un database MySQL
mysql_stat -- Ottiene l'attuale stato del sistema
mysql_tablename -- Ottiene il nome della tabella
mysql_thread_id -- Restituisce l'attuale thread ID
mysql_unbuffered_query --  Invia una query SQL a MySQL senza caricare e bufferare le righe risultanti

mysql_affected_rows

(PHP 3, PHP 4, PHP 5)

mysql_affected_rows -- Ottiene il numero di righe coinvolte nelle precedenti operazioni MySQL

Descrizione

int mysql_affected_rows ( [resource identificativo_connessione] )

mysql_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

<?php
    /* connessione al database */
    mysql_pconnect("localhost", "utente_mysql", "password_mysql") or
        die("Connessione non riuscita: " . mysql_error());

    /* questo dovrebbe restituire il numero corretto di record eliminati */
    mysql_query("DELETE FROM mia_tabella WHERE id < 10");
    printf ("Records eliminati: %d\n", mysql_affected_rows());

    /* senza la clausola WHERE nell'istruzione DELETE, dovrebbe restituire 0 */
    mysql_query("DELETE FROM mia_tabella");
    printf ("Record eliminati: %d\n", mysql_affected_rows());
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
Records eliminati: 10
Records eliminati: 0

Esempio 2. Query di aggiornamento

<?php
    /* connessione al to database */
    mysql_pconnect("localhost", "utente_mysql", "password_mysql") or
        die("Connessione non riuscita: " . mysql_error());

    /* aggiornamento dei record */
    mysql_query("UPDATE mia_tabella SET used=1 WHERE id < 10");
    printf ("Record aggiornati: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
Record aggiornati: 10

Vedere anche: mysql_num_rows(), mysql_info().

mysql_change_user

(PHP 3 >= 3.0.13)

mysql_change_user --  Cambia l'utente della connessione attiva

Descrizione

int mysql_change_user ( string nome_utente, string password [, string database [, resource identificativo_connessione]] )

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

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding -- Restituisce il nome del set di caratteri

Descrizione

int mysql_client_encoding ( [resource identificativo_connessione] )

mysql_client_encoding() restituisce il nome del set di caratteri predefinito per l'attuale connessione.

Esempio 1. Esempio di mysql_client_encoding()

<?php
$connessione = mysql_connect('localhost', 'utente_mysql', 'password_mysql');
$charset = mysql_client_encoding($connessione);
printf ("il set di carattei attuale è %s\n", $charset);
?>

L'esempio riportato sopra produce il seguente output:
il set di caratteri attuale è latin1

Vedere anche: mysql_real_escape_string()

mysql_close

(PHP 3, PHP 4, PHP 5)

mysql_close -- Chiude una connessione MySQL

Descrizione

bool mysql_close ( [resource identificativo_connessione] )

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().

Esempio 1. Esempio di chiura connessione MySQL

<?php
    $connessione = mysql_connect("localhost", "utente_mysql", "password_mysql")
        or die("Connessione non riuscita: " . mysql_error());
    print ("Connesso con successo");
    mysql_close($connessione);
?>

Vedere anche: mysql_connect(), e mysql_pconnect().

mysql_connect

(PHP 3, PHP 4, PHP 5)

mysql_connect -- Apre una connessione ad un server MySQL

Descrizione

resource mysql_connect ( [string server [, string nome_utente [, string password [, bool nuova_connessione [, int client_flags]]]]] )

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().

Esempio 1. Esempio di connessione MySQL

<?php
    $connessione = mysql_connect("localhost", "utente_mysql", "password_mysql")
        or die("Connessione non riuscita: " . mysql_error());
    print ("Connesso con successo");
    mysql_close($connessione);
?>

Vedere anche mysql_pconnect() e mysql_close().

mysql_create_db

(PHP 3, PHP 4, PHP 5)

mysql_create_db -- Crea un database MySQL

Descrizione

bool mysql_create_db ( string nome_database [, resource identificativo_connessione] )

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

<?php
    $connessione = mysql_pconnect("localhost", "utente_mysql", "password_mysql")
        or die("Connessione non riuscita: " . mysql_error());

    if (mysql_create_db("mio_db")) {
        print ("Database creato con successo\n");
    } else {
        printf ("Errore nella creazione del database: %s\n", mysql_error());
    }
?>

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().

mysql_data_seek

(PHP 3, PHP 4, PHP 5)

mysql_data_seek -- Muove il puntatore interno del risultato

Descrizione

bool mysql_data_seek ( resource identificativo_risultato, int numero_riga )

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

<?php
    $connessione = mysql_pconnect("localhost", "utente_mysql", "password_mysql")
        or die("Connessione non riuscita: " . mysql_error());

    mysql_select_db("samp_db")
        or die("Selezione del database non riuscita: " . mysql_error());

    $query = "SELECT cognome, nome FROM amici";
    $risultato = mysql_query($query)
        or die("Query fallita: " . mysql_error());

    /* caricamento righe in ordine inverso */
    for ($i = mysql_num_rows($risultato) - 1; $i >= 0; $i--) {
        if (!mysql_data_seek($risultato, $i)) {
            echo "Non si può eseguire il seek alla riga $i: " . mysql_error() . "\n";
            continue;
        }

        if(!($riga = mysql_fetch_object($risultato)))
            continue;

        echo "$riga->cognome $riga->nome<br />\n";
    }

    mysql_free_result($risultato);
?>

Vedere anche: mysql_query(), mysql_num_rows().

mysql_db_name

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mysql_db_name -- Ottiene dei dati dal risultato

Descrizione

string mysql_db_name ( resource risultato, int riga [, mixed campo] )

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.

Esempio 1. Esempio di mysql_db_name()

<?php
    error_reporting(E_ALL);

    mysql_connect('dbhost', 'nome_utente', 'password');
    $db_list = mysql_list_dbs();

    $i = 0;
    $conteggio = mysql_num_rows($lista_db);
    while ($i < $conteggio) {
        echo mysql_db_name($lista_db, $i) . "\n";
        $i++;
    }
?>

Per motivi di compatibilità con il passato, anche mysql_dbname() è è accettata. Questo comunque è sconsigliato.

mysql_db_query

(PHP 3, PHP 4, PHP 5)

mysql_db_query -- Invia una query MySQL

Descrizione

resource mysql_db_query ( string database, string query [, resource identificativo_connessione] )

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().

mysql_drop_db

(PHP 3, PHP 4, PHP 5)

mysql_drop_db -- Elimina (cancella) un database MySQL

Descrizione

bool mysql_drop_db ( string nome_database [, resource identificativo_connessione] )

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().

mysql_errno

(PHP 3, PHP 4, PHP 5)

mysql_errno --  Restituisce il valore numerico del messaggio di errore della precedente operazione MySQL

Descrizione

int mysql_errno ( [resource identificativo_connessione] )

Restituisce 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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql");

    mysql_select_db("db_inesistente");
    echo mysql_errno() . ": " . mysql_error(). "\n";

    mysql_select_db("kossu");
    mysql_query("SELECT * FROM tabella_inesistente");
    echo mysql_errno() . ": " . mysql_error() . "\n";
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

1049: Unknown database 'db_inesistente'
1146: Table 'kossu.tabella_inesistente' doesn't exist

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()

mysql_error

(PHP 3, PHP 4, PHP 5)

mysql_error --  Restituisce il testo del messagio di errore della precedente operazione MySQL

Descrizione

string mysql_error ( [resource identificativo_connessione] )

Restituisce 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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql");

    mysql_select_db("db_inesistente");
    echo mysql_errno() . ": " . mysql_error(). "\n";

    mysql_select_db("kossu");
    mysql_query("SELECT * FROM tabella_inesistente");
    echo mysql_errno() . ": " . mysql_error() . "\n";
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

1049: Unknown database 'db_inesistente'
1146: Table 'kossu.tabella_inesistente' doesn't exist

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()

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string --  Aggiunge le sequenze di escape in una stringa per l'uso in mysql_query.

Descrizione

string mysql_escape_string ( string stringa_senza_escape )

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()

<?php
    $voce = "Zak's Laptop";
    $voce_con_escape = mysql_escape_string($voce);
    printf ("La stringa con le sequenze di escape: %s\n", $voce_con_escape);
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
La stringa con le sequenze di escape: Zak\'s Laptop

Vedere anche: mysql_real_escape_string(), addslashes(), e la direttiva magic_quotes_gpc .

mysql_fetch_array

(PHP 3, PHP 4, PHP 5)

mysql_fetch_array --  Carica una riga del risultato come un array associativo, un array numerico o entrambi.

Descrizione

array mysql_fetch_array ( resource risultato [, int tipo_risultato] )

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').

Esempio 1. Query con nomi di campo duplicati

SELECT tabella1.campo as foo tabella2.campo as bar from tabella1, tabella2

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

<?php
mysql_connect("localhost", "utente_mysql", "password_mysql") or
    die("Connessione non riuscita: " . mysql_error());
mysql_select_db("mio_db");

$risultato = mysql_query("SELECT id, nome FROM mia_tabella");

while ($riga = mysql_fetch_array($risultato, MYSQL_NUM)) {
    printf ("ID: %s  Nome: %s", $riga[0], $riga[1]);
}

mysql_free_result($risultato);
?>

Esempio 3. mysql_fetch_array() con MYSQL_ASSOC

<?php
mysql_connect("localhost", "utente_mysql", "password_mysql") or
    die("Connessione non riuscita: " . mysql_error());
mysql_select_db("mio_db");

$risultato = mysql_query("SELECT id, nome FROM mia_tabella");

while ($riga = mysql_fetch_array($risultato, MYSQL_ASSOC)) {
    printf ("ID: %s  Nome: %s", $riga["id"], $riga["name"]);
}

mysql_free_result($risultato);
?>

Esempio 4. mysql_fetch_array() con MYSQL_BOTH

<?php
mysql_connect("localhost", "utente_mysql", "password_mysql") or
    die("Connessione non riuscita: " . mysql_error());
mysql_select_db("mio_db");

$risultato = mysql_query("SELECT id, nome FROM mia_tabella");

while ($riga = mysql_fetch_array($risultato, MYSQL_BOTH)) {
    printf ("ID: %s  Nome: %s", $riga[0], $riga["nome"]);
}

mysql_free_result($risultato);
?>

Per maggiori dettagli, vedere anche mysql_fetch_row() e mysql_fetch_assoc().

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc --  Carica una riga del risultato come array associativo

Descrizione

array mysql_fetch_assoc ( resource risultato )

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()

<?php

    $conn = mysql_connect("localhost", "utente_mysql", "password_mysql");

    if (!$conn) {
        echo "Impossibile connettersi al DB: " . mysql_error();
        exit;
    }

    if (!mysql_select_db("mio_nome_db")) {
        echo "Impossibile selezioanre mio_nome_db: " . mysql_error();
        exit;
    }

    $sql = "SELECT id as id_utente, nome_intero, stato_utente
            FROM   una_tabella
            WHERE  stato_utente = 1";

    $risultato = mysql_query($sql);

    if (!$risultato) {
        echo "Fallimento nell'esecuzione della query ($sql) dal DB: " . mysql_error();
        exit;
    }

    if (mysql_num_rows($risultato) == 0) {
        echo "Nessuna riga trovata, niente da stampare quindi si esce";
        exit;
    }

    // Finché esiste una riga di dati, si pone questa riga in $riga come un array associativo
    // Nota: Se ci si aspetta solo una riga, non è necessario usare un ciclo
    // Nota: Se si mette extract($riga); all'interno del seguente ciclo,
    //       si creeranno $id_utente, $nome_intero, and $stato_utente
    while ($riga = mysql_fetch_assoc($risultato)) {
        echo $riga["id_utente"];
        echo $riga["nome_intero"];
        echo $riga["stato_utente"];
    }

    mysql_free_result($risultato);

?>

Vedere anche mysql_fetch_row(), mysql_fetch_array(), mysql_query() e mysql_error().

mysql_fetch_field

(PHP 3, PHP 4, PHP 5)

mysql_fetch_field --  Ottiene informazioni sulla colonna da un risultato e le restituisce come oggetto

Descrizione

object mysql_fetch_field ( resource risultato [, int indice_campo] )

Restituisce 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()

<?php
mysql_connect('localhost:3306', $utente, $password)
    or die("Connessione non riuscita: " . mysql_error());
mysql_select_db("database");
$risultato = mysql_query("select * from tabella")
    or die("Query fallita: " . mysql_error());
/* ottiene i metadata della colonna */
$i = 0;
while ($i < mysql_num_fields($risultato)) {
    echo "Informazioni della colonna $i:<br />\n";
    $meta = mysql_fetch_field($risultato);
    if (!$meta) {
        echo "Nessuna informazione disponibile<br />\n";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill
</pre>";
    $i++;
}
mysql_free_result($risultato);
?>

Vedere anche mysql_field_seek().

mysql_fetch_lengths

(PHP 3, PHP 4, PHP 5)

mysql_fetch_lengths --  Ottiene la lunghezza di ogni output nel risultato

Descrizione

array mysql_fetch_lengths ( resource risultato )

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().

mysql_fetch_object

(PHP 3, PHP 4, PHP 5)

mysql_fetch_object -- Carica una riga del risultato come un ogetto

Descrizione

object mysql_fetch_object ( resource risultato )

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()

<?php
mysql_connect("hostname", "utente", "password");
mysql_select_db($db);
$risultato = mysql_query("select * from tabella");
while ($riga = mysql_fetch_object($risultato)) {
    echo $riga->id_utente;
    echo $riga->nome_intero;
}
mysql_free_result($risultato);
?>

Vedere anche: mysql_fetch_array() e mysql_fetch_row().

mysql_fetch_row

(PHP 3, PHP 4, PHP 5)

mysql_fetch_row -- Ottiene una riga del risultato come un array enumerato

Descrizione

array mysql_fetch_row ( resource risultato )

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().

mysql_field_flags

(PHP 3, PHP 4, PHP 5)

mysql_field_flags --  Ottine i flag associati al campo specificato di un risultato

Descrizione

string mysql_field_flags ( resource risultato, int indice_campo )

mysql_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

(PHP 3, PHP 4, PHP 5)

mysql_field_len --  Restituisce la lunghezza del campo specificato

Descrizione

int mysql_field_len ( resource risultato, int indice_campo )

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

(PHP 3, PHP 4, PHP 5)

mysql_field_name --  Ottiene il nome del campo specificato in un risultato

Descrizione

string mysql_field_name ( resource risultato, int indice_campo )

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()

/* La tabella utenti è costituita da tre campi:
 *   id_utente
 *   nome_utente
 *   password
 */
$connessione = mysql_connect('localhost', "utente_mysql", "password_mysql");
mysql_select_db($nome_db, $connessione)
    or die("Errore nella selezione di $dbname: " . mysql_error());
$risultato = mysql_query("select * from utenti", $connessione);

echo mysql_field_name($risultato, 0) . "\n";
echo mysql_field_name($risultato, 2);

L'esempio riportato sopra dovrebbe produrre il seguente output:
id_utente
password

Per motivi di compatibilità con il passato, anche mysql_fieldname() può essere usata. Questo comunque è sconsigliato.

mysql_field_seek

(PHP 3, PHP 4, PHP 5)

mysql_field_seek --  Imposta il puntatore al risultato ad un determinato indice di campo

Descrizione

int mysql_field_seek ( resource risultato, int indice_campo )

Esegue 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().

mysql_field_table

(PHP 3, PHP 4, PHP 5)

mysql_field_table --  Ottiene il nome della tabella in cui si trova il campo specificato

Descrizione

string mysql_field_table ( resource risultato, int indice_campo )

Ottiene 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

(PHP 3, PHP 4, PHP 5)

mysql_field_type --  Ottiene il tipo del campo specificato in un risultato

Descrizione

string mysql_field_type ( resource risultato, int indice_campo )

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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql");
    mysql_select_db("mysql");
    $risultato = mysql_query("SELECT * FROM func");
    $campi = mysql_num_fields($risultato);
    $righe   = mysql_num_rows($risultato);
    $tabella = mysql_field_table($risultato, 0);
    echo "La tabella'".$table."' ha ".$fields." campi e ".$righe." record\n";
    echo "La tabella ha i seguenti campi:\n";
    for ($i=0; $i < $campi; $i++) {
        $tipo = mysql_field_type($risultato, $i);
        $nome = mysql_field_name($risultato, $i);
        $lung = mysql_field_len($risultato, $i);
        $flag = mysql_field_flags($risultato, $i);
        echo $tipo." ".$nome." ".$lung." ".$flag."\n";
    }
    mysql_free_result($risultato);
    mysql_close();
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

La tabella 'func' ha 4 campi e 1 record
La tabella ha i seguenti campi:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

Per motivi di compatibilità con il passato, anche mysql_fieldtype() può essere usata. Questo comunque è sconsigliato.

mysql_free_result

(PHP 3, PHP 4, PHP 5)

mysql_free_result -- Libera la memoria occupata dal risultato

Descrizione

bool mysql_free_result ( resource risultato )

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

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info -- Ottine informazioni sul client MySQL

Descrizione

string mysql_get_client_info ( void )

mysql_get_client_info() restituisce una stringa che rappresenta la versione della libraria client.

Esempio 1. Esempio di mysql_get_client_info

<?php
    printf ("Informazioni sul client MySQL: %s\n", mysql_get_client_info());
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

Informazioni sul client MySQL: 3.23.39

Vedere anche: mysql_get_host_info(), mysql_get_proto_info() e mysql_get_server_info().

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info -- Ottiene le informazioni sull'host MySQL

Descrizione

string mysql_get_host_info ( [resource identificativo_connessione] )

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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql") or
        die("Connessione non riuscita: " . mysql_error());
    printf ("Informazioni sull'host MySQL: %s\n", mysql_get_host_info());
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

Informazioni sull'host MySQL: Localhost via UNIX socket

Vedere anche: mysql_get_client_info(), mysql_get_proto_info() e mysql_get_server_info().

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info -- Ottiene le informazion sul protocollo MySQL

Descrizione

int mysql_get_proto_info ( [resource identificativo_connessione] )

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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql") or
        die("Connessione non riuscita: " . mysql_error());
    printf ("Versione del protocollo MySQL: %s\n", mysql_get_proto_info());
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

Versione del protocollo MySQL: 10

Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_server_info().

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info -- Ottiene le informazioni sul server MySQL

Descrizione

string mysql_get_server_info ( [resource identificativo_connessione] )

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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql") or
        die("Connessione non riuscita: " . mysql_error());
    printf ("Versione server MySQL: %s\n", mysql_get_server_info());
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:

Versione server MySQL: 4.0.1-alpha

Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_proto_info().

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info --  Ottiene le informazioni relative alla query più recente.

Descrizione

string mysql_info ( [resource identificativo_connessione] )

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

INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0 
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0
I numeri sono indicati solo a titolo esemplificativo; i loro valori corrispondono alla query.

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()

mysql_insert_id

(PHP 3, PHP 4, PHP 5)

mysql_insert_id --  Ottiene l'identificativo generato dalla precedente operazione INSERT

Descrizione

int mysql_insert_id ( [resource identificativo_connessione] )

mysql_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

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql") or
        die("Connessione non riuscita: " . mysql_error());
    mysql_select_db("mio_db");

    mysql_query("INSERT INTO mia_tabella (prodotto) VALUES ('kossu')");
    printf ("L'ultimo recod inserito ha l'identificativo %d\n", mysql_insert_id());
?>

Vedere anche: mysql_query().

mysql_list_dbs

(PHP 3, PHP 4, PHP 5)

mysql_list_dbs --  Elenca i database disponibili in un server MySQL

Descrizione

resource mysql_list_dbs ( [resource identificativo_connessione] )

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()

<?php
$connessione = mysql_connect('localhost', 'utente_mysql', 'password_mysql');
$lista_db = mysql_list_dbs($connessione);

while ($riga = mysql_fetch_object($lista_db)) {
    echo $riga->Database . "\n";
}
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
database1
database2
database3
...

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

(PHP 3, PHP 4, PHP 5)

mysql_list_fields -- Elenca i campi di un risultato MySQL

Descrizione

resource mysql_list_fields ( string nome_database, string nome_tabella [, resource identificativo_connessione] )

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()

<?php
$connessione = mysql_connect('localhost', 'utente_mysql', 'password_mysql');

$campi = mysql_list_fields("database1", "tabella1", $connessione);
$colonne = mysql_num_fields($campi);

for ($i = 0; $i < $colonne; $i++) {
    echo mysql_field_name($campi, $i) . "\n";
}

L'esempio riportato sopra dovrebbe produrre il seguente output:
campo1
campo2
campo3
...

Per motivi di compatibilità con il passato, anche mysql_listfields() può essere usata. Questo comunque è sconsigliato.

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes -- Elenca i processi MySQL

Descrizione

resource mysql_list_processes ( [resource identificativo_connessione] )

mysql_list_processes() restituisce un risultato puntatore che descrive i thread attuali del server.

Esempio 1. Esempio di mysql_list_processes()

<?php
$connessione = mysql_connect('localhost', 'utente_mysql', 'password_mysql');

$risultato = mysql_list_processes($connessione);
while ($riga = mysql_fetch_row($risultato)){
    printf("%s %s %s %s %s\n", $riga["Id"], $riga["Host"], $riga["db"],
       $riga["Command"], $riga["Time"]);
}
mysql_free_result ($risultato);
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
1 localhost test Processlist 0
4 localhost mysql sleep 5

Vedere anche: mysql_thread_id()

mysql_list_tables

(PHP 3, PHP 4, PHP 5)

mysql_list_tables -- Elenca le tabelle in un database MySQL

Descrizione

resource mysql_list_tables ( string database [, resource identificativoi_connessione] )

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

<?php
    $nome_db = 'nome_db_mysql';

    if (!mysql_connect('host_mysql', 'utente_mysql', 'password_mysql')) {
        print 'Connessione a mysql non riuscita';
        exit;
    }

    $risultato = mysql_list_tables($nome_db);

    if (!$risultato) {
        print "Errorore database, Impossibile elencare le tabelle\n";
        print 'Errore MySQL: ' . mysql_error();
        exit;
    }

    while ($riga = mysql_fetch_row($risultato)) {
        print "Tabella: $riga[0]\n";
    }

    mysql_free_result($risultato);
?>

Vedere anche: mysql_list_dbs() e mysql_tablename().

mysql_num_fields

(PHP 3, PHP 4, PHP 5)

mysql_num_fields -- Ottiene il numero di campi nel risultato

Descrizione

int mysql_num_fields ( resource risultato )

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

(PHP 3, PHP 4, PHP 5)

mysql_num_rows -- Ottiene il numero di righe in un risultato

Descrizione

int mysql_num_rows ( resource risultato )

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()

<?php

$connessione = mysql_connect("localhost", "utente_mysql", "password_mysql");
mysql_select_db("database", $connessione);

$risultato = mysql_query("SELECT * FROM tabella1", $connessione);
$num_righe = mysql_num_rows($risultato);

echo "$num_righe Righe\n";

?>

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.

mysql_pconnect

(PHP 3, PHP 4, PHP 5)

mysql_pconnect --  Apre una connessione persiostente ad un server MySQL

Descrizione

resource mysql_pconnect ( [string server [, string nome_utente [, string password [, int flag_client]]]] )

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.

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping -- Esegue un ping su una connessione al server o riconnette se non non esiste la connessione

Descrizione

bool mysql_ping ( [resource identificativo_connessione] )

mysql_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

(PHP 3, PHP 4, PHP 5)

mysql_query -- Invia una query MySQL

Descrizione

resource mysql_query ( string query [, resource identificativo_connessione [, int modo_risultato]] )

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:

Esempio 1. mysql_query()

<?php
$risultato = mysql_query("SELECT * WHERE 1=1")
    or die("Query non valida: " . mysql_error());
?>

La seguente query non è semanticamente valida se mia_colonna non è una colonna della tabella mia_tabella, quindi mysql_query() fallisce e retituisce FALSE:

Esempio 2. mysql_query()

<?php
$risultato = mysql_query("SELECT mia_colonna FROM mia_tabella")
    or die("Query non valida: " . mysql_error());
?>

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().

mysql_real_escape_string

(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.

Descrizione

string mysql_real_escape_string ( string stringa_seza_escape [, resource identificativo_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()

<?php
$connessione = mysql_connect('localhost', 'utente_mysql', 'password_mysql');
$voce = "Zak's and Derick's Laptop";
$voce_con_escape = mysql_real_escape_string($voce);
printf ("La stringa con le sequenze di escape: %s\n", $voce_con_escape);
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
La stringa con le sequenze di escape: Zak\'s and Derick\'s Laptop

Vedere anche : mysql_escape_string() e mysql_character_set_name().

mysql_result

(PHP 3, PHP 4, PHP 5)

mysql_result -- Ottiene i dati dal risultato

Descrizione

mixed mysql_result ( resource risultato, int campo [, mixed campo] )

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().

mysql_select_db

(PHP 3, PHP 4, PHP 5)

mysql_select_db -- Seleziona un database MySQL

Descrizione

bool mysql_select_db ( string nome_database [, resource identificativo_connessione] )

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

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat -- Ottiene l'attuale stato del sistema

Descrizione

string mysql_stat ( [resource identificativo_connessione] )

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

<?php
$connessione = mysql_connect('localhost', "utente_mysql", "password_mysql");
$stato = explode('  ', mysql_stat($connessione));
print_r($stato);
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
Array
(
    [0] => Uptime: 5380
    [1] => Threads: 2
    [2] => Questions: 1321299
    [3] => Slow queries: 0
    [4] => Opens: 26
    [5] => Flush tables: 1
    [6] => Open tables: 17
    [7] => Queries per second avg: 245.595
)

mysql_tablename

(PHP 3, PHP 4, PHP 5)

mysql_tablename -- Ottiene il nome della tabella

Descrizione

string mysql_tablename ( resource risultato, int i )

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().

Esempio 1. Esempio di mysql_tablename()

<?php
    mysql_connect("localhost", "utente_mysql", "password_mysql");
    $risultato = mysql_list_tables("mio_db");

    for ($i = 0; $i < mysql_num_rows($risultato); $i++)
        printf ("Tabela: %s\n", mysql_tablename($risultato, $i));

    mysql_free_result($risultato);
?>

Vedere anche: mysql_list_tables().

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id -- Restituisce l'attuale thread ID

Descrizione

int mysql_thread_id ( [resource identificativo_connessione] )

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()

<?php
$connessione = mysql_connect('localhost', 'utente_mysql', 'password_mysql');
$thread_id = mysql_thread_id($connessione);
if ($thread_id){
    printf ("L'attuale thread è %d\n", $thread_id);
}
?>

L'esempio riportato sopra dovrebbe produrre il seguente output:
L'attuale thread è 73

Vedere anche: mysql_ping() e mysql_list_processes().

mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query --  Invia una query SQL a MySQL senza caricare e bufferare le righe risultanti

Descrizione

resource mysql_unbuffered_query ( string query [, resource identificativo_connessione [, int modo_risultato]] )

mysql_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().

LXXXVII. MySQL Functions (PDO_MYSQL)

Introduzione

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.


Costanti predefinite

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.

PDO_MYSQL_ATTR_USE_BUFFERED_QUERY (integer)

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

<?php
if ($db->getAttribute(PDO_ATTR_DRIVERNAME) == 'mysql')) {
 $stmt = $db->prepare('select * from foo',
    array(PDO_MYSQL_ATTR_USE_UNBUFFERED_QUERY => true));
} else {
 die("my application only works with mysql; I should use \$stmt->fetchAll() instead");
}

Sommario
PDO_MYSQL DSN -- Connecting to MySQL databases

PDO_MYSQL DSN

(no version information, might be only in CVS)

PDO_MYSQL DSN -- Connecting to MySQL databases

Descrizione

The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is mysql:.

host

The hostname on which the database server resides.

dbname

The name of the database.

Esempi

Esempio 1. PDO_MYSQL DSN examples

The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:
mysql:host=localhost;dbname=testdb

LXXXVIII. MySQL Improved Extension

Introduzione

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.


Requisiti

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.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. MySQLi Configuration Options

NameDefaultChangeableChangelog
mysqli.max_links"-1"PHP_INI_SYSTEMAvailable since PHP 5.0.0.
mysqli.default_port"3306"PHP_INI_ALLAvailable since PHP 5.0.0.
mysqli.default_socketNULLPHP_INI_ALLAvailable since PHP 5.0.0.
mysqli.default_hostNULLPHP_INI_ALLAvailable since PHP 5.0.0.
mysqli.default_userNULLPHP_INI_ALLAvailable since PHP 5.0.0.
mysqli.default_pwNULLPHP_INI_ALLAvailable 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.

mysqli.max_links integer

The maximum number of MySQL connections per process.

mysqli.default_port string

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.

mysqli.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysqli.default_host string

The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode.

mysqli.default_user string

The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode.

mysqli.default_pw string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.


Classi predefinite

mysqli

Represents a connection between PHP and a MySQL database.


Costruttori

  • mysqli - construct a new mysqli object


Metodi

  • 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


Proprietà

  • 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


mysqli_stmt

Represents a prepared statement.


Metodi

  • 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


Proprietà

  • 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


mysqli_result

Represents the result set obtained from a query against the database.


Metodi

  • 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


Proprietà

  • 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


Costanti predefinite

Tabella 2. MySQLi Constants

NameDescription
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.

Examples

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

Sommario
mysqli_affected_rows -- Gets the number of affected rows in a previous MySQL operation
mysqli_autocommit -- Turns on or off auto-commiting database modifications
mysqli_bind_param -- Alias for mysqli_stmt_bind_param()
mysqli_bind_result -- Alias for mysqli_stmt_bind_result()
mysqli_change_user -- Changes the user of the specified database connection
mysqli_character_set_name -- Returns the default character set for the database connection
mysqli_client_encoding -- Alias of mysqli_character_set_name()
mysqli_close -- Closes a previously opened database connection
mysqli_commit -- Commits the current transaction
mysqli_connect_errno -- Returns the error code from last connect call
mysqli_connect_error -- Returns a string description of the last connect error
mysqli_connect -- Open a new connection to the MySQL server
mysqli_data_seek -- Adjusts the result pointer to an arbitary row in the result
mysqli_debug -- Performs debugging operations
mysqli_disable_reads_from_master -- Disable reads from master
mysqli_disable_rpl_parse -- Disable RPL parse
mysqli_dump_debug_info -- Dump debugging information into the log
mysqli_embedded_connect -- Open a connection to an embedded mysql server
mysqli_enable_reads_from_master -- Enable reads from master
mysqli_enable_rpl_parse -- Enable RPL parse
mysqli_errno -- Returns the error code for the most recent function call
mysqli_error -- Returns a string description of the last error
mysqli_escape_string -- Alias of mysqli_real_escape_string()
mysqli_execute -- Alias for mysqli_stmt_execute()
mysqli_fetch_array -- Fetch a result row as an associative, a numeric array, or both
mysqli_fetch_assoc -- Fetch a result row as an associative array
mysqli_fetch_field_direct --  Fetch meta-data for a single field
mysqli_fetch_field -- Returns the next field in the result set
mysqli_fetch_fields -- Returns an array of objects representing the fields in a result set
mysqli_fetch_lengths -- Returns the lengths of the columns of the current row in the result set
mysqli_fetch_object -- Returns the current row of a result set as an object
mysqli_fetch_row -- Get a result row as an enumerated array
mysqli_fetch -- Alias for mysqli_stmt_fetch()
mysqli_field_count -- Returns the number of columns for the most recent query
mysqli_field_seek --  Set result pointer to a specified field offset
mysqli_field_tell --  Get current field offset of a result pointer
mysqli_free_result -- Frees the memory associated with a result
mysqli_get_client_info -- Returns the MySQL client version as a string
mysqli_get_client_version -- Get MySQL client info
mysqli_get_host_info -- Returns a string representing the type of connection used
mysqli_get_metadata -- Alias for mysqli_stmt_result_metadata()
mysqli_get_proto_info -- Returns the version of the MySQL protocol used
mysqli_get_server_info -- Returns the version of the MySQL server
mysqli_get_server_version -- Returns the version of the MySQL server as an integer
mysqli_info -- Retrieves information about the most recently executed query
mysqli_init --  Initializes MySQLi and returns a resource for use with mysqli_real_connect()
mysqli_insert_id -- Returns the auto generated id used in the last query
mysqli_kill -- Asks the server to kill a MySQL thread
mysqli_master_query -- Enforce execution of a query on the master in a master/slave setup
mysqli_more_results -- Check if there any more query results from a multi query
mysqli_multi_query -- Performs a query on the database
mysqli_next_result -- Prepare next result from multi_query
mysqli_num_fields --  Get the number of fields in a result
mysqli_num_rows --  Gets the number of rows in a result
mysqli_options -- Set options
mysqli_param_count -- Alias for mysqli_stmt_param_count()
mysqli_ping --  Pings a server connection, or tries to reconnect if the connection has gone down
mysqli_prepare --  Prepare a SQL statement for execution
mysqli_query -- Performs a query on the database
mysqli_real_connect -- Opens a connection to a mysql server
mysqli_real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
mysqli_real_query -- Execute an SQL query
mysqli_report -- Enables or disables internal report functions
mysqli_rollback -- Rolls back current transaction
mysqli_rpl_parse_enabled -- Check if RPL parse is enabled
mysqli_rpl_probe -- RPL probe
mysqli_rpl_query_type -- Returns RPL query type
mysqli_select_db -- Selects the default database for database queries
mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()
mysqli_send_query -- Send the query and return
mysqli_server_end -- Shut down the embedded server
mysqli_server_init -- Initialize embedded server
mysqli_set_charset -- Sets the default client character set
mysqli_set_opt -- Alias of mysqli_options()
mysqli_sqlstate -- Returns the SQLSTATE error from previous MySQL operation
mysqli_ssl_set -- Used for establishing secure connections using SSL
mysqli_stat -- Gets the current system status
mysqli_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
mysqli_stmt_bind_param -- Binds variables to a prepared statement as parameters
mysqli_stmt_bind_result -- Binds variables to a prepared statement for result storage
mysqli_stmt_close -- Closes a prepared statement
mysqli_stmt_data_seek -- Seeks to an arbitray row in statement result set
mysqli_stmt_errno -- Returns the error code for the most recent statement call
mysqli_stmt_error -- Returns a string description for last statement error
mysqli_stmt_execute -- Executes a prepared Query
mysqli_stmt_fetch --  Fetch results from a prepared statement into the bound variables
mysqli_stmt_free_result -- Frees stored result memory for the given statement handle
mysqli_stmt_init --  Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli_stmt_num_rows -- Return the number of rows in statements result set
mysqli_stmt_param_count -- Returns the number of parameter for the given statement
mysqli_stmt_prepare --  Prepare a SQL statement for execution
mysqli_stmt_reset -- Resets a prepared statement
mysqli_stmt_result_metadata -- Returns result set metadata from a prepared statement
mysqli_stmt_send_long_data -- Send data in blocks
mysqli_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation
mysqli_stmt_store_result -- Transfers a result set from a prepared statement
mysqli_store_result -- Transfers a result set from the last query
mysqli_thread_id -- Returns the thread ID for the current connection
mysqli_thread_safe -- Returns whether thread safety is given or not
mysqli_use_result -- Initiate a result set retrieval
mysqli_warning_count -- Returns the number of warnings from the last query for the given link

mysqli_affected_rows

(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 operation

Description

Procedural style:

int mysqli_affected_rows ( mysqli link )

Object oriented style (property):

class mysqli {

int affected_rows

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

mysqli_autocommit

(PHP 5)

mysqli_autocommit

(no version information, might be only in CVS)

mysqli->autocommit -- Turns on or off auto-commiting database modifications

Description

Procedural style:

bool mysqli_autocommit ( mysqli link, bool mode )

Object oriented style (method)

class mysqli {

bool autocommit ( bool mode )

}

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'.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
$mysqli->autocommit(TRUE);

if ($result = $mysqli->query("SELECT @@autocommit")) {
    $row = $result->fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
mysqli_autocommit($link, TRUE);

if ($result = mysqli_query($link, "SELECT @@autocommit")) {
    $row = mysqli_fetch_row($result);
    printf("Autocommit is %s\n", $row[0]);
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Autocommit is 1

mysqli_bind_param

(PHP 5)

mysqli_bind_param -- Alias for mysqli_stmt_bind_param()

Description

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.

Vedere anche:

mysqli_stmt_bind_param().

mysqli_bind_result

(PHP 5)

mysqli_bind_result -- Alias for mysqli_stmt_bind_result()

Description

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.

mysqli_change_user

(PHP 5)

mysqli_change_user

(no version information, might be only in CVS)

mysqli->change_user -- Changes the user of the specified database connection

Description

Procedural style:

bool mysqli_change_user ( mysqli link, string user, string password, string database )

Object oriented style (method):

class mysqli {

bool change_user ( string user, string password, string database )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");
                                         
/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
    $row = $result->fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");
                                         
/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database: %s\n", $row[0]);
    mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
    $row = mysqli_fetch_row($result);
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Default database: world
Value of variable a is NULL

mysqli_character_set_name

(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 connection

Description

Procedural style:

string mysqli_character_set_name ( mysqli link )

Object oriented style (method):

class mysqli {

string character_set_name ( void )

}

Returns the current character set for the database connection specified by the link parameter.

Valori restituiti

The default character set for the current connection

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
                                                                              
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = $mysqli->character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
                                                                              
/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = mysqli_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Current character set is latin1_swedish_ci

mysqli_client_encoding

(PHP 5)

mysqli_client_encoding -- Alias of mysqli_character_set_name()

Description

This function is an alias of mysqli_character_set_name(). For a detailled descripton see description of mysqli_character_set_name().

mysqli_close

(PHP 5)

mysqli_close

(no version information, might be only in CVS)

mysqli->close -- Closes a previously opened database connection

Description

Procedural style:

bool mysqli_close ( mysqli link )

Object oriented style (method):

class mysqli {

bool close ( void )

}

The mysqli_close() function closes a previously opened database connection specified by the link parameter.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_commit

(PHP 5)

mysqli_commit

(no version information, might be only in CVS)

mysqli->commit -- Commits the current transaction

Description

Procedural style:

bool mysqli_commit ( mysqli link )

Object oriented style (method)

class mysqli {

bool commit ( void )

}

Commits the current transaction for the database connection specified by the link parameter.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
$mysqli->commit();

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* close connection */
mysqli_close($link);
?>

mysqli_connect_errno

(PHP 5)

mysqli_connect_errno -- Returns the error code from last connect call

Description

int mysqli_connect_errno ( void )

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.

Valori restituiti

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Esempi

Esempio 1. mysqli_connect_errno sample

<?php

$link = @mysqli_connect("localhost", "nonexisting_user", "");

if (!$link) {
    printf("Can't connect to localhost. Errorcode: %d\n", mysqli_connect_errno());
}
?>

mysqli_connect_error

(PHP 5)

mysqli_connect_error -- Returns a string description of the last connect error

Description

string mysqli_connect_error ( void )

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.

Valori restituiti

A string that describes the error. An empty string if no error occurred.

Esempi

Esempio 1. mysqli_connect_error sample

<?php

$link = @mysqli_connect("localhost", "nonexisting_user", "");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
}
?>

mysqli_connect

(PHP 5)

mysqli_connect

(no version information, might be only in CVS)

mysqli() -- Open a new connection to the MySQL server

Description

Procedural style

mysqli mysqli_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

Object oriented style (constructor):

class mysqli {

__construct ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )

}

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.

Valori restituiti

Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Host information: %s\n", $mysqli->host_info);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Host information: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Host information: Localhost via UNIX socket

mysqli_data_seek

(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 result

Description

Procedural style:

bool mysqli_data_seek ( mysqli_result result, int offset )

Object oriented style (method):

class mysqli_result {

bool data_seek ( int offset )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = $mysqli->query( $query)) {

    /* seek to row no. 400 */
    $result->data_seek(399);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);
        
    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

if ($result = mysqli_query($link, $query)) {

    /* seek to row no. 400 */
    mysqli_data_seek($result, 399);

    /* fetch row */
    $row = mysqli_fetch_row($result);

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);
        
    /* free result set*/
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

City: Benin City  Countrycode: NGA

mysqli_debug

(PHP 5)

mysqli_debug -- Performs debugging operations

Description

bool mysqli_debug ( string debug )

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.

Valori restituiti

mysqli_debug() doesn't return any value.

Esempi

Esempio 1. Generating a Trace File

<?php
    
/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:0,/tmp/client.trace");
    
?>

mysqli_disable_reads_from_master

(PHP 5)

mysqli_disable_reads_from_master

(no version information, might be only in CVS)

mysqli->disable_reads_from_master -- Disable reads from master

Description

Procedural style:

bool mysqli_disable_reads_from_master ( mysqli link )

Object oriented style (method):

class mysqli {

void disable_reads_from_master ( void )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_disable_rpl_parse

(PHP 5)

mysqli_disable_rpl_parse -- Disable RPL parse

Description

bool mysqli_disable_rpl_parse ( mysqli link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_dump_debug_info

(PHP 5)

mysqli_dump_debug_info

(no version information, might be only in CVS)

mysqli->dump_debug_info -- Dump debugging information into the log

Description

bool mysqli_dump_debug_info ( mysqli link )

This 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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

mysqli_debug().

mysqli_embedded_connect

(PHP 5 <= 5.0.4)

mysqli_embedded_connect -- Open a connection to an embedded mysql server

Description

mysqli mysqli_embedded_connect ( [string dbname] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_enable_reads_from_master

(PHP 5)

mysqli_enable_reads_from_master -- Enable reads from master

Description

bool mysqli_enable_reads_from_master ( mysqli link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_enable_rpl_parse

(PHP 5)

mysqli_enable_rpl_parse -- Enable RPL parse

Description

bool mysqli_enable_rpl_parse ( mysqli link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_errno

(PHP 5)

mysqli_errno

(no version information, might be only in CVS)

mysqli->errno -- Returns the error code for the most recent function call

Description

Procedural style:

int mysqli_errno ( mysqli link )

Object oriented style (property):

class mysqli {

int errno

}

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.

Valori restituiti

An error code value for the last call, if it failed. zero means no error occurred.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errorcode: %d\n", $mysqli->errno);
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errorcode: %d\n", mysqli_errno($link));
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Errorcode: 1193

mysqli_error

(PHP 5)

mysqli_error -- Returns a string description of the last error

Description

Procedural style:

string mysqli_error ( mysqli link )

Object oriented style (property)

class mysqli {

string error

}

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.

Valori restituiti

A string that describes the error. An empty string if no error occurred.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errormessage: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errormessage: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Errormessage: Unknown system variable 'a'

mysqli_escape_string

(PHP 5)

mysqli_escape_string -- Alias of mysqli_real_escape_string()

Description

This function is an alias of mysqli_real_escape_string().

mysqli_execute

(PHP 5)

mysqli_execute -- Alias for mysqli_stmt_execute()

Description

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.

Vedere anche:

mysqli_stmt_execute().

mysqli_fetch_array

(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 both

Description

Procedural style:

mixed mysqli_fetch_array ( mysqli_result result [, int resulttype] )

Object oriented style (method):

class mysqli_result {

mixed fetch_array ( [int resulttype] )

}

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.

Valori restituiti

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);  

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);  

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);  

/* free result set */
$result->close();

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);

/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);  

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);  

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);  

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

mysqli_fetch_assoc

(PHP 5)

mysqli_fetch_assoc

(no version information, might be only in CVS)

mysqli->fetch_assoc -- Fetch a result row as an associative array

Description

Procedural style:

array mysqli_fetch_assoc ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

array fetch_assoc ( void )

}

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.

Valori restituiti

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

mysqli_fetch_field_direct

(PHP 5)

mysqli_fetch_field_direct

(no version information, might be only in CVS)

result->fetch_field_direct --  Fetch meta-data for a single field

Description

Procedural style:

object mysqli_fetch_field_direct ( mysqli_result result, int fieldnr )

Object oriented style (method):

class mysqli_result {

object fetch_field_direct ( int fieldnr )

}

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.

Valori restituiti

Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.

Tabella 1. Object attributes

AttributeDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
defThe default value for this field, represented as a string
max_lengthThe maximum width of the field for the result set.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = $result->fetch_field_direct(1);
 
    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);
    
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = mysqli_fetch_field_direct($result, 1);
 
    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

mysqli_fetch_field

(PHP 5)

mysqli_fetch_field

(no version information, might be only in CVS)

result->fetch_field -- Returns the next field in the result set

Description

Procedural style:

object mysqli_fetch_field ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

object fetch_field ( void )

}

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.

Valori restituiti

Returns an object which contains field definition information or FALSE if no field information is available.

Tabella 1. Object properties

PropertyDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
defThe default value for this field, represented as a string
max_lengthThe maximum width of the field for the result set.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {
 
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }    
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {
 
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

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

mysqli_fetch_fields

(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 set

Description

Procedural Style:

array mysqli_fetch_fields ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

array fetch_fields ( void )

}

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.

Valori restituiti

Returns an array of objects which contains field definition information or FALSE if no field information is available.

Tabella 1. Object properties

PropertyDescription
nameThe name of the column
orgnameOriginal column name if an alias was specified
tableThe name of the table this field belongs to (if not calculated)
orgtableOriginal table name if an alias was specified
defThe default value for this field, represented as a string
max_lengthThe maximum width of the field for the result set.
flagsAn integer representing the bit-flags for the field.
typeThe data type used for this field
decimalsThe number of decimals used (for integer fields)

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    $finfo = $result->fetch_fields();

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }    
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all columns */
    $finfo = mysqli_fetch_fields($result);
 
    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }    
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

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

mysqli_fetch_lengths

(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 set

Description

Procedural style:

array mysqli_fetch_lengths ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

array lengths

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli->query($query)) {

    $row = $result->fetch_row();

    /* display column lengths */
    foreach ($result->lengths as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

    $row = mysqli_fetch_row($result);

    /* display column lengths */
    foreach (mysqli_fetch_lengths($result) as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

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

mysqli_fetch_object

(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 object

Description

Procedural style:

mixed mysqli_fetch_object ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

mixed fetch_object ( void )

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

mysqli_fetch_row

(PHP 5)

mysqli_fetch_row

(no version information, might be only in CVS)

result->fetch_row -- Get a result row as an enumerated array

Description

Procedural style:

mixed mysqli_fetch_row ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

mixed fetch_row ( void )

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

mysqli_fetch

(PHP 5)

mysqli_fetch -- Alias for mysqli_stmt_fetch()

Description

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.

Vedere anche:

mysqli_stmt_fetch().

mysqli_field_count

(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 query

Description

Procedural style:

int mysqli_field_count ( mysqli link )

Object oriented style (method):

class mysqli_result {

int field_count ( void )

}

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.

Valori restituiti

An integer representing the number of fields in a result set

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query( "DROP TABLE IF EXISTS friends"); 
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))"); 
 
$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");


$mysqli->real_query($HTTP_POST_VARS['query']);

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = $mysqli->store_result();
    
    /* process resultset */
    $row = $result->fetch_row();

    /* free resultset */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends"); 
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))"); 
 
mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, $HTTP_POST_VARS['query']);

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);
    
    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

mysqli_field_seek

(PHP 5)

mysqli_field_seek

(no version information, might be only in CVS)

result->field_seek --  Set result pointer to a specified field offset

Description

Procedural style:

bool mysqli_field_seek ( mysqli_result result, int fieldnr )

Object oriented style (method):

class mysqli_result {

bool field_seek ( int fieldnr )

}

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.

Valori restituiti

mysqli_field_seek() returns previuos value of field cursor.

Vedere anche:

mysqli_fetch_field().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for 2nd column */
    $result->field_seek(1);
    $finfo = $result->fetch_field();
 
    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);
    
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for 2nd column */
    mysqli_field_seek($result, 1);
    $finfo = mysqli_fetch_field($result);
 
    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

mysqli_field_tell

(PHP 5)

mysqli_field_tell

(no version information, might be only in CVS)

result->current_field --  Get current field offset of a result pointer

Description

Procedural style:

int mysqli_field_tell ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

int current_field

}

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().

Valori restituiti

Returns current offset of field cursor.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        /* get fieldpointer offset */
        $currentfield = $result->current_field;

        printf("Column %d:\n", $currentfield); 
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }    
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {
 
        /* get fieldpointer offset */
        $currentfield = mysqli_field_tell($result);

        printf("Column %d:\n", $currentfield); 
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

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

mysqli_free_result

(PHP 5)

mysqli_free_result

(no version information, might be only in CVS)

result->free -- Frees the memory associated with a result

Description

Procedural style:

void mysqli_free_result ( mysqli_result result )

Object oriented style (method):

class mysqli_result {

void free ( void )

}

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.

Valori restituiti

This function doesn't return any value.

mysqli_get_client_info

(PHP 5)

mysqli_get_client_info -- Returns the MySQL client version as a string

Description

string mysqli_get_client_info ( void )

The mysqli_get_client_info() function is used to return a string representing the client version being used in the MySQLi extension.

Valori restituiti

A string that represents the MySQL client library version

Esempi

Esempio 1. mysqli_get_client_info

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

mysqli_get_client_version

(PHP 5)

mysqli_get_client_version -- Get MySQL client info

Description

int mysqli_get_client_version ( void )

Returns client version number as an integer.

Valori restituiti

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.

Esempi

Esempio 1. mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

mysqli_get_host_info

(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 used

Description

Procdural style:

string mysqli_get_host_info ( mysqli link )

Object oriented style (property):

class mysqli {

string host_info

}

The mysqli_get_host_info() function returns a string describing the connection represented by the link parameter is using (including the server host name).

Valori restituiti

A character string representing the server hostname and the connection type.

Vedere anche:

mysqli_get_proto_info().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", $mysqli->host_info);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Host info: Localhost via UNIX socket

mysqli_get_metadata

(PHP 5)

mysqli_get_metadata -- Alias for mysqli_stmt_result_metadata()

Description

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.

mysqli_get_proto_info

(PHP 5)

mysqli_get_proto_info

(no version information, might be only in CVS)

mysqli->protocol_version -- Returns the version of the MySQL protocol used

Description

Procedural style:

int mysqli_get_proto_info ( mysqli link )

Object oriented style (property):

class mysqli {

string protocol_version

}

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Valori restituiti

Returns an integer representing the protocol version.

Vedere anche:

mysqli_get_host_info().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Protocol version: 10

mysqli_get_server_info

(PHP 5)

mysqli_get_server_info

(no version information, might be only in CVS)

mysqli->server_info -- Returns the version of the MySQL server

Description

Procedural style:

string mysqli_get_server_info ( mysqli link )

Object oriented style (property):

class mysqli {

string server_info

}

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to (represented by the link parameter).

Valori restituiti

A character string representing the server version.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", $mysqli->server_info);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Server version: 4.1.2-alpha-debug

mysqli_get_server_version

(PHP 5)

mysqli_get_server_version -- Returns the version of the MySQL server as an integer

Description

Procedural style:

int mysqli_get_server_version ( mysqli link )

Object oriented style (property):

class mysqli {

int server_version

}

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).

Valori restituiti

An integer representing the server version.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", $mysqli->server_version);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Server version: 40102

mysqli_info

(PHP 5)

mysqli_info

(no version information, might be only in CVS)

mysqli->info -- Retrieves information about the most recently executed query

Description

Procedural style:

string mysqli_info ( mysqli link )

Object oriented style (property)

class mysqli {

string info

}

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 typeExample 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.

Valori restituiti

A character string representing additional information about the most recently executed query.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Records: 150  Duplicates: 0  Warnings: 0

mysqli_init

(PHP 5)

mysqli_init --  Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Description

mysqli mysqli_init ( void )

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.

Valori restituiti

Returns an object.

mysqli_insert_id

(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 query

Description

Procedural style:

int mysqli_insert_id ( mysqli link )

Object oriented style (property):

class mysqli {

int insert_id

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));

/* drop table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

New Record has id 1.

mysqli_kill

(PHP 5)

mysqli_kill

(no version information, might be only in CVS)

mysqli->kill -- Asks the server to kill a MySQL thread

Description

Procedural style:

bool mysqli_kill ( mysqli link, int processid )

Object oriented style (method)

class mysqli {

bool kill ( int processid )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

mysqli_thread_id().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error: MySQL server has gone away

mysqli_master_query

(PHP 5)

mysqli_master_query -- Enforce execution of a query on the master in a master/slave setup

Description

bool mysqli_master_query ( mysqli link, string query )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_more_results

(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 query

Description

bool mysqli_more_results ( mysqli link )

mysqli_more_results() indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_multi_query

(PHP 5)

mysqli_multi_query

(no version information, might be only in CVS)

mysqli->multi_query -- Performs a query on the database

Description

Procedural style:

bool mysqli_multi_query ( mysqli link, string query )

Object oriented style (method):

class mysqli {

bool multi_query ( string query )

}

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().

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->close();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

mysqli_next_result

(PHP 5)

mysqli_next_result

(no version information, might be only in CVS)

mysqli->next_result -- Prepare next result from multi_query

Description

bool mysqli_next_result ( mysqli link )

mysqli_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().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_num_fields

(PHP 5)

mysqli_num_fields

(no version information, might be only in CVS)

result->field_count --  Get the number of fields in a result

Description

Procedural style:

int mysqli_num_fields ( mysqli_result result )

Object oriented style (property):

class mysqli_result {

int field_count

}

mysqli_num_fields() returns the number of fields from specified result set.

Valori restituiti

The number of fields from a result set

Vedere anche:

mysqli_fetch_field().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = mysqli_num_fields($result);

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Result set has 5 fields.

mysqli_num_rows

(PHP 5)

mysqli_num_rows --  Gets the number of rows in a result

Description

Procedural style:

int mysqli_num_rows ( mysqli result )

Object oriented style (property):

class mysqli {

int num_rows

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = mysqli_num_rows($result);

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Result set has 239 rows.

mysqli_options

(PHP 5)

mysqli_options

(no version information, might be only in CVS)

mysqli->options -- Set options

Description

Procedural style:

bool mysqli_options ( mysqli link, int option, mixed value )

Object oriented style (method)

class mysqli {

bool options ( int option, mixed value )

}

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

NameDescription
MYSQLI_OPT_CONNECT_TIMEOUTconnection timeout in seconds
MYSQLI_OPT_LOCAL_INFILEenable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_CMDcommand 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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_param_count

(PHP 5)

mysqli_param_count -- Alias for mysqli_stmt_param_count()

Description

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.

mysqli_ping

(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 down

Description

Procedural style:

bool mysqli_ping ( mysqli link )

Object oriented style (method):

class mysqli {

bool ping ( void )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if ($mysqli->ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if (mysqli_ping($link)) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Our connection is ok!

mysqli_prepare

(PHP 5)

mysqli_prepare

(no version information, might be only in CVS)

mysqli->prepare --  Prepare a SQL statement for execution

Description

Procedure style:

mysqli_stmt mysqli_prepare ( mysqli link, string query )

Object oriented style (method)

class mysqli {

mysqli_stmt prepare ( string query )

}

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.

Valori restituiti

mysqli_prepare() returns a statement object or FALSE if an error occured.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
} 

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
} 

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Amersfoort is in district Utrecht

mysqli_query

(PHP 5)

mysqli_query

(no version information, might be only in CVS)

mysqli->query -- Performs a query on the database

Description

Procedural style:

mixed mysqli_query ( mysqli link, string query [, int resultmode] )

Object oriented style (method):

class mysqli {

mixed query ( string query [, int resultmode] )

}

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().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an 
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    /* free result set */
    mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an 
       'out of sync' error */
    if (!mysqli_query($link, "SET @a:='this will not work'")) {
        printf("Error: %s\n", mysqli_error($link));
    }
    mysqli_free_result($result);
}

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

mysqli_real_connect

(PHP 5)

mysqli_real_connect

(no version information, might be only in CVS)

mysqli->real_connect -- Opens a connection to a mysql server

Description

Procedural 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 {

bool real_connect ( [string hostname [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]] )

}

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

    NameDescription
    MYSQLI_CLIENT_COMPRESSUse compression protocol
    MYSQLI_CLIENT_FOUND_ROWSreturn number of matched rows, not the number of affected rows
    MYSQLI_CLIENT_IGNORE_SPACEAllow 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_SSLUse 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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php

/* create a connection object which is not connected */
$mysqli = mysqli_init();

/* set connection options */
$mysqli->options(MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);

/* connect to server */
$mysqli->real_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("Connection: %s\n.", $mysqli->host_info);

$mysqli->close();
?>

Esempio 2. Procedural style

<?php

/* create a connection object which is not connected */
$link = mysqli_init();

/* set connection options */
mysqli_options($link, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);

/* connect to server */
mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("Connection: %s\n.", mysqli_get_host_info($link));

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Connection: Localhost via UNIX socket

mysqli_real_escape_string

(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 connection

Description

Procedural style:

string mysqli_real_escape_string ( mysqli link, string escapestr )

Object oriented style (method):

class mysqli {

string real_escape_string ( string escapestr )

}

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.

Valori restituiti

Returns an escaped string.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
} 

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
} 

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error: 42000
1 Row inserted.

mysqli_real_query

(PHP 5)

mysqli_real_query

(no version information, might be only in CVS)

mysqli->real_query -- Execute an SQL query

Description

Procedural style

bool mysqli_real_query ( mysqli link, string query )

Object oriented style (method):

class mysqli {

bool real_query ( string query )

}

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().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_report

(PHP 5)

mysqli_report -- Enables or disables internal report functions

Description

bool mysqli_report ( int flags )

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).

Tabella 1. Supported flags

NameDescription
MYSQLI_REPORT_OFFTurns reporting off
MYSQLI_REPORT_ERRORReport errors from mysqli function calls
MYSQLI_REPORT_INDEXReport if no index or bad index was used in a query
MYSQLI_REPORT_ALLSet all options (report all)

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a warning */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
$result->close();

$mysqli->close();
?>

mysqli_rollback

(PHP 5)

mysqli_rollback

(no version information, might be only in CVS)

mysqli->rollback -- Rolls back current transaction

Description

bool mysqli_rollback ( mysqli link )

class mysqli {

bool rollback ( void )

}

Rollbacks the current transaction for the database specified by the link parameter.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli->commit();

/* delete all rows */
$mysqli->query("DELETE FROM myCity");

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Rollback */
$mysqli->rollback();

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

0 rows in table myCity.
50 rows in table myCity (after rollback).

mysqli_rpl_parse_enabled

(PHP 5)

mysqli_rpl_parse_enabled -- Check if RPL parse is enabled

Description

int mysqli_rpl_parse_enabled ( mysqli link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_rpl_probe

(PHP 5)

mysqli_rpl_probe -- RPL probe

Description

bool mysqli_rpl_probe ( mysqli link )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_rpl_query_type

(PHP 5)

mysqli_rpl_query_type

(no version information, might be only in CVS)

mysqli->rpl_query_type -- Returns RPL query type

Description

Procedural style:

int mysqli_rpl_query_type ( mysqli link, string query )

Object oriented style (method)

class mysqli {

int rpl_query_type ( string query )

}

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.

mysqli_select_db

(PHP 5)

mysqli_select_db

(no version information, might be only in CVS)

mysqli->select_db -- Selects the default database for database queries

Description

bool mysqli_select_db ( mysqli link, string dbname )

The 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().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Default database is test.
Default database is world.

mysqli_send_long_data

(PHP 5)

mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()

Description

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.

mysqli_send_query

(PHP 5)

mysqli_send_query

(no version information, might be only in CVS)

mysqli->send_query -- Send the query and return

Description

Procedural style:

bool mysqli_send_query ( mysqli link, string query )

Object oriented style (method)

class mysqli {

bool send_query ( string query )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_server_end

(PHP 5 <= 5.0.4)

mysqli_server_end -- Shut down the embedded server

Description

void mysqli_server_end ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_server_init

(PHP 5 <= 5.0.4)

mysqli_server_init -- Initialize embedded server

Description

bool mysqli_server_init ( [array server [, array groups]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

mysqli_set_charset

(PHP 5 >= 5.1.0RC1)

mysqli_set_charset

(no version information, might be only in CVS)

mysqli->set_charset -- Sets the default client character set

Description

bool mysqli_set_charset ( mysqli link, string charset )

The 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)

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Current character set: utf8

mysqli_set_opt

(PHP 5)

mysqli_set_opt -- Alias of mysqli_options()

Description

This function is an alias of mysqli_options().

mysqli_sqlstate

(PHP 5)

mysqli_sqlstate

(no version information, might be only in CVS)

mysqli->sqlstate -- Returns the SQLSTATE error from previous MySQL operation

Description

Procedural style:

string mysqli_sqlstate ( mysqli link )

Object oriented style (property):

class mysqli {

string sqlstate

}

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.

Valori restituiti

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Vedere anche:

mysqli_errno() e mysqli_error().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error - SQLSTATE 42S01.

mysqli_ssl_set

(PHP 5)

mysqli_ssl_set

(no version information, might be only in CVS)

mysqli->ssl_set -- Used for establishing secure connections using SSL

Description

Procedural style:

bool mysqli_ssl_set ( mysqli link, string key, string cert, string ca, string capath, string cipher )

Object oriented style (method):

class mysqli {

bool ssl_set ( string key, string cert, string ca, string capath, string cipher )

}

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

Valori restituiti

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

mysqli_stat

(PHP 5)

mysqli_stat

(no version information, might be only in CVS)

mysqli->stat -- Gets the current system status

Description

Procedural style:

string mysqli_stat ( mysqli link )

Object oriented style (method):

class mysqli {

string stat ( void )

}

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.

Valori restituiti

A string describing the server status. FALSE if an error occurred.

Vedere anche:

mysqli_get_server_info().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("System status: %s\n", $mysqli->stat());

$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("System status: %s\n", mysqli_stat($link));

mysqli_close($link);
?>

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

mysqli_stmt_affected_rows

(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 statement

Description

Procedural style :

int mysqli_stmt_affected_rows ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int affected_rows

}

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.

Valori restituiti

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.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    $stmt->bind_param("s", $code);
    
    /* execute statement */
    $stmt->execute();

    printf("rows inserted: %d\n", $stmt->affected_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = mysqli_prepare($link, $query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    mysqli_stmt_bind_param($stmt, "s", $code);
    
    /* execute statement */
    mysqli_stmt_execute($stmt);

    printf("rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

rows inserted: 17

mysqli_stmt_bind_param

(PHP 5)

mysqli_stmt_bind_param

(no version information, might be only in CVS)

stmt->bind_param -- Binds variables to a prepared statement as parameters

Description

Procedural style:

bool mysqli_stmt_bind_param ( mysqli_stmt stmt, string types, mixed &var1 [, mixed &...] )

Object oriented style (method):

class mysqli_stmt {

bool bind_param ( string types, mixed &var1 [, mixed &...] )

}

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

CharacterDescription
icorresponding variable has type integer
dcorresponding variable has type double
scorresponding variable has type string
bcorresponding 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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqi_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

1 Row inserted.
1 Row deleted.

mysqli_stmt_bind_result

(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 storage

Description

Procedural style:

bool mysqli_stmt_bind_result ( mysqli_stmt stmt, mixed &var1 [, mixed &...] )

Object oriented style (method):

class mysqli_stmt {

bool bind_result ( mixed &var1 [, mixed &...] )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    mysqli_stmt_execute($stmt);

    /* bind variables to prepared statement */
    mysqli_stmt_bind_result($stmt, $col1, $col2);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

mysqli_stmt_close

(PHP 5)

mysqli_stmt_close

(no version information, might be only in CVS)

mysqli_stmt->close -- Closes a prepared statement

Description

Procedural style:

bool mysqli_stmt_close ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool close ( void )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

mysqli_prepare().

mysqli_stmt_data_seek

(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 set

Description

Procedural style:

void mysqli_stmt_data_seek ( mysqli_stmt statement, int offset )

Object oriented style (method):

class mysqli_stmt {

void data_seek ( int offset )

}

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).

Valori restituiti

Returns NULL on success or FALSE on failure.

Vedere anche:

mysqli_prepare().

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* store result */
    $stmt->store_result();

    /* seek to row no. 400 */
    $stmt->data_seek(399);

    /* fetch values */
    $stmt->fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* store result */
    mysqli_stmt_store_result($stmt);

    /* seek to row no. 400 */
    mysqli_stmt_data_seek($stmt, 399);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

City: Benin City  Countrycode: NGA

mysqli_stmt_errno

(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 call

Description

Procedural style :

int mysqli_stmt_errno ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int errno

}

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.

Valori restituiti

An error code value. Zero means no error occurred.

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %d.\n", $stmt->errno);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %d.\n", mysqli_stmt_errno($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error: 1146.

mysqli_stmt_error

(PHP 5)

mysqli_stmt_error

(no version information, might be only in CVS)

mysqli_stmt->error -- Returns a string description for last statement error

Description

Procedural style:

string mysqli_stmt_error ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

string error

}

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.

Valori restituiti

A string that describes the error. An empty string if no error occurred.

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->error);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_error($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error: Table 'world.myCountry' doesn't exist.

mysqli_stmt_execute

(PHP 5)

mysqli_stmt_execute

(no version information, might be only in CVS)

stmt->execute -- Executes a prepared Query

Description

Procedural style:

bool mysqli_stmt_execute ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool execute ( void )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
   
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
   
$mysqli->query("CREATE TABLE myCity LIKE City");
 
/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
    
/* Execute the statement */
$stmt->execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
    
/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result->close();
}

/* remove table */
$mysqli->query("DROP TABLE myCity");

/* close connection */    
$mysqli->close(); 
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
   
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
   
mysqli_query($link, "CREATE TABLE myCity LIKE City");
 
/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $query);

mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
    
/* Execute the statement */
mysqli_stmt_execute($stmt);

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
    
/* Execute the statement */
mysqli_stmt_execute($stmt);

/* close statement */
mysqli_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_row($result)) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    mysqli_free_result($result);
}

/* remove table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */    
mysqli_close($link); 
?>

Il precedente esempio visualizzerà:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

mysqli_stmt_fetch

(PHP 5)

mysqli_stmt_fetch

(no version information, might be only in CVS)

stmt->fetch --  Fetch results from a prepared statement into the bound variables

Description

Procedural style:

bool mysqli_stmt_fetch ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool fetch ( void )

}

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().

Valori restituiti

Tabella 1. Valori restituiti

ValueDescription
TRUESuccess. Data has been fetched
FALSEError occured
NULLNo more rows/data exists or data truncation occurred

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
 
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = mysqli_prepare($link, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

mysqli_stmt_free_result

(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 handle

Description

Procedural style:

void mysqli_stmt_free_result ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

void free_result ( void )

}

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().

Valori restituiti

This function doesn't return any value.

mysqli_stmt_init

(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_prepare

Description

Procedural style :

mysqli_stmt mysqli_stmt_init ( mysqli link )

Object oriented style (property):

class mysqli {

mysqli_stmt stmt_init ( void )

}

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.

Valori restituiti

Returns an object.

Vedere anche:

mysqli_stmt_prepare().

mysqli_stmt_num_rows

(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 set

Description

Procedural style :

int mysqli_stmt_num_rows ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int num_rows

}

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.

Valori restituiti

An integer representing the number of rows in result set.

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Number of rows: 20.

mysqli_stmt_param_count

(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 statement

Description

Procedural style:

int mysqli_stmt_param_count ( mysqli_stmt stmt )

Object oriented style (property):

class mysqli_stmt {

int param_count

}

mysqli_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Valori restituiti

returns an integer representing the number of parameters.

Vedere anche:

mysqli_prepare().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = $stmt->param_count;
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = mysqli_stmt_param_count($stmt);
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Statement has 2 markers.

mysqli_stmt_prepare

(PHP 5)

mysqli_stmt_prepare

(no version information, might be only in CVS)

stmt->prepare --  Prepare a SQL statement for execution

Description

Procedure style:

bool mysqli_stmt_prepare ( mysqli_stmt stmt, string query )

Object oriented style (method)

class mysqli_stmt {

mixed prepare ( string query )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt =  $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
} 

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init();
if ($stmt = mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
} 

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Amersfoort is in district Utrecht

mysqli_stmt_reset

(PHP 5)

mysqli_stmt_reset

(no version information, might be only in CVS)

stmt->reset -- Resets a prepared statement

Description

Procedural style:

bool mysqli_stmt_reset ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool reset ( void )

}

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().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

mysqli_prepare().

mysqli_stmt_result_metadata

(PHP 5)

mysqli_stmt_result_metadata -- Returns result set metadata from a prepared statement

Description

Procedural style:

mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

mysqli_result result_metadata ( void )

}

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().

Valori restituiti

mysqli_stmt_result_metadata() returns a result object or FALSE if an error occured.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query("DROP TABLE IF EXISTS friends"); 
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))"); 
 
$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends"); 
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))"); 
 
mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

mysqli_stmt_send_long_data

(PHP 5)

mysqli_stmt_send_long_data

(no version information, might be only in CVS)

stmt->send_long_data -- Send data in blocks

Description

Procedural style:

bool mysqli_stmt_send_long_data ( mysqli_stmt stmt, int param_nr, string data )

Object oriented style (method)

class mysqli_stmt {

bool send_long_data ( int param_nr, string data )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_stmt_sqlstate

(PHP 5)

mysqli_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation

Description

string mysqli_stmt_sqlstate ( mysqli_stmt stmt )

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.

Valori restituiti

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->sqlstate);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");


$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error: 42S02.

mysqli_stmt_store_result

(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 statement

Description

Procedural style:

bool mysqli_stmt_store_result ( mysqli_stmt stmt )

Object oriented style (method):

class mysqli_stmt {

bool store_result ( void )

}

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Object oriented style

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* free result */
    $stmt->free_result();

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */ 
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* free result */
    mysqli_stmt_free_result($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Number of rows: 20.

mysqli_store_result

(PHP 5)

mysqli_store_result

(no version information, might be only in CVS)

mysqli->store_result -- Transfers a result set from the last query

Description

Procedural style:

mysqli_result mysqli_store_result ( mysqli link )

Object oriented style (method):

class mysqli {

mysqli_result store_result ( void )

}

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.

Valori restituiti

Returns a buffered result object or FALSE if an error occurred.

mysqli_thread_id

(PHP 5)

mysqli_thread_id

(no version information, might be only in CVS)

mysqli->thread_id -- Returns the thread ID for the current connection

Description

Procedural style:

int mysqli_thread_id ( mysqli link )

Object oriented style (property):

class mysqli {

int thread_id

}

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.

Valori restituiti

mysqli_thread_id() returns the Thread ID for the current connection.

Vedere anche:

mysqli_kill().

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Error: MySQL server has gone away

mysqli_thread_safe

(PHP 5)

mysqli_thread_safe -- Returns whether thread safety is given or not

Description

Procedural style:

bool mysqli_thread_safe ( void )

mysqli_thread_safe() indicates whether the client library is compiled as thread-safe.

Valori restituiti

TRUE if the client library is thread-safe, otherwise FALSE.

mysqli_use_result

(PHP 5)

mysqli_use_result

(no version information, might be only in CVS)

mysqli->use_result -- Initiate a result set retrieval

Description

Procedural style:

mysqli_result mysqli_use_result ( mysqli link )

Object oriented style (method):

class mysqli {

mysqli_result use_result ( void )

}

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.

Valori restituiti

Returns an unbuffered result object or FALSE if an error occurred.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->use_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->close();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_use_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

mysqli_warning_count

(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 link

Description

Procedural style:

int mysqli_warning_count ( mysqli link )

Object oriented style (property):

class mysqli {

int warning_count

}

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].

Valori restituiti

Number of warnings or zero if there are no warnings.

Esempi

Esempio 1. Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
    if ($result = $mysqli->query("SHOW WARNINGS")) {
        $row = $result->fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result->close();
    }
}

/* close connection */
$mysqli->close();
?>

Esempio 2. Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
    if ($result = mysqli_query($link, "SHOW WARNINGS")) {
        $row = mysqli_fetch_row($result);
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        mysqli_free_result($result);
    }
}

/* close connection */
mysqli_close($link);
?>

Il precedente esempio visualizzerà:

Warning (1264): Data truncated for column 'Name' at row 1

LXXXIX. Ncurses Terminal Screen Control Functions

Introduzione

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


Requisiti

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.


Installazione

To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Ncurses configuration options

NameDefaultChangeableChangelog
ncurses.value"42"PHP_INI_ALL 
ncurses.string"foobar"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.


Error codes

On error ncurses functions return NCURSES_ERR.


Colors

Tabella 2. ncurses color constants

constantmeaning
NCURSES_COLOR_BLACKno color (black)
NCURSES_COLOR_WHITEwhite
NCURSES_COLOR_REDred - supported when terminal is in color mode
NCURSES_COLOR_GREENgreen - supported when terminal is in color mode
NCURSES_COLOR_YELLOWyellow - supported when terminal is in color mode
NCURSES_COLOR_BLUEblue - supported when terminal is in color mode
NCURSES_COLOR_CYANcyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTAmagenta - supported when terminal is in color mode

Keys

Tabella 3. ncurses key constants

constantmeaning
NCURSES_KEY_F0 - NCURSES_KEY_F64function keys F1 - F64
NCURSES_KEY_DOWNdown arrow
NCURSES_KEY_UPup arrow
NCURSES_KEY_LEFTleft arrow
NCURSES_KEY_RIGHTright arrow
NCURSES_KEY_HOMEhome key (upward+left arrow)
NCURSES_KEY_BACKSPACEbackspace
NCURSES_KEY_DLdelete line
NCURSES_KEY_ILinsert line
NCURSES_KEY_DCdelete character
NCURSES_KEY_ICinsert char or enter insert mode
NCURSES_KEY_EICexit insert char mode
NCURSES_KEY_CLEARclear screen
NCURSES_KEY_EOSclear to end of screen
NCURSES_KEY_EOLclear to end of line
NCURSES_KEY_SFscroll one line forward
NCURSES_KEY_SRscroll one line backward
NCURSES_KEY_NPAGEnext page
NCURSES_KEY_PPAGEprevious page
NCURSES_KEY_STABset tab
NCURSES_KEY_CTABclear tab
NCURSES_KEY_CATABclear all tabs
NCURSES_KEY_SRESETsoft (partial) reset
NCURSES_KEY_RESETreset or hard reset
NCURSES_KEY_PRINTprint
NCURSES_KEY_LLlower left
NCURSES_KEY_A1upper left of keypad
NCURSES_KEY_A3upper right of keypad
NCURSES_KEY_B2center of keypad
NCURSES_KEY_C1lower left of keypad
NCURSES_KEY_C3lower right of keypad
NCURSES_KEY_BTABback tab
NCURSES_KEY_BEGbeginning
NCURSES_KEY_CANCELcancel
NCURSES_KEY_CLOSEclose
NCURSES_KEY_COMMANDcmd (command)
NCURSES_KEY_COPYcopy
NCURSES_KEY_CREATEcreate
NCURSES_KEY_ENDend
NCURSES_KEY_EXITexit
NCURSES_KEY_FINDfind
NCURSES_KEY_HELPhelp
NCURSES_KEY_MARKmark
NCURSES_KEY_MESSAGEmessage
NCURSES_KEY_MOVEmove
NCURSES_KEY_NEXTnext
NCURSES_KEY_OPENopen
NCURSES_KEY_OPTIONSoptions
NCURSES_KEY_PREVIOUSprevious
NCURSES_KEY_REDOredo
NCURSES_KEY_REFERENCEref (reference)
NCURSES_KEY_REFRESHrefresh
NCURSES_KEY_REPLACEreplace
NCURSES_KEY_RESTARTrestart
NCURSES_KEY_RESUMEresume
NCURSES_KEY_SAVEsave
NCURSES_KEY_SBEGshiftet beg (beginning)
NCURSES_KEY_SCANCELshifted cancel
NCURSES_KEY_SCOMMANDshifted command
NCURSES_KEY_SCOPYshifted copy
NCURSES_KEY_SCREATEshifted create
NCURSES_KEY_SDCshifted delete char
NCURSES_KEY_SDLshifted delete line
NCURSES_KEY_SELECTselect
NCURSES_KEY_SENDshifted end
NCURSES_KEY_SEOLshifted end of line
NCURSES_KEY_SEXITshifted exit
NCURSES_KEY_SFINDshifted find
NCURSES_KEY_SHELPshifted help
NCURSES_KEY_SHOMEshifted home
NCURSES_KEY_SICshifted input
NCURSES_KEY_SLEFTshifted left arrow
NCURSES_KEY_SMESSAGEshifted message
NCURSES_KEY_SMOVEshifted move
NCURSES_KEY_SNEXTshifted next
NCURSES_KEY_SOPTIONSshifted options
NCURSES_KEY_SPREVIOUSshifted previous
NCURSES_KEY_SPRINTshifted print
NCURSES_KEY_SREDOshifted redo
NCURSES_KEY_SREPLACEshifted replace
NCURSES_KEY_SRIGHTshifted right arrow
NCURSES_KEY_SRSUMEshifted resume
NCURSES_KEY_SSAVEshifted save
NCURSES_KEY_SSUSPENDshifted suspend
NCURSES_KEY_UNDOundo
NCURSES_KEY_MOUSEmouse event has occurred
NCURSES_KEY_MAXmaximum key value

Mouse

Tabella 4. mouse constants

Constantmeaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASEDbutton (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSEDbutton (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKEDbutton (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKEDbutton (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKEDbutton (1-4) triple clicked
NCURSES_BUTTON_CTRLctrl pressed during click
NCURSES_BUTTON_SHIFTshift pressed during click
NCURSES_BUTTON_ALTalt pressed during click
NCURSES_ALL_MOUSE_EVENTSreport all mouse events
NCURSES_REPORT_MOUSE_POSITIONreport mouse position
Sommario
ncurses_addch -- Add character at current position and advance cursor
ncurses_addchnstr -- Add attributed string with specified length at current position
ncurses_addchstr -- Add attributed string at current position
ncurses_addnstr -- Add string with specified length at current position
ncurses_addstr -- Output text at current position
ncurses_assume_default_colors -- Define default colors for color 0
ncurses_attroff -- Turn off the given attributes
ncurses_attron -- Turn on the given attributes
ncurses_attrset -- Set given attributes
ncurses_baudrate -- Returns baudrate of terminal
ncurses_beep -- Let the terminal beep
ncurses_bkgd -- Set background property for terminal screen
ncurses_bkgdset -- Control screen background
ncurses_border -- Draw a border around the screen using attributed characters
ncurses_bottom_panel --  Moves a visible panel to the bottom of the stack
ncurses_can_change_color -- Check if we can change terminals colors
ncurses_cbreak -- Switch of input buffering
ncurses_clear -- Clear screen
ncurses_clrtobot -- Clear screen from current position to bottom
ncurses_clrtoeol -- Clear screen from current position to end of line
ncurses_color_content --  Gets the RGB value for color
ncurses_color_set -- Set fore- and background color
ncurses_curs_set -- Set cursor state
ncurses_def_prog_mode -- Saves terminals (program) mode
ncurses_def_shell_mode -- Saves terminals (shell) mode
ncurses_define_key -- Define a keycode
ncurses_del_panel --  Remove panel from the stack and delete it (but not the associated window)
ncurses_delay_output -- Delay output on terminal using padding characters
ncurses_delch -- Delete character at current position, move rest of line left
ncurses_deleteln -- Delete line at current position, move rest of screen up
ncurses_delwin -- Delete a ncurses window
ncurses_doupdate -- Write all prepared refreshes to terminal
ncurses_echo -- Activate keyboard input echo
ncurses_echochar -- Single character output including refresh
ncurses_end -- Stop using ncurses, clean up the screen
ncurses_erase -- Erase terminal screen
ncurses_erasechar -- Returns current erase character
ncurses_filter -- Set LINES for iniscr() and newterm() to 1
ncurses_flash -- Flash terminal screen (visual bell)
ncurses_flushinp -- Flush keyboard input buffer
ncurses_getch -- Read a character from keyboard
ncurses_getmaxyx -- Returns the size of a window
ncurses_getmouse -- Reads mouse event
ncurses_getyx --  Returns the current cursor position for a window
ncurses_halfdelay -- Put terminal into halfdelay mode
ncurses_has_colors -- Check if terminal has colors
ncurses_has_ic -- Check for insert- and delete-capabilities
ncurses_has_il -- Check for line insert- and delete-capabilities
ncurses_has_key -- Check for presence of a function key on terminal keyboard
ncurses_hide_panel --  Remove panel from the stack, making it invisible
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long
ncurses_inch -- Get character and attribute at current position
ncurses_init_color -- Set new RGB value for color
ncurses_init_pair -- Allocate a color pair
ncurses_init -- Initialize ncurses
ncurses_insch -- Insert character moving rest of line including character at current position
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)
ncurses_insertln -- Insert a line, move rest of screen down
ncurses_insstr -- Insert string at current position, moving rest of line right
ncurses_instr -- Reads string from terminal screen
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed
ncurses_keyok -- Enable or disable a keycode
ncurses_keypad --  Turns keypad on or off
ncurses_killchar -- Returns current line kill character
ncurses_longname -- Returns terminals description
ncurses_meta --  Enables/Disable 8-bit meta key information
ncurses_mouse_trafo --  Transforms coordinates
ncurses_mouseinterval -- Set timeout for mouse button clicks
ncurses_mousemask -- Sets mouse options
ncurses_move_panel --  Moves a panel so that its upper-left corner is at [startx, starty]
ncurses_move -- Move output position
ncurses_mvaddch -- Move current position and add character
ncurses_mvaddchnstr -- Move position and add attributed string with specified length
ncurses_mvaddchstr -- Move position and add attributed string
ncurses_mvaddnstr -- Move position and add string with specified length
ncurses_mvaddstr -- Move position and add string
ncurses_mvcur -- Move cursor immediately
ncurses_mvdelch -- Move position and delete character, shift rest of line left
ncurses_mvgetch -- Move position and get character at new position
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long
ncurses_mvinch -- Move position and get attributed character at new position
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long
ncurses_mvwaddstr -- Add string at new position in window
ncurses_napms -- Sleep
ncurses_new_panel --  Create a new panel and associate it with window
ncurses_newpad --  Creates a new pad (window)
ncurses_newwin -- Create a new window
ncurses_nl -- Translate newline and carriage return / line feed
ncurses_nocbreak -- Switch terminal to cooked mode
ncurses_noecho -- Switch off keyboard input echo
ncurses_nonl -- Do not translate newline and carriage return / line feed
ncurses_noqiflush -- Do not flush on signal characters
ncurses_noraw -- Switch terminal out of raw mode
ncurses_pair_content --  Gets the RGB value for color
ncurses_panel_above --  Returns the panel above panel
ncurses_panel_below --  Returns the panel below panel
ncurses_panel_window --  Returns the window associated with panel
ncurses_pnoutrefresh --  Copies a region from a pad into the virtual screen
ncurses_prefresh --  Copies a region from a pad into the virtual screen
ncurses_putp -- Apply padding information to the string and output it
ncurses_qiflush -- Flush on signal characters
ncurses_raw -- Switch terminal into raw mode
ncurses_refresh -- Refresh screen
ncurses_replace_panel --  Replaces the window associated with panel
ncurses_reset_prog_mode --  Resets the prog mode saved by def_prog_mode
ncurses_reset_shell_mode --  Resets the shell mode saved by def_shell_mode
ncurses_resetty -- Restores saved terminal state
ncurses_savetty -- Saves terminal state
ncurses_scr_dump -- Dump screen content to file
ncurses_scr_init -- Initialize screen from file dump
ncurses_scr_restore -- Restore screen from file dump
ncurses_scr_set -- Inherit screen from file dump
ncurses_scrl -- Scroll window content up or down without changing current position
ncurses_show_panel --  Places an invisible panel on top of the stack, making it visible
ncurses_slk_attr -- Returns current soft label key attribute
ncurses_slk_attroff -- Turn off the given attributes for soft function-key labels
ncurses_slk_attron -- Turn on the given attributes for soft function-key labels
ncurses_slk_attrset -- Set given attributes for soft function-key labels
ncurses_slk_clear -- Clears soft labels from screen
ncurses_slk_color -- Sets color for soft label keys
ncurses_slk_init -- Initializes soft label key functions
ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen
ncurses_slk_refresh -- Copies soft label keys to screen
ncurses_slk_restore -- Restores soft label keys
ncurses_slk_set --  Sets function key labels
ncurses_slk_touch -- Forces output when ncurses_slk_noutrefresh is performed
ncurses_standend -- Stop using 'standout' attribute
ncurses_standout -- Start using 'standout' attribute
ncurses_start_color -- Start using colors
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal
ncurses_termname -- Returns terminals (short)-name
ncurses_timeout -- Set timeout for special key sequences
ncurses_top_panel --  Moves a visible panel to the top of the stack
ncurses_typeahead -- Specify different filedescriptor for typeahead checking
ncurses_ungetch -- Put a character back into the input stream
ncurses_ungetmouse -- Pushes mouse event to queue
ncurses_update_panels --  Refreshes the virtual screen to reflect the relations between panels in the stack
ncurses_use_default_colors -- Assign terminal default colors to color id -1
ncurses_use_env -- Control use of environment information about terminal size
ncurses_use_extended_names -- Control use of extended names in terminfo descriptions
ncurses_vidattr -- Display the string on the terminal in the video attribute mode
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long
ncurses_waddch --  Adds character at current position in a window and advance cursor
ncurses_waddstr --  Outputs text at current postion in window
ncurses_wattroff --  Turns off attributes for a window
ncurses_wattron --  Turns on attributes for a window
ncurses_wattrset --  Set the attributes for a window
ncurses_wborder -- Draws a border around the window using attributed characters
ncurses_wclear --  Clears window
ncurses_wcolor_set --  Sets windows color pairings
ncurses_werase --  Erase window contents
ncurses_wgetch --  Reads a character from keyboard (window)
ncurses_whline --  Draws a horizontal line in a window at current position using an attributed character and max. n characters long
ncurses_wmouse_trafo --  Transforms window/stdscr coordinates
ncurses_wmove --  Moves windows output position
ncurses_wnoutrefresh --  Copies window to virtual screen
ncurses_wrefresh -- Refresh window on terminal screen
ncurses_wstandend --  End standout mode for a window
ncurses_wstandout --  Enter standout mode for a window
ncurses_wvline --  Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_addch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_addch -- Add character at current position and advance cursor

Description

int ncurses_addch ( int ch )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addchnstr -- Add attributed string with specified length at current position

Description

int ncurses_addchnstr ( string s, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addchstr -- Add attributed string at current position

Description

int ncurses_addchstr ( string s )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addnstr -- Add string with specified length at current position

Description

int ncurses_addnstr ( string s, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_addstr -- Output text at current position

Description

int ncurses_addstr ( string text )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5)

ncurses_assume_default_colors -- Define default colors for color 0

Description

int ncurses_assume_default_colors ( int fg, int bg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_attroff

(PHP 4 >= 4.1.0, PHP 5)

ncurses_attroff -- Turn off the given attributes

Description

int ncurses_attroff ( int attributes )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_attron

(PHP 4 >= 4.1.0, PHP 5)

ncurses_attron -- Turn on the given attributes

Description

int ncurses_attron ( int attributes )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_attrset

(PHP 4 >= 4.1.0, PHP 5)

ncurses_attrset -- Set given attributes

Description

int ncurses_attrset ( int attributes )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_baudrate

(PHP 4 >= 4.1.0, PHP 5)

ncurses_baudrate -- Returns baudrate of terminal

Description

int ncurses_baudrate ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_beep

(PHP 4 >= 4.1.0, PHP 5)

ncurses_beep -- Let the terminal beep

Description

int ncurses_beep ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_bkgd

(PHP 4 >= 4.1.0, PHP 5)

ncurses_bkgd -- Set background property for terminal screen

Description

int ncurses_bkgd ( int attrchar )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_bkgdset

(PHP 4 >= 4.1.0, PHP 5)

ncurses_bkgdset -- Control screen background

Description

void ncurses_bkgdset ( int attrchar )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_border

(PHP 4 >= 4.2.0, PHP 5)

ncurses_border -- Draw a border around the screen using attributed characters

Description

int ncurses_border ( int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_bottom_panel --  Moves a visible panel to the bottom of the stack

Description

int ncurses_bottom_panel ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_can_change_color

(PHP 4 >= 4.1.0, PHP 5)

ncurses_can_change_color -- Check if we can change terminals colors

Description

bool ncurses_can_change_color ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_cbreak

(PHP 4 >= 4.1.0, PHP 5)

ncurses_cbreak -- Switch of input buffering

Description

bool ncurses_cbreak ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_clear

(PHP 4 >= 4.1.0, PHP 5)

ncurses_clear -- Clear screen

Description

bool ncurses_clear ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

ncurses_clrtobot

(PHP 4 >= 4.1.0, PHP 5)

ncurses_clrtobot -- Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_clrtoeol

(PHP 4 >= 4.1.0, PHP 5)

ncurses_clrtoeol -- Clear screen from current position to end of line

Description

bool ncurses_clrtoeol ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5)

ncurses_color_content --  Gets the RGB value for color

Description

int ncurses_color_content ( int color, int &r, int &g, int &b )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_color_set

(PHP 4 >= 4.1.0, PHP 5)

ncurses_color_set -- Set fore- and background color

Description

int ncurses_color_set ( int pair )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_curs_set

(PHP 4 >= 4.1.0, PHP 5)

ncurses_curs_set -- Set cursor state

Description

int ncurses_curs_set ( int visibility )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_def_prog_mode

(PHP 4 >= 4.1.0, PHP 5)

ncurses_def_prog_mode -- Saves terminals (program) mode

Description

bool ncurses_def_prog_mode ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_def_shell_mode

(PHP 4 >= 4.1.0, PHP 5)

ncurses_def_shell_mode -- Saves terminals (shell) mode

Description

bool ncurses_def_shell_mode ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5)

ncurses_define_key -- Define a keycode

Description

int ncurses_define_key ( string definition, int keycode )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_del_panel --  Remove panel from the stack and delete it (but not the associated window)

Description

bool ncurses_del_panel ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_delay_output

(PHP 4 >= 4.1.0, PHP 5)

ncurses_delay_output -- Delay output on terminal using padding characters

Description

int ncurses_delay_output ( int milliseconds )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_delch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_delch -- Delete character at current position, move rest of line left

Description

bool ncurses_delch ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_deleteln

(PHP 4 >= 4.1.0, PHP 5)

ncurses_deleteln -- Delete line at current position, move rest of screen up

Description

bool ncurses_deleteln ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_delwin

(PHP 4 >= 4.1.0, PHP 5)

ncurses_delwin -- Delete a ncurses window

Description

bool ncurses_delwin ( resource window )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_doupdate

(PHP 4 >= 4.1.0, PHP 5)

ncurses_doupdate -- Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_echo

(PHP 4 >= 4.1.0, PHP 5)

ncurses_echo -- Activate keyboard input echo

Description

bool ncurses_echo ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

ncurses_echochar

(PHP 4 >= 4.1.0, PHP 5)

ncurses_echochar -- Single character output including refresh

Description

int ncurses_echochar ( int character )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_end

(PHP 4 >= 4.1.0, PHP 5)

ncurses_end -- Stop using ncurses, clean up the screen

Description

int ncurses_end ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_erase

(PHP 4 >= 4.1.0, PHP 5)

ncurses_erase -- Erase terminal screen

Description

bool ncurses_erase ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_erasechar

(PHP 4 >= 4.1.0, PHP 5)

ncurses_erasechar -- Returns current erase character

Description

string ncurses_erasechar ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_filter

(PHP 4 >= 4.1.0, PHP 5)

ncurses_filter -- Set LINES for iniscr() and newterm() to 1

Description

void ncurses_filter ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_flash

(PHP 4 >= 4.1.0, PHP 5)

ncurses_flash -- Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_flushinp

(PHP 4 >= 4.1.0, PHP 5)

ncurses_flushinp -- Flush keyboard input buffer

Description

bool ncurses_flushinp ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_getch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_getch -- Read a character from keyboard

Description

int ncurses_getch ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5)

ncurses_getmaxyx -- Returns the size of a window

Description

void ncurses_getmaxyx ( resource window, int &y, int &x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5)

ncurses_getmouse -- Reads mouse event

Description

bool ncurses_getmouse ( array &mevent )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

Esempio 1. ncurses_getmouse() example

<?php
switch (ncurses_getch()){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse(&$mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    /* .... */
}
?>

See also ncurses_ungetmouse()

ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5)

ncurses_getyx --  Returns the current cursor position for a window

Description

void ncurses_getyx ( resource window, int &y, int &x )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_halfdelay

(PHP 4 >= 4.1.0, PHP 5)

ncurses_halfdelay -- Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int tenth )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_has_colors

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_colors -- Check if terminal has colors

Description

bool ncurses_has_colors ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_has_ic

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_ic -- Check for insert- and delete-capabilities

Description

bool ncurses_has_ic ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_has_il

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_il -- Check for line insert- and delete-capabilities

Description

bool ncurses_has_il ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_has_key

(PHP 4 >= 4.1.0, PHP 5)

ncurses_has_key -- Check for presence of a function key on terminal keyboard

Description

int ncurses_has_key ( int keycode )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_hide_panel --  Remove panel from the stack, making it invisible

Description

int ncurses_hide_panel ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_hline

(PHP 4 >= 4.2.0, PHP 5)

ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int charattr, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_inch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_inch -- Get character and attribute at current position

Description

string ncurses_inch ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5)

ncurses_init_color -- Set new RGB value for color

Description

int ncurses_init_color ( int color, int r, int g, int b )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_init_pair

(PHP 4 >= 4.1.0, PHP 5)

ncurses_init_pair -- Allocate a color pair

Description

int ncurses_init_pair ( int pair, int fg, int bg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_init

(PHP 4 >= 4.1.0, PHP 5)

ncurses_init -- Initialize ncurses

Description

void ncurses_init ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_insch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_insch -- Insert character moving rest of line including character at current position

Description

int ncurses_insch ( int character )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_insdelln

(PHP 4 >= 4.1.0, PHP 5)

ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

int ncurses_insdelln ( int count )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_insertln

(PHP 4 >= 4.1.0, PHP 5)

ncurses_insertln -- Insert a line, move rest of screen down

Description

bool ncurses_insertln ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_insstr -- Insert string at current position, moving rest of line right

Description

int ncurses_insstr ( string text )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_instr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_instr -- Reads string from terminal screen

Description

int ncurses_instr ( string &buffer )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_isendwin

(PHP 4 >= 4.1.0, PHP 5)

ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed

Description

bool ncurses_isendwin ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5)

ncurses_keyok -- Enable or disable a keycode

Description

int ncurses_keyok ( int keycode, bool enable )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5)

ncurses_keypad --  Turns keypad on or off

Description

int ncurses_keypad ( resource window, bool bf )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_killchar

(PHP 4 >= 4.1.0, PHP 5)

ncurses_killchar -- Returns current line kill character

Description

string ncurses_killchar ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_longname

(PHP 4 >= 4.2.0, PHP 5)

ncurses_longname -- Returns terminals description

Description

string ncurses_longname ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_meta

(PHP 4 >= 4.3.0, PHP 5)

ncurses_meta --  Enables/Disable 8-bit meta key information

Description

int ncurses_meta ( resource window, bool 8bit )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mouse_trafo --  Transforms coordinates

Description

bool ncurses_mouse_trafo ( int &y, int &x, bool toscreen )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_mouseinterval

(PHP 4 >= 4.1.0, PHP 5)

ncurses_mouseinterval -- Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int milliseconds )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mousemask -- Sets mouse options

Description

int ncurses_mousemask ( int newmask, int &oldmask )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

Esempio 1. ncurses_mousemask() example

<?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, &$oldmask);
if ($mask & $newmask){
  printf ("All specified mouse options will be supported\n");
}
?>

See also ncurses_getmouse(), ncurses_ungetmouse() and ncurese_getch().

ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_move_panel --  Moves a panel so that its upper-left corner is at [startx, starty]

Description

int ncurses_move_panel ( resource panel, int startx, int starty )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_move

(PHP 4 >= 4.1.0, PHP 5)

ncurses_move -- Move output position

Description

int ncurses_move ( int y, int x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddch -- Move current position and add character

Description

int ncurses_mvaddch ( int y, int x, int c )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddchnstr -- Move position and add attributed string with specified length

Description

int ncurses_mvaddchnstr ( int y, int x, string s, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddchstr -- Move position and add attributed string

Description

int ncurses_mvaddchstr ( int y, int x, string s )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddnstr -- Move position and add string with specified length

Description

int ncurses_mvaddnstr ( int y, int x, string s, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvaddstr -- Move position and add string

Description

int ncurses_mvaddstr ( int y, int x, string s )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvcur -- Move cursor immediately

Description

int ncurses_mvcur ( int old_y, int old_x, int new_y, int new_x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvdelch -- Move position and delete character, shift rest of line left

Description

int ncurses_mvdelch ( int y, int x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvgetch -- Move position and get character at new position

Description

int ncurses_mvgetch ( int y, int x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvhline

(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 long

Description

int ncurses_mvhline ( int y, int x, int attrchar, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvinch -- Move position and get attributed character at new position

Description

int ncurses_mvinch ( int y, int x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvvline

(no version information, might be only in CVS)

ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long

Description

int ncurses_mvvline ( int y, int x, int attrchar, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_mvwaddstr -- Add string at new position in window

Description

int ncurses_mvwaddstr ( resource window, int y, int x, string text )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_napms

(PHP 4 >= 4.1.0, PHP 5)

ncurses_napms -- Sleep

Description

int ncurses_napms ( int milliseconds )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_new_panel --  Create a new panel and associate it with window

Description

resource ncurses_new_panel ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5)

ncurses_newpad --  Creates a new pad (window)

Description

resource ncurses_newpad ( int rows, int cols )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_newwin

(PHP 4 >= 4.1.0, PHP 5)

ncurses_newwin -- Create a new window

Description

resource ncurses_newwin ( int rows, int cols, int y, int x )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_nl

(PHP 4 >= 4.1.0, PHP 5)

ncurses_nl -- Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_nocbreak

(PHP 4 >= 4.1.0, PHP 5)

ncurses_nocbreak -- Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_noecho

(PHP 4 >= 4.1.0, PHP 5)

ncurses_noecho -- Switch off keyboard input echo

Description

bool ncurses_noecho ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_nonl

(PHP 4 >= 4.1.0, PHP 5)

ncurses_nonl -- Do not translate newline and carriage return / line feed

Description

bool ncurses_nonl ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_noqiflush

(PHP 4 >= 4.1.0, PHP 5)

ncurses_noqiflush -- Do not flush on signal characters

Description

void ncurses_noqiflush ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_noraw

(PHP 4 >= 4.1.0, PHP 5)

ncurses_noraw -- Switch terminal out of raw mode

Description

bool ncurses_noraw ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5)

ncurses_pair_content --  Gets the RGB value for color

Description

int ncurses_pair_content ( int pair, int &f, int &b )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_above --  Returns the panel above panel

Description

resource ncurses_panel_above ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

If panel is null, returns the bottom panel in the stack.

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_below --  Returns the panel below panel

Description

resource ncurses_panel_below ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

If panel is null, returns the top panel in the stack.

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_window --  Returns the window associated with panel

Description

resource ncurses_panel_window ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5)

ncurses_pnoutrefresh --  Copies a region from a pad into the virtual screen

Description

int ncurses_pnoutrefresh ( resource pad, int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5)

ncurses_prefresh --  Copies a region from a pad into the virtual screen

Description

int ncurses_prefresh ( resource pad, int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_putp

(PHP 4 >= 4.2.0, PHP 5)

ncurses_putp -- Apply padding information to the string and output it

Description

int ncurses_putp ( string text )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_qiflush

(PHP 4 >= 4.1.0, PHP 5)

ncurses_qiflush -- Flush on signal characters

Description

void ncurses_qiflush ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_raw

(PHP 4 >= 4.1.0, PHP 5)

ncurses_raw -- Switch terminal into raw mode

Description

bool ncurses_raw ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_refresh

(PHP 4 >= 4.1.0, PHP 5)

ncurses_refresh -- Refresh screen

Description

int ncurses_refresh ( int ch )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_replace_panel --  Replaces the window associated with panel

Description

int ncurses_replace_panel ( resource panel, resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5)

ncurses_reset_prog_mode --  Resets the prog mode saved by def_prog_mode

Description

int ncurses_reset_prog_mode ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5)

ncurses_reset_shell_mode --  Resets the shell mode saved by def_shell_mode

Description

int ncurses_reset_shell_mode ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_resetty

(PHP 4 >= 4.1.0, PHP 5)

ncurses_resetty -- Restores saved terminal state

Description

bool ncurses_resetty ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_savetty

(PHP 4 >= 4.1.0, PHP 5)

ncurses_savetty -- Saves terminal state

Description

bool ncurses_savetty ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_dump -- Dump screen content to file

Description

int ncurses_scr_dump ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_init -- Initialize screen from file dump

Description

int ncurses_scr_init ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_restore -- Restore screen from file dump

Description

int ncurses_scr_restore ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5)

ncurses_scr_set -- Inherit screen from file dump

Description

int ncurses_scr_set ( string filename )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_scrl

(PHP 4 >= 4.1.0, PHP 5)

ncurses_scrl -- Scroll window content up or down without changing current position

Description

int ncurses_scrl ( int count )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_show_panel --  Places an invisible panel on top of the stack, making it visible

Description

int ncurses_show_panel ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_slk_attr

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attr -- Returns current soft label key attribute

Description

bool ncurses_slk_attr ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_attroff

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attroff -- Turn off the given attributes for soft function-key labels

Description

int ncurses_slk_attroff ( int intarg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_attron

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attron -- Turn on the given attributes for soft function-key labels

Description

int ncurses_slk_attron ( int intarg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_attrset

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_attrset -- Set given attributes for soft function-key labels

Description

int ncurses_slk_attrset ( int intarg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_clear

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_clear -- Clears soft labels from screen

Description

bool ncurses_slk_clear ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_color

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_color -- Sets color for soft label keys

Description

int ncurses_slk_color ( int intarg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_init

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_init -- Initializes soft label key functions

Description

bool ncurses_slk_init ( int format )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_noutrefresh

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen

Description

bool ncurses_slk_noutrefresh ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_refresh

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_refresh -- Copies soft label keys to screen

Description

bool ncurses_slk_refresh ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_restore

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_restore -- Restores soft label keys

Description

bool ncurses_slk_restore ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5)

ncurses_slk_set --  Sets function key labels

Description

bool ncurses_slk_set ( int labelnr, string label, int format )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_slk_touch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_slk_touch -- Forces output when ncurses_slk_noutrefresh is performed

Description

bool ncurses_slk_touch ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_standend

(PHP 4 >= 4.1.0, PHP 5)

ncurses_standend -- Stop using 'standout' attribute

Description

int ncurses_standend ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_standout

(PHP 4 >= 4.1.0, PHP 5)

ncurses_standout -- Start using 'standout' attribute

Description

int ncurses_standout ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_start_color

(PHP 4 >= 4.1.0, PHP 5)

ncurses_start_color -- Start using colors

Description

int ncurses_start_color ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_termattrs

(PHP 4 >= 4.1.0, PHP 5)

ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal

Description

bool ncurses_termattrs ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_termname

(PHP 4 >= 4.2.0, PHP 5)

ncurses_termname -- Returns terminals (short)-name

Description

string ncurses_termname ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_timeout

(PHP 4 >= 4.1.0, PHP 5)

ncurses_timeout -- Set timeout for special key sequences

Description

void ncurses_timeout ( int millisec )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5)

ncurses_top_panel --  Moves a visible panel to the top of the stack

Description

int ncurses_top_panel ( resource panel )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_typeahead

(PHP 4 >= 4.1.0, PHP 5)

ncurses_typeahead -- Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int fd )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_ungetch

(PHP 4 >= 4.1.0, PHP 5)

ncurses_ungetch -- Put a character back into the input stream

Description

int ncurses_ungetch ( int keycode )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5)

ncurses_ungetmouse -- Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array mevent )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()

ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5)

ncurses_update_panels --  Refreshes the virtual screen to reflect the relations between panels in the stack

Description

void ncurses_update_panels ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_use_default_colors

(PHP 4 >= 4.1.0, PHP 5)

ncurses_use_default_colors -- Assign terminal default colors to color id -1

Description

bool ncurses_use_default_colors ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_use_env

(PHP 4 >= 4.1.0, PHP 5)

ncurses_use_env -- Control use of environment information about terminal size

Description

void ncurses_use_env ( bool flag )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_use_extended_names

(PHP 4 >= 4.1.0, PHP 5)

ncurses_use_extended_names -- Control use of extended names in terminfo descriptions

Description

int ncurses_use_extended_names ( bool flag )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_vidattr

(PHP 4 >= 4.1.0, PHP 5)

ncurses_vidattr -- Display the string on the terminal in the video attribute mode

Description

int ncurses_vidattr ( int intarg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_vline

(PHP 4 >= 4.2.0, PHP 5)

ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int charattr, int n )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5)

ncurses_waddch --  Adds character at current position in a window and advance cursor

Description

int ncurses_waddch ( resource window, int ch )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5)

ncurses_waddstr --  Outputs text at current postion in window

Description

int ncurses_waddstr ( resource window, string str [, int n] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wattroff --  Turns off attributes for a window

Description

int ncurses_wattroff ( resource window, int attrs )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wattron --  Turns on attributes for a window

Description

int ncurses_wattron ( resource window, int attrs )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wattrset --  Set the attributes for a window

Description

int ncurses_wattrset ( resource window, int attrs )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wborder -- Draws a border around the window using attributed characters

Description

int ncurses_wborder ( resource window, int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wclear --  Clears window

Description

int ncurses_wclear ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wcolor_set --  Sets windows color pairings

Description

int ncurses_wcolor_set ( resource window, int color_pair )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_werase

(PHP 4 >= 4.3.0, PHP 5)

ncurses_werase --  Erase window contents

Description

int ncurses_werase ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wgetch --  Reads a character from keyboard (window)

Description

int ncurses_wgetch ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_whline

(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

Description

int ncurses_whline ( resource window, int charattr, int n )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wmouse_trafo --  Transforms window/stdscr coordinates

Description

bool ncurses_wmouse_trafo ( resource window, int &y, int &x, bool toscreen )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wmove --  Moves windows output position

Description

int ncurses_wmove ( resource window, int y, int x )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wnoutrefresh --  Copies window to virtual screen

Description

int ncurses_wnoutrefresh ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5)

ncurses_wrefresh -- Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource window )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wstandend --  End standout mode for a window

Description

int ncurses_wstandend ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wstandout --  Enter standout mode for a window

Description

int ncurses_wstandout ( resource window )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5)

ncurses_wvline --  Draws a vertical line in a window at current position using an attributed character and max. n characters long

Description

int ncurses_wvline ( resource window, int charattr, int n )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

XC. Funzioni di rete


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione.

NomeDefaultModificabile
define_syslog_variables"0"PHP_INI_ALL
Per maggiori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

define_syslog_variables boolean

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().


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.

Tabella 2. Opzioni openlog()

CostanteDescrizione
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_PERRORScrive il messaggio di log anche nello standard error
LOG_PIDInclude anche il PID in ciascun messaggio

Tabella 3. Tools openlog()

CostanteDescrizione
LOG_AUTH Messaggio di sicurezza/autorizzazione (utilizzare LOG_AUTHPRIV nei sistemi in cui questa costante è definita)
LOG_AUTHPRIVMessaggi di sicurezza/autorizzazione (privati)
LOG_CRONDemone dell'ora (cron ed at)
LOG_DAEMONAltri demoni di sistema
LOG_KERNMessaggi del kernel
LOG_LOCAL0 ... LOG_LOCAL7Riservato per utilizzi locali, questi non sono dipsonibili in Windows
LOG_LPRSottosistema della stampante
LOG_MAILSottosistema di posta
LOG_NEWSSottosistema USENET news
LOG_SYSLOGMessaggi generati internamente da syslogd
LOG_USERMessaggi utente generici
LOG_UUCPSottosistema UUCP

Tabella 4. Priorità (in ordine decrescente) di syslog()

CostanteDescrizione
LOG_EMERGSistema inutilizzabile
LOG_ALERTAzioni devono essere intraprese immediatamente
LOG_CRITCondizioni critiche
LOG_ERRCondizioni di errore
LOG_WARNINGCondizioni di attenzione
LOG_NOTICESituazione normale, ma significativa
LOG_INFOMessaggio informativo
LOG_DEBUGMessaggio di debug

Tabella 5. Parametri dns_get_record()

CostanteDescrizione
DNS_ARisorsa con indirizzo IPv4
DNS_MXMail Exchanger Resource
DNS_CNAMEAlias (Canonical Name) Resource
DNS_NSAuthoritative Name Server Resource
DNS_PTRPointer Resource
DNS_HINFOHost Info Resource (Vedere la pagina IANA Operating System Names per il significato di questi valori)
DNS_SOAStart of Authority Resource
DNS_TXTText Resource
DNS_ANYAny Resource Record. In molti sistemi questo restituisce tutti i record, tuttavia non si dovrebbe farne affidamento per utilzzi critici. Piuttosto utilizzare DNS_ALL.
DNS_AAAAIPv6 Address Resource
DNS_ALLInterroga in modo iterativo il DNS alla ricerca di ogni tipo di record disponibile.
Sommario
checkdnsrr --  Controlla i record DNS relativi ad un host Internet o indirizzo IP
closelog -- Chiude la connessione al logger di sistema
debugger_off -- Disattiva il debugger interno PHP
debugger_on -- Attiva il debugger interno PHP
define_syslog_variables -- Inizializza tutte le costanti collegate al syslog
dns_check_record -- Synonym for checkdnsrr()
dns_get_mx -- Synonym for getmxrr()
dns_get_record --  Fetch DNS Resource Records associated with a hostname
fsockopen --  Apre una connessione a un socket appartenente a un dominio Internet o Unix
gethostbyaddr --  Ottiene l'host Internet corrispondente a un dato indirizzo IP
gethostbyname --  Ottiene l'indirizzo IP corrispondente a un dato hostname Internet
gethostbynamel --  Ottiene la lista degli indirizzi IP corrispondenti a un dato hostname Internet
getmxrr --  Ottiene i record MX corrispondenti a un dato nome di host Internet
getprotobyname --  Ottiene il numero del protocollo associato al nome del protocollo
getprotobynumber --  Ottiene il nome del protocollo associato al numero del protocollo
getservbyname --  Ottiene il numero di porta associato ad un servizio Internet e ad un protocollo
getservbyport --  Ottiene il servizio Internet corrispondente ad una porta e ad un protocollo
inet_ntop --  Converts a packed internet address to a human readable representation
inet_pton --  Converts a human readable IP address to its packed in_addr representation
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.
long2ip --  Converte un indirizzo di rete del Protocollo Internet (IPv4) in una stringa contenente un indirizzo espresso secondo la notazione standard di Internet.
openlog -- Apre una connessione al logger di sistema
pfsockopen --  Apre una connessione persistente Internet o di tipo domain socket Unix
socket_get_status -- Alias di stream_get_meta_data()
socket_set_blocking -- Alias di stream_set_blocking()
socket_set_timeout -- Alias di stream_set_timeout()
syslog -- Genera un messaggio del system log

checkdnsrr

(PHP 3, PHP 4, PHP 5)

checkdnsrr --  Controlla i record DNS relativi ad un host Internet o indirizzo IP

Descrizione

int checkdnsrr ( string host [, string type] )

Cerca 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

(PHP 3, PHP 4, PHP 5)

closelog -- Chiude la connessione al logger di sistema

Descrizione

int closelog ( void )

closelog() chiude il descrittore usato per scrivere al logger di sistema. L'uso di closelog() è facoltativo.

Vedere anche define_syslog_variables(), syslog() e openlog().

debugger_off

(PHP 3)

debugger_off -- Disattiva il debugger interno PHP

Descrizione

int debugger_off ( void )

Disattiva il debugger interno PHP. Il debugger è ancora in fase di sviluppo.

debugger_on

(PHP 3)

debugger_on -- Attiva il debugger interno PHP

Descrizione

int debugger_on ( string indirizzo )

Attiva il debugger interno PHP, connettendolo ad indirizzo. Il debugger è in fase di sviluppo.

define_syslog_variables

(PHP 3, PHP 4, PHP 5)

define_syslog_variables -- Inizializza tutte le costanti collegate al syslog

Descrizione

void define_syslog_variables ( void )

Inizializza tutte le costanti usate nelle funzioni del syslog.

Vedere anche openlog(), syslog() e closelog().

dns_check_record

(PHP 5)

dns_check_record -- Synonym for checkdnsrr()

Description

bool dns_check_record ( string host [, string type] )

Check DNS records corresponding to a given Internet host name or IP address

dns_get_mx

(PHP 5)

dns_get_mx -- Synonym for getmxrr()

Description

bool dns_get_mx ( string hostname, array &mxhosts [, array &weight] )

Get MX records corresponding to a given Internet host name.

dns_get_record

(PHP 5)

dns_get_record --  Fetch DNS Resource Records associated with a hostname

Description

array dns_get_record ( string hostname [, int type [, array &authns, array &addtl]] )

Nota: This function is not implemented on Windows platforms, 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

AttributeMeaning
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'

TypeExtra 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()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

Produces output similar to the following:

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)

Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.

Esempio 2. Using dns_get_record() and DNS_ANY

<?php
/* Request "ANY" record for php.net, 
   and create $authns and $addtl arrays
   containing list of name servers and
   any additional records which go with
   them */
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?>

Produces output similar to the following:

Result = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
Auth NS = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [1] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [2] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [3] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

)
Additional = Array
(
    [0] => Array
        (
            [host] => pair2.php.net
            [type] => A
            [ip] => 216.92.131.5
            [class] => IN
            [ttl] => 6766
        )

    [1] => Array
        (
            [host] => remote1.easydns.com
            [type] => A
            [ip] => 64.39.29.212
            [class] => IN
            [ttl] => 100384
        )

    [2] => Array
        (
            [host] => remote2.easydns.com
            [type] => A
            [ip] => 212.100.224.80
            [class] => IN
            [ttl] => 81241
        )

    [3] => Array
        (
            [host] => ns1.easydns.com
            [type] => A
            [ip] => 216.220.40.243
            [class] => IN
            [ttl] => 81241
        )

    [4] => Array
        (
            [host] => ns2.easydns.com
            [type] => A
            [ip] => 216.220.40.244
            [class] => IN
            [ttl] => 81241
        )

)

See also dns_get_mx(), and dns_check_record()

fsockopen

(PHP 3, PHP 4, PHP 5)

fsockopen --  Apre una connessione a un socket appartenente a un dominio Internet o Unix

Descrizione

int fsockopen ( string hostname, int porta [, int errno [, string errstr [, float timeout]]] )

Inizializza 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().

Esempio 1. Esempio di fsockopen()

<?php
$fp = fsockopen ("www.php.net", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br>\n";
} else {
    fputs ($fp, "GET / HTTP/1.0\r\nHost: www.php.net\r\n\r\n");
    while (!feof($fp)) {
        echo fgets ($fp,128);
    }
    fclose ($fp);
}
?>
L'esempio seguente mostra come ottenere data e ora tramite il servizio UDP "daytime" (porta 13) della vostra stessa macchina.

Esempio 2. Uso di connessione UDP

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERRORE: $errno - $errstr<br>\n";
} else {
    fwrite($fp,"\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Nota: Il parametro timeout è stato introdotto nel PHP 3.0.9 e il supporto UDP è stato aggiunto nel PHP 4.

Vedere anche pfsockopen(), socket_set_blocking(), socket_set_timeout(), fgets(), fgetss(), fputs(), fclose(), feof() e l'estensione Curl.

gethostbyaddr

(PHP 3, PHP 4, PHP 5)

gethostbyaddr --  Ottiene l'host Internet corrispondente a un dato indirizzo IP

Descrizione

string gethostbyaddr ( string indirizzo_ip )

Restituisce l'hostname dell'host Internet specificato da indirizzo_ip. Se occorre un errore, restituisce indirizzo_ip.

Vedere anche gethostbyname().

gethostbyname

(PHP 3, PHP 4, PHP 5)

gethostbyname --  Ottiene l'indirizzo IP corrispondente a un dato hostname Internet

Descrizione

string gethostbyname ( string hostname )

Restituisce l'indirizzo IP dell'host Internet specificato da hostname.

Vedere anche gethostbyaddr().

gethostbynamel

(PHP 3, PHP 4, PHP 5)

gethostbynamel --  Ottiene la lista degli indirizzi IP corrispondenti a un dato hostname Internet

Descrizione

array gethostbynamel ( string hostname )

Restituisce 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).

getmxrr

(PHP 3, PHP 4, PHP 5)

getmxrr --  Ottiene i record MX corrispondenti a un dato nome di host Internet

Descrizione

int getmxrr ( string hostname, array mxhosts [, array weight] )

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

(PHP 4, PHP 5)

getprotobyname --  Ottiene il numero del protocollo associato al nome del protocollo

Descrizione

int getprotobyname ( string nome )

getprotobyname() restituisce il numero del protocollo associato al protocollo nome come in /etc/protocols.

Vedere anche: getprotobynumber().

getprotobynumber

(PHP 4, PHP 5)

getprotobynumber --  Ottiene il nome del protocollo associato al numero del protocollo

Descrizione

string getprotobynumber ( int numero )

getprotobynumber() restituisce il nome del protocollo associato al protocollo numero come in /etc/protocols.

Vedere anche: getprotobyname().

getservbyname

(PHP 4, PHP 5)

getservbyname --  Ottiene il numero di porta associato ad un servizio Internet e ad un protocollo

Descrizione

int getservbyname ( string servizio, string protocollo )

getservbyname() 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.

Esempio 1. Esempio di uso di getservbyname()

<?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');
 
foreach ($services as $service) {
    $port = getservbyname($service, 'tcp');
    echo $service . ": " . $port . "<br />\n";
}
?>

Per avere la lista completa dei numeri di porta vedere: http://www.iana.org/assignments/port-numbers.

Vedere anche: getservbyport().

getservbyport

(PHP 4, PHP 5)

getservbyport --  Ottiene il servizio Internet corrispondente ad una porta e ad un protocollo

Descrizione

string getservbyport ( int porta, string protocollo )

getservbyport() 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().

inet_ntop

(PHP 5 >= 5.1.0RC1)

inet_ntop --  Converts a packed internet address to a human readable representation

Description

string inet_ntop ( string in_addr )

This 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.

Esempio 1. inet_ntop() Example

<?php
$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

Nota: Questa funzione non è implementata su piattaforme Windows

See also long2ip(), inet_pton(), and ip2long().

inet_pton

(PHP 5 >= 5.1.0RC1)

inet_pton --  Converts a human readable IP address to its packed in_addr representation

Description

string inet_pton ( string address )

This 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.

Esempio 1. inet_pton() Example

<?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');

?>

Nota: Questa funzione non è implementata su piattaforme Windows

See also ip2long(), inet_ntop(), and long2ip().

ip2long

(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.

Descrizione

int ip2long ( string indirizzo_ip )

La funzione ip2long() genera un indirizzo di rete Internet IPv4 a partire dalla rappresentazione in formato standard (stringa separata da punti).

Esempio 1. Esempio di ip2long()

<?php
$ip = gethostbyname("www.php.net");
$out = "I seguenti URL sono equivalenti:<br>\n";
$out .= "http://www.php.net/, http://".$ip."/, e http://".sprintf("%u",ip2long($ip))."/<br>\n";
echo $out;
?>

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.

Questo secondo esempio mostra come stampare un indirizzo convertito, usando la funzione printf():

Esempio 2. Visualizzazione di un indirizzo IP

<?php
$ip = gethostbyname("www.php.net");
printf("%u\n", ip2long($ip));
echo $out;
?>

Vedere anche: long2ip()

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.

Descrizione

string long2ip ( int proper_address )

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

(PHP 3, PHP 4, PHP 5)

openlog -- Apre una connessione al logger di sistema

Descrizione

int openlog ( string ident, int option, int facility )

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()

CostanteDescrizione
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_PERRORstampa un messaggio di log anche su standard error
LOG_PIDinclude il PID in ciascun messaggio
Si possono usare una o più di queste opzioni. Usando opzioni multiple è necessario usare OR, ad esempio per aprire la connessione immediatamente, scrivere sulla console e il PID in ciascun messaggio, si dovrà usare: LOG_CONS | LOG_NDELAY | LOG_PID

Tabella 2. Facility di openlog()

CostanteDescrizione
LOG_AUTH messaggi di sicurezza/autorizzazione (usa LOG_AUTHPRIV nei sistemi dove è definita quella costante)
LOG_AUTHPRIVmessaggi di sicurezza/autorizzazione (private)
LOG_CRONclock daemon (cron e at)
LOG_DAEMONaltri demoni di sistema
LOG_KERNmessaggi del kernel
LOG_LOCAL0 ... LOG_LOCAL7riservato per il locale
LOG_LPRsottosistema line printer
LOG_MAILsottosistema mail
LOG_NEWSsottosistema news di USENET
LOG_SYSLOGmessaggi generati internamente da syslogd
LOG_USERmessaggi generici user-level
LOG_UUCPsottosistema UUCP

Vedere anche define_syslog_variables(), syslog() e closelog().

pfsockopen

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

pfsockopen --  Apre una connessione persistente Internet o di tipo domain socket Unix

Descrizione

int pfsockopen ( string hostname, int port [, int errno [, string errstr [, int timeout]]] )

Questa 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().

socket_get_status

(PHP 4, PHP 5)

socket_get_status -- Alias di stream_get_meta_data()

Descrizione

This function is an alias of: stream_get_meta_data().

socket_set_blocking

(PHP 4, PHP 5)

socket_set_blocking -- Alias di stream_set_blocking()

Descrizione

This function is an alias of: stream_set_blocking().

socket_set_timeout

(PHP 4, PHP 5)

socket_set_timeout -- Alias di stream_set_timeout()

Descrizione

This function is an alias of: stream_set_timeout().

syslog

(PHP 3, PHP 4, PHP 5)

syslog -- Genera un messaggio del system log

Descrizione

int syslog ( int priorità, string messaggio )

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)

CostanteDescrizione
LOG_EMERGsistema non utilizzabile
LOG_ALERTazione da intraprendere immediatamente
LOG_CRITcondizioni critiche
LOG_ERRcondizioni di errore
LOG_WARNINGcondizioni di attenzione
LOG_NOTICEcondizione normale, ma significativa
LOG_INFOmessaggio di informazione
LOG_DEBUGmessaggio a livello di debug

Esempio 1. Uso di syslog()

<?php
define_syslog_variables();
// apre il syslog, include l'ID del processo, invia il
// log anche su standard error e fa uso di un meccanismo
// di logging defiito dall'utente
openlog("IlMioLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// un po' di codice

if (client_autorizzato()) {
    // fa qualcosa
} else {
    // client non autorizzato!
    // logga il tentativo
    $accesso = date("Y/m/d H:i:s");
    syslog(LOG_WARNING,"Client non autorizzato: $accesso $REMOTE_ADDR ($HTTP_USER_AGENT)");
}

closelog();
?>
Per informazioni su come creare un gestore di log definito dall'utente, fare riferimento alla man page syslog.conf(5) di Unix. Ulteriori informazioni sulle facility di syslog e sulle sue opzioni possono essere trovate sulle macchine Unix nelle man page di syslog(3).

Su Windows NT, il servizio syslog è emulato usando Event Log.

Vedere anche define_syslog_variables(), openlog() e closelog().

XCI. Newt Functions

Introduzione

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.


Requisiti

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.


Installazione

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


Tipi di risorse

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())


Costanti predefinite

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.

NEWT_COLORSET_ROOT (integer)

NEWT_COLORSET_BORDER (integer)

NEWT_COLORSET_WINDOW (integer)

NEWT_COLORSET_SHADOW (integer)

NEWT_COLORSET_TITLE (integer)

NEWT_COLORSET_BUTTON (integer)

NEWT_COLORSET_ACTBUTTON (integer)

NEWT_COLORSET_CHECKBOX (integer)

NEWT_COLORSET_ACTCHECKBOX (integer)

NEWT_COLORSET_ENTRY (integer)

NEWT_COLORSET_LABEL (integer)

NEWT_COLORSET_LISTBOX (integer)

NEWT_COLORSET_ACTLISTBOX (integer)

NEWT_COLORSET_TEXTBOX (integer)

NEWT_COLORSET_ACTTEXTBOX (integer)

NEWT_COLORSET_HELPLINE (integer)

NEWT_COLORSET_ROOTTEXT (integer)

NEWT_COLORSET_EMPTYSCALE (integer)

NEWT_COLORSET_FULLSCALE (integer)

NEWT_COLORSET_DISENTRY (integer)

NEWT_COLORSET_COMPACTBUTTON (integer)

NEWT_COLORSET_ACTSELLISTBOX (integer)

NEWT_COLORSET_SELLISTBOX (integer)

NEWT_ARG_LAST (integer)

NEWT_ARG_APPEND (integer)

NEWT_FLAGS_SET (integer)

NEWT_FLAGS_RESET (integer)

NEWT_FLAGS_TOGGLE (integer)

NEWT_FLAG_RETURNEXIT (integer)

NEWT_FLAG_HIDDEN (integer)

NEWT_FLAG_SCROLL (integer)

NEWT_FLAG_DISABLED (integer)

NEWT_FLAG_BORDER (integer)

NEWT_FLAG_WRAP (integer)

NEWT_FLAG_NOF12 (integer)

NEWT_FLAG_MULTIPLE (integer)

NEWT_FLAG_SELECTED (integer)

NEWT_FLAG_CHECKBOX (integer)

NEWT_FLAG_PASSWORD (integer)

NEWT_FLAG_SHOWCURSOR (integer)

NEWT_FD_READ (integer)

NEWT_FD_WRITE (integer)

NEWT_FD_EXCEPT (integer)

NEWT_CHECKBOXTREE_UNSELECTABLE (integer)

NEWT_CHECKBOXTREE_HIDE_BOX (integer)

NEWT_CHECKBOXTREE_COLLAPSED (integer)

NEWT_CHECKBOXTREE_EXPANDED (integer)

NEWT_CHECKBOXTREE_UNSELECTED (integer)

NEWT_CHECKBOXTREE_SELECTED (integer)

NEWT_LISTBOX_RETURNEXIT (integer)

NEWT_ENTRY_SCROLL (integer)

NEWT_ENTRY_HIDDEN (integer)

NEWT_ENTRY_RETURNEXIT (integer)

NEWT_ENTRY_DISABLED (integer)

NEWT_TEXTBOX_WRAP (integer)

NEWT_TEXTBOX_SCROLL (integer)

NEWT_FORM_NOF12 (integer)

NEWT_EXIT_HOTKEY (integer)

NEWT_EXIT_COMPONENT (integer)

NEWT_EXIT_FDREADY (integer)

NEWT_EXIT_TIMER (integer)

NEWT_KEY_TAB (integer)

NEWT_KEY_ENTER (integer)

NEWT_KEY_SUSPEND (integer)

NEWT_KEY_ESCAPE (integer)

NEWT_KEY_RETURN (integer)

NEWT_KEY_EXTRA_BASE (integer)

NEWT_KEY_UP (integer)

NEWT_KEY_DOWN (integer)

NEWT_KEY_LEFT (integer)

NEWT_KEY_RIGHT (integer)

NEWT_KEY_BKSPC (integer)

NEWT_KEY_DELETE (integer)

NEWT_KEY_HOME (integer)

NEWT_KEY_END (integer)

NEWT_KEY_UNTAB (integer)

NEWT_KEY_PGUP (integer)

NEWT_KEY_PGDN (integer)

NEWT_KEY_INSERT (integer)

NEWT_KEY_F1 (integer)

NEWT_KEY_F2 (integer)

NEWT_KEY_F3 (integer)

NEWT_KEY_F4 (integer)

NEWT_KEY_F5 (integer)

NEWT_KEY_F6 (integer)

NEWT_KEY_F7 (integer)

NEWT_KEY_F8 (integer)

NEWT_KEY_F9 (integer)

NEWT_KEY_F10 (integer)

NEWT_KEY_F11 (integer)

NEWT_KEY_F12 (integer)

NEWT_KEY_RESIZE (integer)

NEWT_ANCHOR_LEFT (integer)

NEWT_ANCHOR_RIGHT (integer)

NEWT_ANCHOR_TOP (integer)

NEWT_ANCHOR_BOTTOM (integer)

NEWT_GRID_FLAG_GROWX (integer)

NEWT_GRID_FLAG_GROWY (integer)

NEWT_GRID_EMPTY (integer)

NEWT_GRID_COMPONENT (integer)

NEWT_GRID_SUBGRID (integer)

Sommario
newt_bell -- Send a beep to the terminal
newt_button_bar -- 
newt_button -- 
newt_centered_window -- Open a centered window of the specified size
newt_checkbox_get_value -- 
newt_checkbox_set_flags -- 
newt_checkbox_set_value -- 
newt_checkbox_tree_add_item -- *
newt_checkbox_tree_find_item -- 
newt_checkbox_tree_get_current -- 
newt_checkbox_tree_get_entry_value -- 
newt_checkbox_tree_get_multi_selection -- 
newt_checkbox_tree_get_selection -- 
newt_checkbox_tree_multi -- 
newt_checkbox_tree_set_current -- 
newt_checkbox_tree_set_entry_value -- 
newt_checkbox_tree_set_entry -- 
newt_checkbox_tree_set_width -- 
newt_checkbox_tree -- 
newt_checkbox -- 
newt_clear_key_buffer -- Discards the contents of the terminal's input buffer without waiting for additional input
newt_cls -- 
newt_compact_button -- 
newt_component_add_callback -- 
newt_component_takes_focus -- 
newt_create_grid -- 
newt_cursor_off -- 
newt_cursor_on -- 
newt_delay -- 
newt_draw_form -- 
newt_draw_root_text -- Displays the string text at the position indicated
newt_entry_get_value -- 
newt_entry_set_filter -- 
newt_entry_set_flags -- 
newt_entry_set -- 
newt_entry -- 
newt_finished -- Uninitializes newt interface.
newt_form_add_component -- 
newt_form_add_components -- 
newt_form_add_host_key -- 
newt_form_get_current -- 
newt_form_run -- 
newt_form_set_background -- 
newt_form_set_height -- 
newt_form_set_size -- 
newt_form_set_timer -- 
newt_form_set_width -- 
newt_form_watch_fd -- 
newt_form -- 
newt_get_screen_size -- Fills in the passed references with the current size of the terminal
newt_grid_add_components_to_form -- 
newt_grid_basic_window -- 
newt_grid_free -- 
newt_grid_get_size -- 
newt_grid_h_close_stacked -- 
newt_grid_h_stacked -- 
newt_grid_place -- 
newt_grid_set_field -- 
newt_grid_simple_window -- 
newt_grid_v_close_stacked -- 
newt_grid_v_stacked -- 
newt_grid_wrapped_window_at -- 
newt_grid_wrapped_window -- 
newt_init -- Initialize newt
newt_label_set_text -- 
newt_label -- 
newt_listbox_append_entry -- 
newt_listbox_clear_selection -- 
newt_listbox_clear -- 
newt_listbox_delete_entry -- 
newt_listbox_get_current -- 
newt_listbox_get_selection -- 
newt_listbox_insert_entry -- 
newt_listbox_item_count -- 
newt_listbox_select_item -- 
newt_listbox_set_current_by_key -- 
newt_listbox_set_current -- 
newt_listbox_set_data -- 
newt_listbox_set_entry -- 
newt_listbox_set_width -- 
newt_listbox -- 
newt_listitem_get_data -- 
newt_listitem_set -- 
newt_listitem -- 
newt_open_window -- Open a window of the specified size and position
newt_pop_help_line -- Replaces the current help line with the one from the stack
newt_pop_window -- Removes the top window from the display
newt_push_help_line -- Saves the current help line on a stack, and displays the new line
newt_radio_get_current -- 
newt_radiobutton -- 
newt_redraw_help_line -- 
newt_reflow_text -- 
newt_refresh -- Updates modified portions of the screen
newt_resize_screen -- 
newt_resume -- Resume using the newt interface after calling newt_suspend()
newt_run_form -- 
newt_scale_set -- 
newt_scale -- 
newt_scrollbar_set -- 
newt_set_help_callback -- 
newt_set_suspend_callback -- Set a callback function which gets invoked when user presses the suspend key
newt_suspend -- Tells newt to return the terminal to its initial state
newt_texbox_set_text -- 
newt_textbox_get_num_lines -- 
newt_textbox_reflowed -- 
newt_textbox_set_height -- 
newt_textbox -- 
newt_vertical_scrollbar -- 
newt_wait_for_key -- Doesn't return until a key has been pressed
newt_win_choice -- 
newt_win_entries -- 
newt_win_menu -- 
newt_win_message -- 
newt_win_messagev -- 
newt_win_ternary -- 

newt_bell

(PECL)

newt_bell -- Send a beep to the terminal

Descrizione

void newt_bell ( void )

This function sends a beep to the terminal.

Nota: Depending on the terminal's settings, this been may or may not be audible.

newt_button_bar

(PECL)

newt_button_bar -- 

Descrizione

resource newt_button_bar ( array &buttons )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

buttons

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_button

(PECL)

newt_button -- 

Descrizione

resource newt_button ( int left, int top, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_centered_window

(PECL)

newt_centered_window -- Open a centered window of the specified size

Descrizione

int newt_centered_window ( int width, int height [, string title] )

Open a centered window of the specified size.

Elenco dei parametri

width

Window width

height

Window height

title

Window title

Valori restituiti

Undefined value.

newt_checkbox_get_value

(PECL)

newt_checkbox_get_value -- 

Descrizione

string newt_checkbox_get_value ( resource checkbox )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkbox

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_set_flags

(PECL)

newt_checkbox_set_flags -- 

Descrizione

void newt_checkbox_set_flags ( resource checkbox, int flags, int sense )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkbox

Its description

flags

Its description

sense

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_set_value

(PECL)

newt_checkbox_set_value -- 

Descrizione

void newt_checkbox_set_value ( resource checkbox, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkbox

Its description

value

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_add_item

(PECL)

newt_checkbox_tree_add_item -- *

Descrizione

void newt_checkbox_tree_add_item ( resource checkboxtree, string text, mixed data, int flags, array indexes )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

text

Its description

data

Its description

flags

Its description

indexes

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_find_item

(PECL)

newt_checkbox_tree_find_item -- 

Descrizione

array newt_checkbox_tree_find_item ( resource checkboxtree, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_get_current

(PECL)

newt_checkbox_tree_get_current -- 

Descrizione

mixed newt_checkbox_tree_get_current ( resource checkboxtree )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_get_entry_value

(PECL)

newt_checkbox_tree_get_entry_value -- 

Descrizione

string newt_checkbox_tree_get_entry_value ( resource checkboxtree, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_get_multi_selection

(PECL)

newt_checkbox_tree_get_multi_selection -- 

Descrizione

array newt_checkbox_tree_get_multi_selection ( resource checkboxtree, string seqnum )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

seqnum

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_get_selection

(PECL)

newt_checkbox_tree_get_selection -- 

Descrizione

array newt_checkbox_tree_get_selection ( resource checkboxtree )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_multi

(PECL)

newt_checkbox_tree_multi -- 

Descrizione

resource newt_checkbox_tree_multi ( int left, int top, int height, string seq [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

height

Its description

seq

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_set_current

(PECL)

newt_checkbox_tree_set_current -- 

Descrizione

void newt_checkbox_tree_set_current ( resource checkboxtree, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_set_entry_value

(PECL)

newt_checkbox_tree_set_entry_value -- 

Descrizione

void newt_checkbox_tree_set_entry_value ( resource checkboxtree, mixed data, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

data

Its description

value

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_set_entry

(PECL)

newt_checkbox_tree_set_entry -- 

Descrizione

void newt_checkbox_tree_set_entry ( resource checkboxtree, mixed data, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkboxtree

Its description

data

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree_set_width

(PECL)

newt_checkbox_tree_set_width -- 

Descrizione

void newt_checkbox_tree_set_width ( resource checkbox_tree, int width )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

checkbox_tree

Its description

width

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox_tree

(PECL)

newt_checkbox_tree -- 

Descrizione

resource newt_checkbox_tree ( int left, int top, int height [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

height

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_checkbox

(PECL)

newt_checkbox -- 

Descrizione

resource newt_checkbox ( int left, int top, string text, string def_value [, string seq] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

text

Its description

def_value

Its description

seq

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_clear_key_buffer

(PECL)

newt_clear_key_buffer -- Discards the contents of the terminal's input buffer without waiting for additional input

Descrizione

void newt_clear_key_buffer ( void )

Discards the contents of the terminal's input buffer without waiting for additional input.

Vedere anche:

newt_wait_for_key()

newt_cls

(PECL)

newt_cls -- 

Descrizione

void newt_cls ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_compact_button

(PECL)

newt_compact_button -- 

Descrizione

resource newt_compact_button ( int left, int top, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_component_add_callback

(PECL)

newt_component_add_callback -- 

Descrizione

void newt_component_add_callback ( resource component, mixed func_name, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

component

Its description

func_name

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_component_takes_focus

(PECL)

newt_component_takes_focus -- 

Descrizione

void newt_component_takes_focus ( resource component, bool takes_focus )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

component

Its description

takes_focus

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_create_grid

(PECL)

newt_create_grid -- 

Descrizione

resource newt_create_grid ( int cols, int rows )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

cols

Its description

rows

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_cursor_off

(PECL)

newt_cursor_off -- 

Descrizione

void newt_cursor_off ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_cursor_on

(PECL)

newt_cursor_on -- 

Descrizione

void newt_cursor_on ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_delay

(PECL)

newt_delay -- 

Descrizione

void newt_delay ( int microseconds )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

microseconds

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_draw_form

(PECL)

newt_draw_form -- 

Descrizione

void newt_draw_form ( resource form )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_draw_root_text

(PECL)

newt_draw_root_text -- Displays the string text at the position indicated

Descrizione

void newt_draw_root_text ( int left, int top, string text )

Displays the string text at the position indicated.

Elenco dei parametri

left

Column number

Nota: If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Nota: If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

Esempi

Esempio 1. A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

<?
 newt_init();
 newt_cls();

 newt_draw_root_text (2, 0, "Some root text");
 newt_refresh();
 sleep(1);

 newt_draw_root_text (-30, 0, "Root text in the other corner");
 newt_refresh();
 sleep(1);

 newt_finished();
?>

newt_entry_get_value

(PECL)

newt_entry_get_value -- 

Descrizione

string newt_entry_get_value ( resource entry )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

entry

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_entry_set_filter

(PECL)

newt_entry_set_filter -- 

Descrizione

void newt_entry_set_filter ( resource entry, callback filter, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

entry

Its description

filter

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_entry_set_flags

(PECL)

newt_entry_set_flags -- 

Descrizione

void newt_entry_set_flags ( resource entry, int flags, int sense )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

entry

Its description

flags

Its description

sense

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_entry_set

(PECL)

newt_entry_set -- 

Descrizione

void newt_entry_set ( resource entry, string value [, bool cursor_at_end] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

entry

Its description

value

Its description

cursor_at_end

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_entry

(PECL)

newt_entry -- 

Descrizione

resource newt_entry ( int left, int top, int width [, string init_value [, int flags]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

width

Its description

init_value

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_finished

(PECL)

newt_finished -- Uninitializes newt interface.

Descrizione

void newt_finished ( void )

Uninitializes newt interface. This function be called, when program is ready to exit.

Vedere anche:

newt_init()

newt_form_add_component

(PECL)

newt_form_add_component -- 

Descrizione

void newt_form_add_component ( resource form, resource component )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

component

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_add_components

(PECL)

newt_form_add_components -- 

Descrizione

void newt_form_add_components ( resource form, array components )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

components

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_add_host_key

(no version information, might be only in CVS)

newt_form_add_host_key -- 

Descrizione

void newt_form_add_host_key ( resource form, int key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

key

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_get_current

(PECL)

newt_form_get_current -- 

Descrizione

resource newt_form_get_current ( resource form )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_run

(PECL)

newt_form_run -- 

Descrizione

void newt_form_run ( resource form, array &exit_struct )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

exit_struct

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_set_background

(PECL)

newt_form_set_background -- 

Descrizione

void newt_form_set_background ( resource from, int background )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

from

Its description

background

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_set_height

(PECL)

newt_form_set_height -- 

Descrizione

void newt_form_set_height ( resource form, int height )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

height

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_set_size

(PECL)

newt_form_set_size -- 

Descrizione

void newt_form_set_size ( resource form )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_set_timer

(PECL)

newt_form_set_timer -- 

Descrizione

void newt_form_set_timer ( resource form, int milliseconds )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

milliseconds

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_set_width

(PECL)

newt_form_set_width -- 

Descrizione

void newt_form_set_width ( resource form, int width )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

width

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form_watch_fd

(PECL)

newt_form_watch_fd -- 

Descrizione

void newt_form_watch_fd ( resource form, resource stream [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

stream

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_form

(PECL)

newt_form -- 

Descrizione

resource newt_form ( [resource vert_bar [, string help [, int flags]]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

vert_bar

Its description

help

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_get_screen_size

(PECL)

newt_get_screen_size -- Fills in the passed references with the current size of the terminal

Descrizione

void newt_get_screen_size ( int &cols, int &rows )

Fills in the passed references with the current size of the terminal.

Elenco dei parametri

cols

Number of columns in the terminal

rows

Number of rows in the terminal

Valori restituiti

This function returns values in an arguments, passed by reference.

Esempi

Esempio 1. A newt_get_screen_size() example

This code prints out the screen size of your terminal.

<?php
 newt_init();
 newt_get_screen_size (&$cols, &$rows);
 newt_finished();

 print "Your terminal size is: {$cols}x{$rows}\n";
?>

Il precedente esempio visualizzerà:

Your terminal size is: 138x47

newt_grid_add_components_to_form

(PECL)

newt_grid_add_components_to_form -- 

Descrizione

void newt_grid_add_components_to_form ( resource grid, resource form, bool recurse )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

form

Its description

recurse

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_basic_window

(PECL)

newt_grid_basic_window -- 

Descrizione

resource newt_grid_basic_window ( resource text, resource middle, resource buttons )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

text

Its description

middle

Its description

buttons

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_free

(PECL)

newt_grid_free -- 

Descrizione

void newt_grid_free ( resource grid, bool recurse )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

recurse

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_get_size

(PECL)

newt_grid_get_size -- 

Descrizione

void newt_grid_get_size ( resouce grid, int &width, int &height )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

width

Its description

height

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_h_close_stacked

(PECL)

newt_grid_h_close_stacked -- 

Descrizione

resource newt_grid_h_close_stacked ( int element1_type, resource element1 )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

element1_type

Its description

element1

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_h_stacked

(PECL)

newt_grid_h_stacked -- 

Descrizione

resource newt_grid_h_stacked ( int element1_type, resource element1 )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

element1_type

Its description

element1

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_place

(PECL)

newt_grid_place -- 

Descrizione

void newt_grid_place ( resource grid, int left, int top )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

left

Its description

top

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_set_field

(PECL)

newt_grid_set_field -- 

Descrizione

void newt_grid_set_field ( resource grid, int col, int row, int type, resource val, int pad_left, int pad_top, int pad_right, int pad_bottom, int anchor [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

col

Its description

row

Its description

type

Its description

val

Its description

pad_left

Its description

pad_top

Its description

pad_right

Its description

pad_bottom

Its description

anchor

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_simple_window

(PECL)

newt_grid_simple_window -- 

Descrizione

resource newt_grid_simple_window ( resource text, resource middle, resource buttons )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

text

Its description

middle

Its description

buttons

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_v_close_stacked

(PECL)

newt_grid_v_close_stacked -- 

Descrizione

resource newt_grid_v_close_stacked ( int element1_type, resource element1 )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

element1_type

Its description

element1

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_v_stacked

(PECL)

newt_grid_v_stacked -- 

Descrizione

resource newt_grid_v_stacked ( int element1_type, resource element1 )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

element1_type

Its description

element1

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_wrapped_window_at

(PECL)

newt_grid_wrapped_window_at -- 

Descrizione

void newt_grid_wrapped_window_at ( resource grid, string title, int left, int top )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

title

Its description

left

Its description

top

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_grid_wrapped_window

(PECL)

newt_grid_wrapped_window -- 

Descrizione

void newt_grid_wrapped_window ( resource grid, string title )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

grid

Its description

title

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_init

(PECL)

newt_init -- Initialize newt

Descrizione

void newt_init ( void )

Initializes the newt interface. This function must be called before any other newt function.

Vedere anche:

newt_finished()

newt_label_set_text

(PECL)

newt_label_set_text -- 

Descrizione

void newt_label_set_text ( resource label, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

label

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_label

(PECL)

newt_label -- 

Descrizione

resource newt_label ( int left, int top, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_append_entry

(PECL)

newt_listbox_append_entry -- 

Descrizione

void newt_listbox_append_entry ( resource listbox, string text, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

text

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_clear_selection

(PECL)

newt_listbox_clear_selection -- 

Descrizione

void newt_listbox_clear_selection ( resource listbox )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_clear

(PECL)

newt_listbox_clear -- 

Descrizione

void newt_listbox_clear ( resource listobx )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listobx

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_delete_entry

(PECL)

newt_listbox_delete_entry -- 

Descrizione

void newt_listbox_delete_entry ( resource listbox, mixed key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

key

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_get_current

(PECL)

newt_listbox_get_current -- 

Descrizione

string newt_listbox_get_current ( resource listbox )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_get_selection

(PECL)

newt_listbox_get_selection -- 

Descrizione

array newt_listbox_get_selection ( resource listbox )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_insert_entry

(PECL)

newt_listbox_insert_entry -- 

Descrizione

void newt_listbox_insert_entry ( resource listbox, string text, mixed data, mixed key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

text

Its description

data

Its description

key

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_item_count

(PECL)

newt_listbox_item_count -- 

Descrizione

int newt_listbox_item_count ( resource listbox )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_select_item

(PECL)

newt_listbox_select_item -- 

Descrizione

void newt_listbox_select_item ( resource listbox, mixed key, int sense )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

key

Its description

sense

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_set_current_by_key

(PECL)

newt_listbox_set_current_by_key -- 

Descrizione

void newt_listbox_set_current_by_key ( resource listbox, mixed key )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

key

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_set_current

(PECL)

newt_listbox_set_current -- 

Descrizione

void newt_listbox_set_current ( resource listbox, int num )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

num

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_set_data

(PECL)

newt_listbox_set_data -- 

Descrizione

void newt_listbox_set_data ( resource listbox, int num, mixed data )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

num

Its description

data

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_set_entry

(PECL)

newt_listbox_set_entry -- 

Descrizione

void newt_listbox_set_entry ( resource listbox, int num, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

num

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox_set_width

(PECL)

newt_listbox_set_width -- 

Descrizione

void newt_listbox_set_width ( resource listbox, int width )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

listbox

Its description

width

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listbox

(PECL)

newt_listbox -- 

Descrizione

resource newt_listbox ( int left, int top, int height [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

height

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listitem_get_data

(PECL)

newt_listitem_get_data -- 

Descrizione

mixed newt_listitem_get_data ( resource item )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

item

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listitem_set

(PECL)

newt_listitem_set -- 

Descrizione

void newt_listitem_set ( resource item, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

item

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_listitem

(PECL)

newt_listitem -- 

Descrizione

resource newt_listitem ( int left, int top, string text, bool is_default, resouce prev_item, mixed data [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

text

Its description

is_default

Its description

prev_item

Its description

data

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_open_window

(PECL)

newt_open_window -- Open a window of the specified size and position

Descrizione

void newt_open_window ( int left, int top, int width, int height [, string title] )

Open a window of the specified size and position.

Elenco dei parametri

left

Location of the upper left-hand corner of the window (column number)

top

Location of the upper left-hand corner of the window (row number)

width

Window width

height

Window height

title

Window title

Valori restituiti

Undefined value.

newt_pop_help_line

(PECL)

newt_pop_help_line -- Replaces the current help line with the one from the stack

Descrizione

void newt_pop_help_line ( void )

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().

Vedere anche:

newt_push_help_line()

newt_pop_window

(PECL)

newt_pop_window -- Removes the top window from the display

Descrizione

void newt_pop_window ( void )

Removes the top window from the display, and redraws the display areas which the window overwrote.

newt_push_help_line

(PECL)

newt_push_help_line -- Saves the current help line on a stack, and displays the new line

Descrizione

void newt_push_help_line ( [string text] )

Saves the current help line on a stack, and displays the new line.

Elenco dei parametri

text

New help text message

Nota: If not specified, the help line is cleared.

Vedere anche:

newt_pop_help_line()

newt_radio_get_current

(PECL)

newt_radio_get_current -- 

Descrizione

resource newt_radio_get_current ( resource set_member )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

set_member

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_radiobutton

(PECL)

newt_radiobutton -- 

Descrizione

resource newt_radiobutton ( int left, int top, string text, bool is_default [, resource prev_button] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

text

Its description

is_default

Its description

prev_button

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_redraw_help_line

(PECL)

newt_redraw_help_line -- 

Descrizione

void newt_redraw_help_line ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_reflow_text

(PECL)

newt_reflow_text -- 

Descrizione

string newt_reflow_text ( string text, int width, int flex_down, int flex_up, int &actual_width, int &actual_height )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

text

Its description

width

Its description

flex_down

Its description

flex_up

Its description

actual_width

Its description

actual_height

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_refresh

(PECL)

newt_refresh -- Updates modified portions of the screen

Descrizione

void newt_refresh ( void )

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.

newt_resize_screen

(PECL)

newt_resize_screen -- 

Descrizione

void newt_resize_screen ( [bool redraw] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

redraw

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_resume

(PECL)

newt_resume -- Resume using the newt interface after calling newt_suspend()

Descrizione

void newt_resume ( void )

Resume using the newt interface after calling newt_suspend().

Vedere anche:

newt_suspend()

newt_run_form

(PECL)

newt_run_form -- 

Descrizione

resource newt_run_form ( resource form )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

form

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_scale_set

(PECL)

newt_scale_set -- 

Descrizione

void newt_scale_set ( resource scale, int amount )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

scale

Its description

amount

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_scale

(PECL)

newt_scale -- 

Descrizione

resource newt_scale ( int left, int top, int width, int full_value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

width

Its description

full_value

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_scrollbar_set

(PECL)

newt_scrollbar_set -- 

Descrizione

void newt_scrollbar_set ( resource scrollbar, int where, int total )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

scrollbar

Its description

where

Its description

total

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_set_help_callback

(PECL)

newt_set_help_callback -- 

Descrizione

void newt_set_help_callback ( mixed function )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

function

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_set_suspend_callback

(PECL)

newt_set_suspend_callback -- Set a callback function which gets invoked when user presses the suspend key

Descrizione

void newt_set_suspend_callback ( callback function, mixed data )

Set 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.

Elenco dei parametri

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

newt_suspend

(PECL)

newt_suspend -- Tells newt to return the terminal to its initial state

Descrizione

void newt_suspend ( void )

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.

Vedere anche:

newt_resume()

newt_texbox_set_text

(no version information, might be only in CVS)

newt_texbox_set_text -- 

Descrizione

void newt_texbox_set_text ( resource textbox, string text )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

textbox

Its description

text

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_textbox_get_num_lines

(PECL)

newt_textbox_get_num_lines -- 

Descrizione

int newt_textbox_get_num_lines ( resource textbox )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

textbox

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_textbox_reflowed

(PECL)

newt_textbox_reflowed -- 

Descrizione

resource newt_textbox_reflowed ( int left, int top, char *text, int width, int flex_down, int flex_up [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

*text

Its description

width

Its description

flex_down

Its description

flex_up

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_textbox_set_height

(PECL)

newt_textbox_set_height -- 

Descrizione

void newt_textbox_set_height ( resource textbox, int height )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

textbox

Its description

height

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_textbox

(PECL)

newt_textbox -- 

Descrizione

resource newt_textbox ( int left, int top, int width, int height [, int flags] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

width

Its description

height

Its description

flags

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_vertical_scrollbar

(PECL)

newt_vertical_scrollbar -- 

Descrizione

resource newt_vertical_scrollbar ( int left, int top, int height [, int normal_colorset [, int thumb_colorset]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

left

Its description

top

Its description

height

Its description

normal_colorset

Its description

thumb_colorset

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_wait_for_key

(PECL)

newt_wait_for_key -- Doesn't return until a key has been pressed

Descrizione

void newt_wait_for_key ( void )

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.

newt_win_choice

(PECL)

newt_win_choice -- 

Descrizione

int newt_win_choice ( string title, string button1_text, string button2_text, string format [, mixed args] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

title

Its description

button1_text

Its description

button2_text

Its description

format

Its description

args

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_entries

(PECL)

newt_win_entries -- 

Descrizione

int newt_win_entries ( string title, string text, int suggested_width, int flex_down, int flex_up, int data_width, array &items, string button1 [, string button2] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

title

Its description

text

Its description

suggested_width

Its description

flex_down

Its description

flex_up

Its description

data_width

Its description

items

Its description

button1

Its description

button2

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_menu

(PECL)

newt_win_menu -- 

Descrizione

int newt_win_menu ( string title, string text, int suggestedWidth, int flexDown, int flexUp, int maxListHeight, array items, int &listItem [, string button1] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

title

Its description

text

Its description

suggestedWidth

Its description

flexDown

Its description

flexUp

Its description

maxListHeight

Its description

items

Its description

listItem

Its description

button1

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_message

(PECL)

newt_win_message -- 

Descrizione

void newt_win_message ( string title, string button_text, string format [, mixed args] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

title

Its description

button_text

Its description

format

Its description

args

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_messagev

(PECL)

newt_win_messagev -- 

Descrizione

void newt_win_messagev ( string title, string button_text, string format, array args )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

title

Its description

button_text

Its description

format

Its description

args

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

newt_win_ternary

(PECL)

newt_win_ternary -- 

Descrizione

int newt_win_ternary ( string title, string button1_text, string button2_text, string button3_text, string format [, mixed args] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

Valori restituiti

What the function returns, first on success, then on failure. See also the &return.success; entity

XCII. NSAPI-specific Functions

Introduzione

These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/SunONE webservers.


Installazione

For PHP installation on Netscape/iPlanet/SunONE webservers see the NSAPI section (UNIX, Windows) in the installation chapter.


Configurazione di Runtime

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

NameDefaultChangeableChangelog
nsapi.read_timeout"60"PHP_INI_ALLAvailable since PHP 4.3.3.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

nsapi.read_timeout integer

Sets the time in seconds the plugin is waiting for POST data from the client.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Vedere anche:

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 functionDescription
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

Sommario
nsapi_request_headers -- Fetch all HTTP request headers
nsapi_response_headers --  Fetch all HTTP response headers
nsapi_virtual -- Perform an NSAPI sub-request

nsapi_request_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_request_headers -- Fetch all HTTP request headers

Descrizione

array nsapi_request_headers ( void )

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.

Valori restituiti

Returns an associative array with all the HTTP headers.

Esempi

Esempio 1. nsapi_request_headers() example

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
  echo "$header: $value <br />\n";
}
?>

nsapi_response_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_response_headers --  Fetch all HTTP response headers

Descrizione

array nsapi_response_headers ( void )

Gets all the NSAPI response headers.

Valori restituiti

Returns an associative array with all the NSAPI response headers.

nsapi_virtual

(PHP 4 >= 4.3.3, PHP 5)

nsapi_virtual -- Perform an NSAPI sub-request

Descrizione

bool nsapi_virtual ( string uri )

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.

Elenco dei parametri

uri

The URI of the script.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XCIII. Object Aggregation/Composition 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.


Introduzione

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

<?php
class DateTime {
   
   function DateTime() 
   {
       // empty constructor
   }

   function now() 
   {
       return date("Y-m-d H:i:s");
   }
}

class Report {
   var $_dt;
   // more properties ...

   function Report() 
   {
       $this->_dt = new DateTime();
       // initialization code ...
   }

   function generateReport() 
   {
       $dateTime = $this->_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
?>
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Esempio 2. Object association

<?php
class DateTime {
   // same as previous example
}

class DateTimePlus {
   var $_format;
   
   function DateTimePlus($format="Y-m-d H:i:s") 
   {
       $this->_format = $format;
   }

   function now() 
   {
       return date($this->_format);
   }
}

class Report {
   var $_dt;    // we'll keep the reference to DateTime here
   // more properties ...

   function Report() 
   {
       // do some initialization
   }

   function setDateTime(&$dt) 
   {
       $this->_dt =& $dt;
   }

   function generateReport() 
   {
       $dateTime = $this->_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setDateTime(&$dt);
echo $rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setDateTime(&$dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ... 
?>

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.


Esempi

We define 3 classes, each implementing a different storage method:

Esempio 3. storage_classes.inc

<?php
class FileStorage {
    var $data;

    function FileStorage($data) 
    {
        $this->data = $data;
    }
    
    function write($name) 
    {
        $fp = fopen(name, "w");
        fwrite($fp, $this->data);
        fclose($data);
    }
}

class WDDXStorage {
    var $data;
    var $version = "1.0";
    var $_id; // "private" variable

    function WDDXStorage($data) 
    {
        $this->data = $data;
        $this->_id = $this->_genID();
    }

    function store() 
    {
        if ($this->_id) {
            $pid = wddx_packet_start($this->_id);
            wddx_add_vars($pid, "this->data");
            $packet = wddx_packet_end($pid);
        } else {
            $packet = wddx_serialize_value($this->data);
        }
        $dbh = dba_open("varstore", "w", "gdbm");
        dba_insert(md5(uniqid("", true)), $packet, $dbh);
        dba_close($dbh);
    }

    // a private method
    function _genID() 
    {
        return md5(uniqid(rand(), true));
    }
}

class DBStorage {
    var $data;
    var $dbtype = "mysql";

    function DBStorage($data) 
    {
        $this->data = $data;
    }

    function save() 
    {
        $dbh = mysql_connect();
        mysql_select_db("storage", $dbh);
        $serdata = serialize($this->data);
        mysql_query("insert into vars ('$serdata',now())", $dbh);
        mysql_close($dbh);
    }
}

?>

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Esempio 4. test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr) 
{
    foreach ($arr as $k => $v)
        $out[] = "\t$k => $v";
    return implode("\n", $out);
}

function object_info($obj) 
{
    $out[] = "Class: " . get_class($obj);
    foreach (get_object_vars($obj) as $var=>$val) {
        if (is_array($val)) {
            $out[] = "property: $var (array)\n" . p_arr($val);
        } else {
            $out[] = "property: $var = $val";
        }
    }
    foreach (get_class_methods($obj) as $method) {
        $out[] = "method: $method";
    }
    return implode("\n", $out);
}


$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs) . "\n";
echo "\n\$ws object\n";
echo object_info($ws) . "\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

?>

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The 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.

Sommario
aggregate_info --  Returns an associative array of the methods and properties from each class that has been aggregated to the object
aggregate_methods_by_list --  Selective dynamic class methods aggregation to an object
aggregate_methods_by_regexp --  Selective class methods aggregation to an object using a regular expression
aggregate_methods --  Dynamic class and object aggregation of methods
aggregate_properties_by_list --  Selective dynamic class properties aggregation to an object
aggregate_properties_by_regexp --  Selective class properties aggregation to an object using a regular expression
aggregate_properties --  Dynamic aggregation of class properties to an object
aggregate --  Dynamic class and object aggregation of methods and properties
aggregation_info -- Alias di aggregate_info()
deaggregate --  Removes the aggregated methods and properties from an object

aggregate_info

(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 object

Description

array aggregate_info ( object object )

Will 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()

<?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable) 
    {
        $this->vegetable = $vegetable;
    }

    function slice_it($num_cuts) 
    {
        echo "Doing some simple slicing\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable) 
    {
        $this->vegetable = $vegetable;
    }

    function dice_it($num_cuts) 
    {
        echo "Cutting in one direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some cutting
        }
        $this->rotate($this->rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg) 
    {
        echo "Now rotating {$this->vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts) 
    {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?>

Will produce the output

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)
As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list --  Selective dynamic class methods aggregation to an object

Description

void aggregate_methods_by_list ( object object, string class_name, array methods_list [, bool exclude] )

Aggregates 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()

aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp --  Selective class methods aggregation to an object using a regular expression

Description

void aggregate_methods_by_regexp ( object object, string class_name, string regexp [, bool exclude] )

Aggregates 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()

aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods --  Dynamic class and object aggregation of methods

Description

void aggregate_methods ( object object, string class_name )

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_info(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list --  Selective dynamic class properties aggregation to an object

Description

void aggregate_properties_by_list ( object object, string class_name, array properties_list [, bool exclude] )

Aggregates 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()

aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp --  Selective class properties aggregation to an object using a regular expression

Description

void aggregate_properties_by_regexp ( object object, string class_name, string regexp [, bool exclude] )

Aggregates 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()

aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties --  Dynamic aggregation of class properties to an object

Description

void aggregate_properties ( object object, string class_name )

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate

(PHP 4 >= 4.2.0)

aggregate --  Dynamic class and object aggregation of methods and properties

Description

void aggregate ( object object, string class_name )

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

See also aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregation_info

(PHP 4 >= 4.2.0)

aggregation_info -- Alias di aggregate_info()

Descrizione

This function is an alias of: aggregate_info().

deaggregate

(PHP 4 >= 4.2.0)

deaggregate --  Removes the aggregated methods and properties from an object

Description

void deaggregate ( object object [, string class_name] )

Removes the methods and properties from classes that were aggregated to an object. If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info()

XCIV. Proprietà object e method call overloading

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Alcuni semplici esempi sull'uso della funzione overload()

Esempio 1. Overloading di una classe PHP

<?php

class OO {
    var $a = 111;
    var $elem = array('b' => 9, 'c' => 42);

    // Callback method for getting a property
    function __get($prop_name, &$prop_value)
    {
        if (isset($this->elem[$prop_name])) {
            $prop_value = $this->elem[$prop_name];
            return true;
        } else {
            return false;
        }
    }

    // Callback method for setting a property
    function __set($prop_name, $prop_value)
    {
        $this->elem[$prop_name] = $prop_value;
        return true;
    }
}

// Here we overload the OO object
overload('OO');

$o = new OO;
echo "\$o->a: $o->a\n"; // print: $o->a:
echo "\$o->b: $o->b\n"; // print: $o->b: 9
echo "\$o->c: $o->c\n"; // print: $o->c: 42
echo "\$o->d: $o->d\n"; // print: $o->d:

// add a new item to the $elem array in OO
$o->x = 56; 

// instantiate stdclass (it is built-in in PHP 4)
// $val is not overloaded!
$val = new stdclass;
$val->prop = 555;

// Set "a" to be an array with the $val object in it
// But __set() will put this in the $elem array
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

Sommario
overload -- Abilita le proprietà e il method call overloading per una classe

overload

(PHP 4 >= 4.2.0)

overload -- Abilita le proprietà e il method call overloading per una classe

Descrizione

void overload ( [string class_name] )

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..

XCV. Funzioni Oracle 8

Introduzione

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;


Requisiti

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:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

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.


Installazione

Si deve compilare PHP con l'opzione --with-oci8[=DIR], dove DIR è di default il contenuto della variabile di ambiente ORACLE_HOME.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

OCI_DEFAULT (integer)

Modalità di esecuzione dello statement. Non viene eseguito il commit automatico utilizzando questa modalità.

OCI_DESCRIBE_ONLY (integer)

Modalità di esecuzione dello statement. Utilizzare questa modalità se non si vuole eseguire la query, ma solamente ricevere la descrizione della select list.

OCI_COMMIT_ON_SUCCESS (integer)

Modalità di esecuzione dello statement. Vene eseguito automaticamente il commit dello statement dopo la chiamata della oci_execute().

OCI_EXACT_FETCH (integer)

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.

OCI_SYSDATE (integer)

OCI_B_BFILE (integer)

Utilizzato con oci_bind_by_name() quando si collegano i BFILE.

OCI_B_CFILEE (integer)

Utilizzato con oci_bind_by_name() quando si collegano i CFILE.

OCI_B_CLOB (integer)

Utilizzato con oci_bind_by_name() quando si collegano i CLOB.

OCI_B_BLOB (integer)

Utilizzato con oci_bind_by_name() quando si collegano i BLOB.

OCI_B_ROWID (integer)

Utilizzato con oci_bind_by_name() quando si collegano i ROWID.

OCI_B_CURSOR (integer)

Utilizzato con oci_bind_by_name() quando si collegano i cursori, precedentemente allocati con oci_new_descriptor().

OCI_B_NTY (integer)

Utilizzato con oci_bind_by_name() quando si collegano i named data type.

OCI_B_BIN (integer)

SQLT_BFILEE (integer)

Alias di OCI_B_BFILE.

SQLT_CFILEE (integer)

Alias di OCI_B_CFILEE.

SQLT_CLOB (integer)

Alias di OCI_B_CLOB.

SQLT_BLOB (integer)

Alias di OCI_B_BLOB.

SQLT_RDD (integer)

Alias di OCI_B_ROWID.

SQLT_NTY (integer)

Alias di OCI_B_NTY.

OCI_FETCHSTATEMENT_BY_COLUMN (integer)

Modalità di default di oci_fetch_all().

OCI_FETCHSTATEMENT_BY_ROW (integer)

Modalità alternativa di oci_fetch_all().

OCI_ASSOC (integer)

Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array associative come risultato.

OCI_NUM (integer)

Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array enumerativo come risultato.

OCI_BOTH (integer)

Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array con indici sia associativi che numerici.

OCI_RETURN_NULLS (integer)

Utilizzato con oci_fetch_array() per ottenere elementi dell'array vuoti se il valore del campo è NULL.

OCI_RETURN_LOBS (integer)

Utilizzato con oci_fetch_array() per ottenere il valore del LOB invece del suo descrittore.

OCI_DTYPE_FILE (integer)

Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di FILE.

OCI_DTYPE_LOB (integer)

Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di LOB.

OCI_DTYPE_ROWID (integer)

Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di ROWID.

OCI_D_FILE (integer)

Alias di OCI_DTYPE_FILE.

OCI_D_LOB (integer)

Alias di OCI_DTYPE_LOB.

OCI_D_ROWID (integer)

Alias di OCI_DTYPE_ROWID.


Esempi

Esempio 1. Trucchi OCI

<?php
// by sergo at bacup dot ru

// Usare l'opzione OCI_DEFAULT nel comando execute per ritardare l'esicuzione
OCIExecute($stmt, OCI_DEFAULT);

// per ricevere i dati utilizzare (dopo il fetch):

$result = OCIResult($stmt, $n);
if (is_object($result)) $result = $result->load();

// come comandi INSERT o UPDATE usare:

$sql = "insert into table (field1, field2) values (field1 = 'value',
 field2 = empty_clob()) returning field2 into :field2";
OCIParse($conn, $sql);
$clob = OCINewDescriptor($conn, OCI_D_LOB);
OCIBindByName($stmt, ":field2", &$clob, -1, OCI_B_CLOB);
OCIExecute($stmt, OCI_DEFAULT);
$clob->save("some text");
OCICommit($conn);

?>

You can easily access stored procedures in the same way as you would from the commands line.

Esempio 2. Using Stored Procedures

<?php
// by webmaster at remoterealty dot com
$sth = OCIParse($dbh, "begin sp_newaddress( :address_id, '$firstname',
 '$lastname', '$company', '$address1', '$address2', '$city', '$state',
 '$postalcode', '$country', :error_code );end;");

// Questo codice richiama la stored procedure sp_newaddress, dove :address_id è
// una variabile in/out e :error_code è una variabile out.
// Quindi si effettua il binding:

   OCIBindByName($sth, ":address_id", $addr_id, 10);
   OCIBindByName($sth, ":error_code", $errorcode, 10);
   OCIExecute($sth);

?>

Sommario
OCI-Collection->append -- Appends element to the collection
OCI-Collection->assign -- Assigns a value to the collection from another existing collection
OCI-Collection->assignElem -- Assigns a value to the element of the collection
OCI-Collection->free -- Frees the resources associated with the collection object
OCI-Collection->getElem -- Returns value of the element
OCI-Collection->max -- Returns the maximum number of elements in the collection
OCI-Collection->size -- Returns size of the collection
OCI-Collection->trim -- Trims elements from the end of the collection
OCI-Lob->append -- Appends data from the large object to another large object
OCI-Lob->close -- Closes LOB descriptor
OCI-Lob->eof -- Tests for end-of-file on a large object's descriptor
OCI-Lob->erase -- Erases a specified portion of the internal LOB data
OCI-Lob->export -- Exports LOB's contents to a file
OCI-Lob->flush -- Flushes/writes buffer of the LOB to the server
OCI-Lob->free -- Frees resources associated with the LOB descriptor
OCI-Lob->getBuffering -- Returns current state of buffering for the large object
OCI-Lob->import -- Imports file data to the LOB
OCI-Lob->load -- Returns large object's contents
OCI-Lob->read -- Reads part of the large object
OCI-Lob->rewind -- Moves the internal pointer to the beginning of the large object
OCI-Lob->save -- Saves data to the large object
OCI-Lob->saveFile -- Alias di oci_lob_import()
OCI-Lob->seek -- Sets the internal pointer of the large object
OCI-Lob->setBuffering -- Changes current state of buffering for the large object
OCI-Lob->size -- Returns size of large object
OCI-Lob->tell -- Returns current position of internal pointer of large object
OCI-Lob->truncate -- Truncates large object
OCI-Lob->write -- Writes data to the large object
OCI-Lob->writeTemporary -- Writes temporary large object
OCI-Lob->writeToFile -- Alias di oci_lob_export()
oci_bind_by_name --  Lega una variabile PHP ad un segnaposto Oracle
oci_cancel -- Interrompe la lettura del cursore
oci_close -- Closes Oracle connection
oci_commit -- Commits outstanding statements
oci_connect -- Establishes a connection to the Oracle server
oci_define_by_name --  Uses a PHP variable for the define-step during a SELECT
oci_error -- Returns the last error found
oci_execute -- Executes a statement
oci_fetch_all -- Fetches all rows of result data into an array
oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or both
oci_fetch_assoc -- Returns the next row from the result data as an associative array
oci_fetch_object -- Returns the next row from the result data as an object
oci_fetch_row -- Returns the next row from the result data as a numeric array
oci_fetch -- Fetches the next row into result-buffer
oci_field_is_null -- Checks if the field is NULL
oci_field_name -- Returns the name of a field from the statement
oci_field_precision -- Tell the precision of a field
oci_field_scale -- Tell the scale of the field
oci_field_size -- Returns field's size
oci_field_type_raw -- Tell the raw Oracle data type of the field
oci_field_type -- Returns field's data type
oci_free_statement --  Frees all resources associated with statement or cursor
oci_internal_debug -- Enables or disables internal debug output
oci_lob_copy -- Copies large object
oci_lob_is_equal -- Compares two LOB/FILE locators for equality
oci_new_collection -- Allocates new collection object
oci_new_connect -- Establishes a new connection to the Oracle server
oci_new_cursor -- Allocates and returns a new cursor (statement handle)
oci_new_descriptor -- Initializes a new empty LOB or FILE descriptor
oci_num_fields --  Returns the number of result columns in a statement
oci_num_rows -- Returns number of rows affected during statement execution
oci_parse -- Prepares Oracle statement for execution
oci_password_change -- Changes password of Oracle's user
oci_pconnect -- Connect to an Oracle database using a persistent connection
oci_result -- Returns field's value from the fetched row
oci_rollback -- Rolls back outstanding transaction
oci_server_version -- Returns server version
oci_set_prefetch -- Sets number of rows to be prefetched
oci_statement_type -- Returns the type of an OCI statement
ocibindbyname -- Alias di oci_bind_by_name()
ocicancel -- Interrompe la lettura del cursore
ocicloselob -- Alias di OCI-Lob->close
ocicollappend -- Aggiunge un oggetto alla collezione
ocicollassign -- Assegna una collezione da un'altra collezione esistente
ocicollassignelem -- Assegna un elemento alla collezione in una specifica posizione
ocicollgetelem -- Coming soon
ocicollmax -- Coming soon
ocicollsize -- Coming soon
ocicolltrim -- Coming soon
ocicolumnisnull -- Verifica se un campo di risultato è NULL
ocicolumnname -- Restituisce il nome di un campo
ocicolumnprecision -- Coming soon
ocicolumnscale -- Coming soon
ocicolumnsize -- Restituisce la dimensione del campo
ocicolumntype -- Restituisce il tipo di dati di un campo
ocicolumntyperaw -- Coming soon
OCICommit -- Esegue le transazioni in sospeso
OCIDefineByName --  Utilizza una variabile PHP per la fase di definizione in un comando SELECT
OCIError -- Restituisce l'ultimo errore di stmt|conn|global
ociexecute -- Esegue un comando SQL
ocifetch -- Estrae la prossima tupla opnendola nel buffer di risultato.
ocifetchinto -- Estrae la prossima tupla ponendola in un array
ocifetchstatement -- Estrae tutte le tuple in un array
ocifreecollection -- Coming soon
ocifreecursor --  Libera tutte le risorse associate ad un cursore
ocifreedesc -- Cancella un descrittore di oggetto binario (LOB)
ocifreestatement --  Libera tutte le risorse associate ad un'istruzione
ociinternaldebug --  Abilita o disabilita la visualizzazione del debug interno.
ociloadlob -- Coming soon
ocilogoff -- Disconnette da Oracle
ocilogon -- Stabilisce una connessione a Oracle
ocinewcollection -- Coming soon
ocinewcursor --  Restituisce un nuovo cursore (Statement-Handle)
ocinewdescriptor --  Inizializza un nuovo descrittore LOB/FILE vuoto
ocinlogon -- Stabilisce, una nuova connessione a Oracle.
ocinumcols --  Restituisce il numero di campi che risultano da un comando SQL
ociparse -- Analizza una query e restituisce un'istruzione.
ociplogon --  Stabilisce una connessione permanente a Oracle.
ociresult -- Restituisce il valore di campo della tupla estratta
ocirollback -- Annulla le transazioni in sospeso
ocirowcount -- Restituisce il numero di tuple modificate
ocisavelob -- Coming soon
ocisavelobfile -- Coming soon
ociserverversion -- Restituisce una stringa contenente informazioni sulla versione del server
ocisetprefetch -- Imposta il numero di tuple da precaricare
ocistatementtype -- Restituisce il tipo di un'istruzione OCI
ociwritelobtofile -- Coming soon
ociwritetemporarylob -- Alias di OCI-Lob->writeTemporary

OCI-Collection->append

(no version information, might be only in CVS)

OCI-Collection->append -- Appends element to the collection

Descrizione

class OCI-Collection {

bool append ( mixed value )

}

Appends 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.

Elenco dei parametri

value

The value to be added to the collection.

Vedere anche:

OCI-Collection->assign

OCI-Collection->assign

(no version information, might be only in CVS)

OCI-Collection->assign -- Assigns a value to the collection from another existing collection

Descrizione

class OCI-Collection {

bool assign ( OCI-Collection from )

}

Assigns 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.

Elenco dei parametri

from

An instance of OCI-Collection.

Vedere anche:

OCI-Collection->append

OCI-Collection->assignElem

(no version information, might be only in CVS)

OCI-Collection->assignElem -- Assigns a value to the element of the collection

Descrizione

class OCI-Collection {

bool assignElem ( int index, mixed value )

}

Assigns 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.

Elenco dei parametri

index

value

OCI-Collection->free

(no version information, might be only in CVS)

OCI-Collection->free -- Frees the resources associated with the collection object

Descrizione

class OCI-Collection {

bool free ( void )

}

Frees the resources associated with the collection object.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

oci_new_collection

OCI-Collection->getElem

(no version information, might be only in CVS)

OCI-Collection->getElem -- Returns value of the element

Descrizione

class OCI-Collection {

mixed getElem ( int index )

}

Returns 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.

Elenco dei parametri

index

OCI-Collection->max

(no version information, might be only in CVS)

OCI-Collection->max -- Returns the maximum number of elements in the collection

Descrizione

class OCI-Collection {

int max ( void )

}

Returns 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.

Vedere anche:

OCI-Collection->size

OCI-Collection->size

(no version information, might be only in CVS)

OCI-Collection->size -- Returns size of the collection

Descrizione

class OCI-Collection {

int size ( void )

}

Returns the number of elements in the collection or FALSE on error.

Vedere anche:

OCI-Collection->max

OCI-Collection->trim

(no version information, might be only in CVS)

OCI-Collection->trim -- Trims elements from the end of the collection

Descrizione

class OCI-Collection {

bool trim ( int num )

}

Trims num of elements from the end of the collection.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Elenco dei parametri

num

Vedere anche:

OCI-Collection->size

OCI-Lob->append

(no version information, might be only in CVS)

OCI-Lob->append -- Appends data from the large object to another large object

Descrizione

class OCI-Lob {

bool append ( OCI-Lob lob_from )

}

Appends 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.

Elenco dei parametri

lob_from

OCI-Lob->close

(no version information, might be only in CVS)

OCI-Lob->close -- Closes LOB descriptor

Descrizione

class OCI-Lob {

bool close ( void )

}

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.

OCI-Lob->eof

(no version information, might be only in CVS)

OCI-Lob->eof -- Tests for end-of-file on a large object's descriptor

Descrizione

class OCI-Lob {

bool eof ( void )

}

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

Vedere anche:

OCI-Lob->size

OCI-Lob->erase

(no version information, might be only in CVS)

OCI-Lob->erase -- Erases a specified portion of the internal LOB data

Descrizione

class OCI-Lob {

int erase ( [int offset [, int length]] )

}

Erases 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.

Elenco dei parametri

offset

length

Vedere anche:

OCI-Lob->truncate

OCI-Lob->export

(no version information, might be only in CVS)

OCI-Lob->export -- Exports LOB's contents to a file

Descrizione

class OCI-Lob {

bool export ( string filename [, int start [, int length]] )

}

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.

Elenco dei parametri

filename

start

length

Vedere anche:

OCI-Lob->import

OCI-Lob->flush

(no version information, might be only in CVS)

OCI-Lob->flush -- Flushes/writes buffer of the LOB to the server

Descrizione

class OCI-Lob {

bool flush ( [int flag] )

}

OCI-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.

Elenco dei parametri

flag

OCI-Lob->free

(no version information, might be only in CVS)

OCI-Lob->free -- Frees resources associated with the LOB descriptor

Descrizione

class OCI-Lob {

bool free ( void )

}

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

OCI-Lob->getBuffering

(no version information, might be only in CVS)

OCI-Lob->getBuffering -- Returns current state of buffering for the large object

Descrizione

class OCI-Lob {

bool getBuffering ( void )

}

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

Vedere anche:

OCI-Lob->setBuffering

OCI-Lob->import

(no version information, might be only in CVS)

OCI-Lob->import -- Imports file data to the LOB

Descrizione

class OCI-Lob {

bool import ( string filename )

}

Writes data from the filename in to the current position of large object.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Elenco dei parametri

filename

OCI-Lob->load

(no version information, might be only in CVS)

OCI-Lob->load -- Returns large object's contents

Descrizione

class OCI-Lob {

string load ( void )

}

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.

Vedere anche:

OCI-Lob->read

OCI-Lob->read

(no version information, might be only in CVS)

OCI-Lob->read -- Reads part of the large object

Descrizione

class OCI-Lob {

string read ( int length )

}

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.

Elenco dei parametri

length

OCI-Lob->rewind

(no version information, might be only in CVS)

OCI-Lob->rewind -- Moves the internal pointer to the beginning of the large object

Descrizione

class OCI-Lob {

bool rewind ( void )

}

Sets the internal pointer to the beginning of the large object.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

OCI-Lob->save

(no version information, might be only in CVS)

OCI-Lob->save -- Saves data to the large object

Descrizione

class OCI-Lob {

bool save ( string data [, int offset] )

}

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.

Elenco dei parametri

data

offset

OCI-Lob->saveFile

(no version information, might be only in CVS)

OCI-Lob->saveFile -- Alias di oci_lob_import()

Descrizione

This function is an alias of: oci_lob_import().

OCI-Lob->seek

(no version information, might be only in CVS)

OCI-Lob->seek -- Sets the internal pointer of the large object

Descrizione

class OCI-Lob {

bool seek ( int offset [, int whence] )

}

Sets 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.

Elenco dei parametri

offset

whence

OCI-Lob->setBuffering

(no version information, might be only in CVS)

OCI-Lob->setBuffering -- Changes current state of buffering for the large object

Descrizione

class OCI-Lob {

bool setBuffering ( bool on_off )

}

lob->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.

Elenco dei parametri

on_off

Vedere anche:

OCI-Lob->getBuffering

OCI-Lob->size

(no version information, might be only in CVS)

OCI-Lob->size -- Returns size of large object

Descrizione

class OCI-Lob {

int size ( void )

}

Returns length of large object value or FALSE in case of error. Empty objects have zero length.

OCI-Lob->tell

(no version information, might be only in CVS)

OCI-Lob->tell -- Returns current position of internal pointer of large object

Descrizione

class OCI-Lob {

int tell ( void )

}

Returns current position of a LOB's internal pointer or FALSE if an error occurred.

OCI-Lob->truncate

(no version information, might be only in CVS)

OCI-Lob->truncate -- Truncates large object

Descrizione

class OCI-Lob {

bool truncate ( [int length] )

}

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.

Elenco dei parametri

length

Vedere anche:

OCI-Lob->erase

OCI-Lob->write

(no version information, might be only in CVS)

OCI-Lob->write -- Writes data to the large object

Descrizione

class OCI-Lob {

int write ( string data [, int length] )

}

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.

Elenco dei parametri

data

length

Vedere anche:

OCI-Lob->read

OCI-Lob->writeTemporary

(no version information, might be only in CVS)

OCI-Lob->writeTemporary -- Writes temporary large object

Descrizione

class OCI-Lob {

bool writeTemporary ( string data [, int lob_type] )

}

Creates 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.

Elenco dei parametri

lob_type

Vedere anche:

OCI-Lob->close

OCI-Lob->writeToFile

(no version information, might be only in CVS)

OCI-Lob->writeToFile -- Alias di oci_lob_export()

Descrizione

This function is an alias of: oci_lob_export().

oci_bind_by_name

(PHP 5)

oci_bind_by_name --  Lega una variabile PHP ad un segnaposto Oracle

Descrizione

bool oci_bind_by_name ( resource stmt, string nome_ph, mixed &variabile [, int lungmax [, int tipo]] )

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()

<?php
/* esempio di oci_bind_by_name thies at thieso dot net (980221)
  inserisce 3 tuple in emp, e usa ROWID per aggiornare le
  tuple subito dopo l'inserimento.
*/

$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "
                          INSERT INTO 
                                     emp (empno, ename) 
                                              VALUES 
                                     (:empno,:ename) 
                            RETURNING 
                                     ROWID 
                                 INTO 
                                     :rid
                                         ");

$data = array(
              1111 => "Larry", 
              2222 => "Bill", 
              3333 => "Jim"
             );

$rowid = oci_new_descriptor($conn, OCI_D_ROWID);

oci_bind_by_name($stmt, ":empno", $empno, 32);
oci_bind_by_name($stmt, ":ename", $ename, 32);
oci_bind_by_name($stmt, ":rid",   $rowid, -1, OCI_B_ROWID);

$update = oci_parse($conn, "
                            UPDATE
                                  emp 
                               SET 
                                  sal = :sal 
                             WHERE 
                                  ROWID = :rid
                             ");
oci_bind_by_name($update, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($update, ":sal", $sal,   32);

$sal = 10000;

while (list($empno, $ename) = each($data)) {
    oci_execute($stmt);
 oci_execute($update);
} 

$rowid->free();

oci_free_statement($update);
oci_free_statement($stmt);

$stmt = oci_parse($conn, "
                          SELECT 
                                * 
                            FROM 
                                emp 
                           WHERE 
                                empno 
                              IN 
                                (1111,2222,3333)
                              ");
oci_execute($stmt);
                              
while ($row = oci_fetch_assoc($stmt)) {
    var_dump($row);
}

oci_free_statement($stmt);

/* delete our "junk" from the emp table.... */
$stmt = oci_parse($conn, "
                          DELETE FROM
                                     emp 
                                WHERE 
                                     empno 
                                   IN 
                                     (1111,2222,3333)
                                   ");
oci_execute($stmt);
oci_free_statement($stmt);

oci_close($conn);
?>

Ricordarsi che questa funzione elimina gli spazi alla fine della riga. Vedere il seguente esempio:

Esempio 2. esempio di oci_bind_by_name()

<?php
    $connection = oci_connect('apelsin','kanistra');
    $query = "INSERT INTO test_table VALUES(:id, :text)";

    $statement = oci_parse($query);
    oci_bind_by_name($statement, ":id", 1);
    oci_bind_by_name($statement, ":text", "Qui ci sono degli spazi     ");
    oci_execute($statement);
    /*
     Questo codice inserisce nel DB la stringa 'Qui ci sono degli spazi', senza
     gli spazi finali
    */
?>

Esempio 3. esempio di oci_bind_by_name()

<?php
    $connection = oci_connect('apelsin','kanistra');
    $query = "INSERT INTO test_table VALUES(:id, 'Qui ci sono degli spazi      ')";

    $statement = oci_parse($query);
    oci_bind_by_name($statement, ":id", 1);
    oci_execute($statement);
    /*
     Questo codice aggiunge 'Qui ci sono degli spazi      ', mantenendo
     gli spazi 
    */
?>

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

(PHP 5)

oci_cancel -- Interrompe la lettura del cursore

Descrizione

bool oci_cancel ( resource stmt )

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

(PHP 5)

oci_close -- Closes Oracle connection

Description

bool oci_close ( resource connection )

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

(PHP 5)

oci_commit -- Commits outstanding statements

Description

bool oci_commit ( resource connection )

oci_commit() commits all outstanding statements for the active transaction on the Oracle connection connection.

Esempio 1. oci_commit() example

<?php
    // Login to Oracle server
    $conn = oci_connect('scott', 'tiger');
     
    // Parse SQL
    $stmt = oci_parse($conn, "
                              INSERT INTO 
                                         employees (name, surname) 
                                   VALUES 
                                         ('Maxim', 'Maletsky')
                             ");

    /* Execute statement
       OCI_DEFAULT tells oci_execute() 
       not to commit statement immediately */
    oci_execute($stmt, OCI_DEFAULT);

    /*
    ....
    Parsing and executing other statements here ...
    ....
    */
    
    // Commit transaction
    $committed = oci_commit($conn);

    // Test whether commit was successful. If error occurred, return error message
    if (!$committed) {
        $error = oci_error($conn);
        echo 'Commit failed. Oracle reports: ' . $error['message'];
    }

?>

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

(PHP 5)

oci_connect -- Establishes a connection to the Oracle server

Description

resource oci_connect ( string username, string password [, string db [, string charset [, int session_mode]]] )

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

<?php
echo "<pre>";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_connect("scott", "tiger", $db);

function create_table($conn) 
{
  $stmt = oci_parse($conn, "create table scott.hallo (test varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn) 
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn) 
{
  $stmt = oci_parse($conn, "insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn) 
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn) 
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn) 
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn) 
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " [" . oci_result($stmt, "TEST") . "]\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);   // Insert a row using c1
insert_data($c2);   // Insert a row using c2

select_data($c1);   // Results of both inserts are returned
select_data($c2);   

rollback($c1);      // Rollback using c1

select_data($c1);   // Both inserts have been rolled back
select_data($c2);   

insert_data($c2);   // Insert a row using c2
commit($c2);        // Commit using c2

select_data($c1);   // Result of c2 insert is returned

delete_data($c1);   // Delete all rows in table using c1
select_data($c1);   // No rows returned
select_data($c2);   // No rows returned
commit($c1);        // Commit using c1

select_data($c1);   // No rows returned
select_data($c2);   // No rows returned

drop_table($c1);
echo "</pre>";
?>

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

(PHP 5)

oci_define_by_name --  Uses a PHP variable for the define-step during a SELECT

Description

bool oci_define_by_name ( resource statement, string column_name, mixed &variable [, int type] )

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

<?php
/* oci_define_by_name example - thies at thieso dot net (980219) */

$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "SELECT empno, ename FROM emp");

/* the define MUST be done BEFORE oci_execute! */

oci_define_by_name($stmt, "EMPNO", $empno);
oci_define_by_name($stmt, "ENAME", $ename);

oci_execute($stmt);

while (oci_fetch($stmt)) {
    echo "empno:" . $empno . "\n";
    echo "ename:" . $ename . "\n";
}

oci_free_statement($stmt);
oci_close($conn);
?>

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.

oci_error

(PHP 5)

oci_error -- Returns the last error found

Description

array oci_error ( [resource source] )

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 1. Displaying the Oracle error message after a connection error

$conn = @oci_connect("scott", "tiger", "mydb");
if (!$conn) {
  $e = oci_error();   // For oci_connect errors pass no handle
  echo htmlentities($e['message']);
}

Esempio 2. Displaying the Oracle error message after a parsing error

$stmt = @oci_parse($conn, "select ' from dual");  // note mismatched quote
if (!$stmt) {
  $e = oci_error($conn);  // For oci_parse errors pass the connection handle
  echo htmlentities($e['message']);
}

Esempio 3. Displaying the Oracle error message and problematic statement after an execution error

$r = oci_execute($stmt);
if (!$r) {
  $e = oci_error($stmt); // For oci_execute errors pass the statementhandle
  echo htmlentities($e['message']);
  echo "<pre>";
  echo htmlentities($e['sqltext']);
  printf("\n%".($e['offset']+1)."s", "^");
  echo "</pre>";
}

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

(PHP 5)

oci_execute -- Executes a statement

Description

bool oci_execute ( resource stmt [, int mode] )

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

(PHP 5)

oci_fetch_all -- Fetches all rows of result data into an array

Description

int oci_fetch_all ( resource statement, array &output [, int skip [, int maxrows [, int flags]]] )

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

<?php
/* oci_fetch_all example mbritton at verinet dot com (990624) */

$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "select * from emp");

oci_execute($stmt);

$nrows = oci_fetch_all($stmt, $results);
if ($nrows > 0) {
   echo "<table border=\"1\">\n";
   echo "<tr>\n";
   foreach ($results as $key => $val) {
      echo "<th>$key</th>\n";
   }
   echo "</tr>\n";
   
   for ($i = 0; $i < $nrows; $i++) {
      echo "<tr>\n";
      foreach ($results as $data) {
         echo "<td>$data[$i]</td>\n";
      }
      echo "</tr>\n";
   }
   echo "</table>\n";
} else {
   echo "No data found<br />\n";
}      
echo "$nrows Records Selected<br />\n";
 
oci_free_statement($stmt);
oci_close($conn);
?>

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.

oci_fetch_array

(PHP 5)

oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or both

Description

array oci_fetch_array ( resource statement [, int mode] )

Returns 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.

Default mode is OCI_BOTH.

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

<?php
$connection = oci_connect("apelsin", "kanistra");

$query = "SELECT id, name FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_BOTH)) {
    echo $row[0]." and ".$row['ID']." is the same<br>";
    echo $row[1]." and ".$row['NAME']." is the same<br>";
}
?>

Esempio 2. oci_fetch_array() with OCI_NUM example

<?php
$connection = oci_connect("user", "password");

$query = "SELECT id, name, lob_field FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_NUM)) {
    echo $row[0]."<br>";
    echo $row[1]."<br>";
    echo $row[2]->read(100)."<br>";  //this will output first 100 bytes from LOB
}
?>

Esempio 3. oci_fetch_array() with OCI_ASSOC example

<?php
$connection = oci_connect("user", "password");

$query = "SELECT id, name, lob_field FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_NUM)) {
    echo $row['ID']."<br>";
    echo $row['NAME']."<br>";
    echo $row['LOB_FIELD']."<br>";  //this will output "Object id #1"
}
?>

Esempio 4. oci_fetch_array() with OCI_RETURN_LOBS example

<?php
$connection = oci_connect("user", "password");

$query = "SELECT id, name, lob_field FROM fruits";

$statement = oci_parse ($connection, $query);
oci_execute ($statement);

while ($row = oci_fetch_array ($statement, OCI_NUM)) {
    echo $row[0]."<br>";
    echo $row[1]."<br>";
    echo $row['LOB_FIELD']."<br>";  //this will output LOB's content
}
?>

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

(PHP 5)

oci_fetch_assoc -- Returns the next row from the result data as an associative array

Description

array oci_fetch_assoc ( resource statement )

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

(PHP 5)

oci_fetch_object -- Returns the next row from the result data as an object

Description

object oci_fetch_object ( resource statement )

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().

oci_fetch_row

(PHP 5)

oci_fetch_row -- Returns the next row from the result data as a numeric array

Description

array oci_fetch_row ( resource statement )

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

(PHP 5)

oci_fetch -- Fetches the next row into result-buffer

Description

bool oci_fetch ( resource statement )

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

(PHP 5)

oci_field_is_null -- Checks if the field is NULL

Description

bool oci_field_is_null ( resource stmt, mixed field )

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

(PHP 5)

oci_field_name -- Returns the name of a field from the statement

Description

string oci_field_name ( resource statement, int field )

oci_field_name() returns the name of the field corresponding to the field number (1-based).

Esempio 1. oci_field_name() example

<?php   
    $conn = oci_connect("scott", "tiger");
    $stmt = oci_parse($conn, "SELECT * FROM emp");
    oci_execute($stmt);
    
    echo "<table border=\"1\">";
    echo "<tr>";
    echo "<th>Name</th>";
    echo "<th>Type</th>";
    echo "<th>Length</th>";
    echo "</tr>";
   
    $ncols = oci_num_fields($stmt);
   
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_type  = oci_field_type($stmt, $i);
        $column_size  = oci_field_size($stmt, $i);
        
        echo "<tr>";
        echo "<td>$column_name</td>";
        echo "<td>$column_type</td>";
        echo "<td>$column_size</td>";
        echo "</tr>";
    }
       
    echo "</table>\n"; 
    oci_free_statement($stmt);  
    oci_close($conn);   
?>

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().

oci_field_precision

(PHP 5)

oci_field_precision -- Tell the precision of a field

Description

int oci_field_precision ( resource statement, int field )

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().

oci_field_scale

(PHP 5)

oci_field_scale -- Tell the scale of the field

Description

int oci_field_scale ( resource statement, int field )

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

(PHP 5)

oci_field_size -- Returns field's size

Description

int oci_field_size ( resource stmt, mixed field )

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

<?php   
    $conn = oci_connect("scott", "tiger");
    $stmt = oci_parse($conn, "SELECT * FROM emp");
    oci_execute($stmt);
    
    echo "<table border=\"1\">";
    echo "<tr>";
    echo "<th>Name</th>";
    echo "<th>Type</th>";
    echo "<th>Length</th>";
    echo "</tr>";
   
    $ncols = oci_num_fields($stmt);
   
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_type  = oci_field_type($stmt, $i);
        $column_size  = oci_field_size($stmt, $i);
        echo "<tr>";
        echo "<td>$column_name</td>";
        echo "<td>$column_type</td>";
        echo "<td>$column_size</td>";
        echo "</tr>";
    }
       
    echo "</table>";
   
    oci_free_statement($stmt);  
    oci_close($conn);   
?>

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

(PHP 5)

oci_field_type_raw -- Tell the raw Oracle data type of the field

Description

int oci_field_type_raw ( resource statement, int field )

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

(PHP 5)

oci_field_type -- Returns field's data type

Description

mixed oci_field_type ( resource stmt, int field )

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

<?php   
    $conn = oci_connect("scott", "tiger");
    $stmt = oci_parse($conn, "SELECT * FROM emp");
    oci_execute($stmt);
    
    echo "<table border=\"1\">";
    echo "<tr>";
    echo "<th>Name</th>";
    echo "<th>Type</th>";
    echo "<th>Length</th>";
    echo "</tr>";
   
    $ncols = oci_num_fields($stmt);
   
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_type  = oci_field_type($stmt, $i);
        $column_size  = oci_field_size($stmt, $i);
        
        echo "<tr>";
        echo "<td>$column_name</td>";
        echo "<td>$column_type</td>";
        echo "<td>$column_size</td>";
        echo "</tr>";
    }
       
    echo "</table>\n"; 
   
    oci_free_statement($stmt);  
    oci_close($conn);   
?>

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

(PHP 5)

oci_free_statement --  Frees all resources associated with statement or cursor

Description

bool oci_free_statement ( resource statement )

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

(PHP 5)

oci_internal_debug -- Enables or disables internal debug output

Description

void oci_internal_debug ( int onoff )

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.

oci_lob_copy

(PHP 5)

oci_lob_copy -- Copies large object

Description

bool oci_lob_copy ( OCI-Lob lob_to, OCI-Lob lob_from [, int length] )

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.

oci_lob_is_equal

(PHP 5)

oci_lob_is_equal -- Compares two LOB/FILE locators for equality

Description

bool oci_lob_is_equal ( OCI-Lob lob1, OCI-Lob lob2 )

Compares two LOB/FILE locators. Returns TRUE if these objects are equal and FALSE otherwise.

oci_new_collection

(PHP 5)

oci_new_collection -- Allocates new collection object

Description

OCI-Collection oci_new_collection ( resource connection, string tdo [, string schema] )

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

(PHP 5)

oci_new_connect -- Establishes a new connection to the Oracle server

Description

resource oci_new_connect ( string username, string password [, string db [, string charset [, int session_mode]]] )

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

<?php
echo "<html><pre>";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_new_connect("scott", "tiger", $db);

function create_table($conn) 
{
  $stmt = oci_parse($conn, "create table scott.hallo (test
varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn) 
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn) 
{
  $stmt = oci_parse($conn, "insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn) 
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn) 
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn) 
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn) 
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . "----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " <" . oci_result($stmt, "TEST") . ">\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);   
select_data($c2);   

rollback($c1);      

select_data($c1);   
select_data($c2);   

insert_data($c2);   
commit($c2);        

select_data($c1);   

delete_data($c1);   
select_data($c1);   
select_data($c2);   
commit($c1);        

select_data($c1);
select_data($c2);

drop_table($c1);
echo "</pre></html>";
?>

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

(PHP 5)

oci_new_cursor -- Allocates and returns a new cursor (statement handle)

Description

resource oci_new_cursor ( resource connection )

oci_new_cursor() allocates a new statement handle on the specified connection.

Esempio 1. Using REF CURSOR in an Oracle's stored procedure

<?php   
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = oci_connect("scott", "tiger");
$curs = oci_new_cursor($conn);
$stmt = oci_parse($conn, "begin info.output(:data); end;");

oci_bind_by_name($stmt, "data", $curs, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_execute($curs);

while ($data = oci_fetch_row($curs)) {
    var_dump($data);
}
 
oci_free_statement($stmt);
oci_free_statement($curs);
oci_close($conn);
?>

Esempio 2. Using REF CURSOR in an Oracle's select statement

<?php   
echo "<html><body>";
$conn = oci_connect("scott", "tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = oci_parse($conn, "select deptno,dname,$count_cursor");

oci_execute($stmt);
echo "<table border=\"1\">";
echo "<tr>";
echo "<th>DEPT NAME</th>";
echo "<th>DEPT #</th>";
echo "<th># EMPLOYEES</th>";
echo "</tr>";

while ($data = oci_fetch_assoc($stmt)) {
    echo "<tr>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    echo "<td>$dname</td>";
    echo "<td>$deptno</td>";
    oci_execute($data["EMPCNT"]);
    while ($subdata = oci_fetch_assoc($data["EMPCNT"])) {
        $num_emps = $subdata["NUM_EMPS"];
        echo  "<td>$num_emps</td>";
    }
    echo "</tr>";
}
echo "</table>";
echo "</body></html>";
oci_free_statement($stmt);
oci_close($conn);
?>

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

(PHP 5)

oci_new_descriptor -- Initializes a new empty LOB or FILE descriptor

Description

OCI-Lob oci_new_descriptor ( resource connection [, int type] )

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

<?php   
    /* This script is designed to be called from a HTML form.
     * It expects $user, $password, $table, $where, and $commitsize
     * to be passed in from the form.  The script then deletes
     * the selected rows using the ROWID and commits after each
     * set of $commitsize rows. (Use with care, there is no rollback)
     */
    $conn = oci_connect($user, $password);
    $stmt = oci_parse($conn, "select rowid from $table $where");
    $rowid = oci_new_descriptor($conn, OCI_D_ROWID);
    oci_define_by_name($stmt, "ROWID", $rowid);   
    oci_execute($stmt);
    while (oci_fetch($stmt)) {
       $nrows = oci_num_rows($stmt);
       $delete = oci_parse($conn, "delete from $table where ROWID = :rid");
       oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
       oci_execute($delete);      
       echo "$nrows\n";
       if (($nrows % $commitsize) == 0) {
           oci_commit($conn);      
       }   
    }
    $nrows = oci_num_rows($stmt);   
    echo "$nrows deleted...\n";
    oci_free_statement($stmt);  
    oci_close($conn);
?>
<?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload" />
     * ...
     */
  if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads
     
     $conn = oci_connect($user, $password);
     $lob = oci_new_descriptor($conn, OCI_D_LOB);
     $stmt = oci_parse($conn, "insert into $table (id, the_blob) 
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
     oci_execute($stmt, OCI_DEFAULT);
     if ($lob->savefile($lob_upload)){
        oci_commit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     oci_free_descriptor($lob);
     oci_free_statement($stmt);
     oci_close($conn);
  }
?>

Esempio 2. oci_new_descriptor() example

<?php   
    /* Calling PL/SQL stored procedures which contain clobs as input
     * parameters (PHP 4 >= 4.0.6). 
     * Example PL/SQL stored procedure signature is:
     *
     * PROCEDURE save_data
     *   Argument Name                  Type                    In/Out Default?
     *   ------------------------------ ----------------------- ------ --------
     *   KEY                            NUMBER(38)              IN
     *   DATA                           CLOB                    IN
     *
     */

    $conn = oci_connect($user, $password);
    $stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
    $clob = oci_new_descriptor($conn, OCI_D_LOB);
    oci_bind_by_name($stmt, ':key', $key);
    oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
    $clob->write($data);
    oci_execute($stmt, OCI_DEFAULT);
    oci_commit($conn);
    $clob->free();
    oci_free_statement($stmt);
?>

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

(PHP 5)

oci_num_fields --  Returns the number of result columns in a statement

Description

int oci_num_fields ( resource statement )

oci_num_fields() returns the number of columns in the statement.

Esempio 1. oci_num_fields() example

<?php   
    echo "<pre>\n";   
    $conn = oci_connect("scott", "tiger");
    $stmt = oci_parse($conn, "select * from emp");
    
    oci_execute($stmt);
    
    while (oci_fetch($stmt)) {
        echo "\n";   
        $ncols = oci_num_fields($stmt);
        for ($i = 1; $i <= $ncols; $i++) {
            $column_name  = oci_field_name($stmt, $i);
            $column_value = oci_result($stmt, $i);
            echo $column_name . ': ' . $column_value . "\n";
        }
        echo "\n";
    }
    
    oci_free_statement($stmt);  
    oci_close($conn);   
    
    echo "</pre>";
?>

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

(PHP 5)

oci_num_rows -- Returns number of rows affected during statement execution

Description

int oci_num_rows ( resource stmt )

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

<?php
    echo "<pre>";
    $conn = oci_connect("scott", "tiger");
     
    $stmt = oci_parse($conn, "create table emp2 as select * from emp");
    oci_execute($stmt);
    echo oci_num_rows($stmt) . " rows inserted.<br />";
    oci_free_statement($stmt);
    
    $stmt = oci_parse($conn, "delete from emp2");
    oci_execute($stmt, OCI_DEFAULT);
    echo oci_num_rows($stmt) . " rows deleted.<br />";
    oci_commit($conn);
    oci_free_statement($stmt);
    
    $stmt = oci_parse($conn, "drop table emp2");
    oci_execute($stmt);
    oci_free_statement($stmt);
    
    oci_close($conn);
    echo "</pre>";
?>

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

(PHP 5)

oci_parse -- Prepares Oracle statement for execution

Description

resource oci_parse ( resource connection, string query )

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.

oci_password_change

(PHP 5)

oci_password_change -- Changes password of Oracle's user

Description

bool oci_password_change ( resource connection, string username, string old_password, string new_password )

resource oci_password_change ( string dbname, string username, string old_password, string new_password )

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

(PHP 5)

oci_pconnect -- Connect to an Oracle database using a persistent connection

Description

resource oci_pconnect ( string username, string password [, string db [, string charset [, int session_mode]]] )

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

(PHP 5)

oci_result -- Returns field's value from the fetched row

Description

mixed oci_result ( resource statement, mixed field )

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

(PHP 5)

oci_rollback -- Rolls back outstanding transaction

Description

bool oci_rollback ( resource connection )

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().

oci_server_version

(PHP 5)

oci_server_version -- Returns server version

Description

string oci_server_version ( resource connection )

Returns a string with version information of the Oracle server, which uses connection connection or returns FALSE on error.

Esempio 1. oci_server_version() example

<?php
    $conn = oci_connect("scott", "tiger");
    echo "Server Version: " . oci_server_version($conn);
    oci_close($conn);
?>

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.

oci_set_prefetch

(PHP 5)

oci_set_prefetch -- Sets number of rows to be prefetched

Description

bool oci_set_prefetch ( resource statement [, int rows] )

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

(PHP 5)

oci_statement_type -- Returns the type of an OCI statement

Description

string oci_statement_type ( resource statement )

oci_statement_type() returns the query type of statement statement as one of the following values:

  1. SELECT

  2. UPDATE

  3. DELETE

  4. INSERT

  5. CREATE

  6. DROP

  7. ALTER

  8. BEGIN

  9. DECLARE

  10. UNKNOWN

Parameter statement is a valid OCI statement identifier, returned from oci_parse().

Esempio 1. oci_statement_type() example

<?php
    $conn = oci_connect("scott", "tiger");
    $sql  = "delete from emp where deptno = 10";
   
    $stmt = oci_parse($conn, $sql);
    if (oci_statement_type($stmt) == "DELETE") {
        die("You are not allowed to delete from this table<br />");
    }
   
    oci_close($conn);
?>

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.

ocibindbyname

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocibindbyname -- Alias di oci_bind_by_name()

Descrizione

This function is an alias of: oci_bind_by_name().

ocicancel

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocicancel -- Interrompe la lettura del cursore

Descrizione

bool ocicancel ( resource stmt )

Se non si vogliono leggere altri dati da un cursore, chiamare ocicancel().

ocicloselob

(no version information, might be only in CVS)

ocicloselob -- Alias di OCI-Lob->close

Descrizione

This function is an alias of: OCI-Lob->close.

ocicollappend

(PHP 4 >= 4.0.6, PHP 5)

ocicollappend -- Aggiunge un oggetto alla collezione

Descrizione

bool ocicollappend ( object valore )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicollassign

(PHP 4 >= 4.0.6)

ocicollassign -- Assegna una collezione da un'altra collezione esistente

Descrizione

bool ocicollassign ( object da )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5)

ocicollassignelem -- Assegna un elemento alla collezione in una specifica posizione

Descrizione

bool ocicollassignelem ( int ndx, string val )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5)

ocicollgetelem -- Coming soon

Descrizione

string ocicollgetelem ( object collection, string ndx )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicollmax

(PHP 4 >= 4.0.6, PHP 5)

ocicollmax -- Coming soon

Descrizione

int ocicollmax ( object collection )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicollsize

(PHP 4 >= 4.0.6, PHP 5)

ocicollsize -- Coming soon

Descrizione

int ocicollsize ( object collection )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5)

ocicolltrim -- Coming soon

Descrizione

bool ocicolltrim ( object collection, int num )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicolumnisnull

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumnisnull -- Verifica se un campo di risultato è NULL

Descrizione

bool ocicolumnisnull ( resource stmt, mixed col )

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

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumnname -- Restituisce il nome di un campo

Descrizione

string ocicolumnname ( int stmt, int col )

ocicolumnname() restituisce il nome del campo corrispondente alla posizione (1 = primo campo) specificata.

Esempio 1. esempio di ocicolumnname()

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

Vedere anche ocinumcols(), ocicolumntype(), e ocicolumnsize().

ocicolumnprecision

(PHP 4, PHP 5)

ocicolumnprecision -- Coming soon

Descrizione

int ocicolumnprecision ( int stmt, int col )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicolumnscale

(PHP 4, PHP 5)

ocicolumnscale -- Coming soon

Descrizione

int ocicolumnscale ( int stmt, int col )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocicolumnsize

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumnsize -- Restituisce la dimensione del campo

Descrizione

int ocicolumnsize ( int stmt, mixed column )

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()

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>";
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

Vedere anche ocinumcols(), ocicolumnname() e ocicolumnsize().

ocicolumntype

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocicolumntype -- Restituisce il tipo di dati di un campo

Descrizione

mixed ocicolumntype ( int stmt, int col )

ocicolumntype() restituisce il tipo del campo corrispondente alla posizione (1 = primo campo) specificata.

Esempio 1. OCIColumnType

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

Vedere anche ocinumcols(), ocicolumnname(), e ocicolumnsize().

ocicolumntyperaw

(PHP 4, PHP 5)

ocicolumntyperaw -- Coming soon

Descrizione

mixed ocicolumntyperaw ( int stmt, int col )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

OCICommit

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

OCICommit -- Esegue le transazioni in sospeso

Descrizione

bool OCICommit ( int connection )

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

<?php
    // Login sul server Oracle
    $conn = OCILogon('scott', 'tiger');

    // Parse SQL
    $stmt = OCIParse($conn, "INSERT INTO impiegati (nome, cognome) VALUES ('Massimo', 'Carlotti')");

    // Esecuzione dello statement
    OCIExecute($stmt);

    // Commit della transazione
    $committed = OCICommit($conn);

    // Valuta se la commit ha funzionata. Se c'e' un errore, restituisce il messaggio di errore
    if(!$committed) {
        $error = OCIError($conn);
        echo 'Commit fallito. Oracle ha restituito: ' . $error['message'];
    }

    // Chiusura della connessione
    OCILogoff($conn);
?>

Vedere anche ocirollback().

OCIDefineByName

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

OCIDefineByName --  Utilizza una variabile PHP per la fase di definizione in un comando SELECT

Descrizione

bool ocidefinebyname ( int stmt, string Column-Name, mixed variable [, int type] )

ocidefinebyname() 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

<?php
/* OCIDefineByName example - thies@thieso.net (980219) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select empno, ename from emp");

/* il define DEVE essere eseguito PRIMA di ociexecute! */

OCIDefineByName($stmt,"EMPNO",$empno);
OCIDefineByName($stmt,"ENAME",$ename);

OCIExecute($stmt);

while (OCIFetch($stmt)) {
    echo "empno:".$empno."\n";
    echo "ename:".$ename."\n";
}

OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCIError

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

OCIError -- Restituisce l'ultimo errore di stmt|conn|global

Descrizione

array OCIError ( [int stmt|conn|global] )

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

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociexecute -- Esegue un comando SQL

Descrizione

int ociexecute ( int statement [, int mode] )

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.

ocifetch

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocifetch -- Estrae la prossima tupla opnendola nel buffer di risultato.

Descrizione

bool ocifetch ( int statement )

ocifetch() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nel buffer interno di risultato.

ocifetchinto

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocifetchinto -- Estrae la prossima tupla ponendola in un array

Descrizione

int ocifetchinto ( int stmt, array &result [, int mode] )

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.

Esempio 1. Un semplice esempio di ocifetchinto()

<?php
$conn = ocilogon("username","password");

$query = "SELECT mele FROM arance";

$statement = OCIParse ($conn, $query);
OCIExecute ($statement);

while (OCIFetchInto ($statement, $row, OCI_ASSOC)) {
    print $row['mele'];
}
?>

Vedere anche ocifetch() e ociexecute().

ocifetchstatement

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocifetchstatement -- Estrae tutte le tuple in un array

Descrizione

int ocifetchstatement ( resource stmt, array & variable )

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()

<?php
/* OCIFetchStatement example mbritton@verinet.com (990624) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select * from emp");

OCIExecute($stmt);

$nrows = OCIFetchStatement($stmt,$results);
if ( $nrows > 0 ) {
   print "<TABLE BORDER=\"1\">\n";
   print "<TR>\n";
   while ( list( $key, $val ) = each( $results ) ) {
      print "<TH>$key</TH>\n";
   }
   print "</TR>\n";
   
   for ( $i = 0; $i < $nrows; $i++ ) {
      reset($results);
      print "<TR>\n";
      while ( $column = each($results) ) {   
         $data = $column['value'];
         print "<TD>$data[$i]</TD>\n";
      }
      print "</TR>\n";
   }
   print "</TABLE>\n";
} else {
   echo "No data found<BR>\n";
}      
print "$nrows Records Selected<BR>\n";
 
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

ocifreecollection

(PHP 4 >= 4.1.0, PHP 5)

ocifreecollection -- Coming soon

Descrizione

bool ocifreecollection ( object lob )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocifreecursor

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocifreecursor --  Libera tutte le risorse associate ad un cursore

Descrizione

int ocifreecursor ( int stmt )

ocifreecursor() libera tutte le risorse associate al cursore stmt. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ocifreedesc

(PHP 4, PHP 5)

ocifreedesc -- Cancella un descrittore di oggetto binario (LOB)

Descrizione

bool ocifreedesc ( object lob )

ocifreedesc() cancella il descrittore di oggetto binario lob. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ocifreestatement

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

ocifreestatement --  Libera tutte le risorse associate ad un'istruzione

Descrizione

bool ocifreestatement ( resource stmt )

ocifreestatement() libera tutte le risorse associate all'istruzione stmt.Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ociinternaldebug

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociinternaldebug --  Abilita o disabilita la visualizzazione del debug interno.

Descrizione

void ociinternaldebug ( int onoff )

ociinternaldebug() abilita la visualizzazione del debug interno. Impostare onoff a 0 per spegnere il debug, 1 per accenderlo.

ociloadlob

(PHP 4, PHP 5)

ociloadlob -- Coming soon

Descrizione

string ociloadlob ( object lob )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocilogoff

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocilogoff -- Disconnette da Oracle

Descrizione

bool ocilogoff ( resource connessione )

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

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocilogon -- Stabilisce una connessione a Oracle

Descrizione

int ocilogon ( string username, string password [, string db] )

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()

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocilogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"TEST").">\n\n";
  echo $conn."----done\n\n";
}

create_table($c1);
insert_data($c1);   // Insert a row using c1
insert_data($c2);   // Insert a row using c2

select_data($c1);   // Results of both inserts are returned
select_data($c2);   

rollback($c1);      // Rollback using c1

select_data($c1);   // Both inserts have been rolled back
select_data($c2);   

insert_data($c2);   // Insert a row using c2
commit($c2);        // Commit using c2

select_data($c1);   // Result of c2 insert is returned

delete_data($c1);   // Delete all rows in table using c1
select_data($c1);   // No rows returned
select_data($c2);   // No rows returned
commit($c1);        // Commit using c1

select_data($c1);   // No rows returned
select_data($c2);   // No rows returned

drop_table($c1);
print "</PRE></HTML>";
?>

Vedere anche ociplogon() e ocinlogon().

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5)

ocinewcollection -- Coming soon

Descrizione

bool ocinewcollection ( int conn, string tdo [, string shema] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocinewcursor

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocinewcursor --  Restituisce un nuovo cursore (Statement-Handle)

Descrizione

resource ocinewcursor ( resource conn )

ocinewcursor() alloca un nuovo identificatore di istruzione sulla connessione specificata.

Esempio 1. Using a REF CURSOR from a stored procedure

<?php   
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = OCILogon("scott","tiger");
$curs = OCINewCursor($conn);
$stmt = OCIParse($conn,"begin info.output(:data); end;");

ocibindbyname($stmt,"data",&$curs,-1,OCI_B_CURSOR);
ociexecute($stmt);
ociexecute($curs);

while (OCIFetchInto($curs,&$data)) {
    var_dump($data);
}
 
OCIFreeStatement($stmt);
OCIFreeCursor($curs);
OCILogoff($conn);
?>

Esempio 2. Using a REF CURSOR in a select statement

<?php   
print "<HTML><BODY>";
$conn = OCILogon("scott","tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = OCIParse($conn,"select deptno,dname,$count_cursor");

ociexecute($stmt);
print "<TABLE BORDER=\"1\">";
print "<TR>";
print "<TH>DEPT NAME</TH>";
print "<TH>DEPT #</TH>";
print "<TH># EMPLOYEES</TH>";
print "</TR>";

while (OCIFetchInto($stmt,&$data,OCI_ASSOC)) {
    print "<TR>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    print "<TD>$dname</TD>";
    print "<TD>$deptno</TD>";
    ociexecute($data["EMPCNT"]);
    while (OCIFetchInto($data["EMPCNT"],&$subdata,OCI_ASSOC)) {
        $num_emps = $subdata["NUM_EMPS"];
        print  "<TD>$num_emps</TD>";
    }
    print "</TR>";
}
print "</TABLE>";
print "</BODY></HTML>";
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

ocinewdescriptor

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocinewdescriptor --  Inizializza un nuovo descrittore LOB/FILE vuoto

Descrizione

string ocinewdescriptor ( int connection [, int type] )

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()

<?php   
    /* Questo codice deve essere richiamato da un form HTML.
     * Richiede che $user, $password, $table, $where, e $commitsize
     * siano passati dalla form.  Il codice quindi cancella
     * le tuple selezionate usando ROWID ed esegue un commit ogni
     * $commitsize righe. (Usare con attenzione, non si può fare rollback)
     */
    $conn = OCILogon($user, $password);
    $stmt = OCIParse($conn,"select rowid from $table $where");
    $rowid = OCINewDescriptor($conn,OCI_D_ROWID);
    OCIDefineByName($stmt,"ROWID",&$rowid);   
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {      
       $nrows = OCIRowCount($stmt);
       $delete = OCIParse($conn,"delete from $table where ROWID = :rid");
       OCIBindByName($delete,":rid",&$rowid,-1,OCI_B_ROWID);
       OCIExecute($delete);      
       print "$nrows\n";
       if ( ($nrows % $commitsize) == 0 ) {
           OCICommit($conn);      
       }   
    }
    $nrows = OCIRowCount($stmt);   
    print "$nrows deleted...\n";
    OCIFreeStatement($stmt);  
    OCILogoff($conn);
?>
<?php
    /* Questo codice dimostra l'upload di file verso campi LOB.
     * Il form usato per questo esempio è del tipo seguente:
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload">
     * ...
     */
  if(!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload"><br>
<input type="submit" value="Upload"> - <input type="reset">
</form>
<?php
} else {

     // $lob_upload contiene il nome del file temporaneo

     // vedere anche la sezione delle funzionalita' di upload dei file,
     // se si vogliono usare gli upload sicuri
     
     $conn = OCILogon($user, $password);
     $lob = OCINewDescriptor($conn, OCI_D_LOB);
     $stmt = OCIParse($conn,"insert into $table (id, the_blob) 
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     OCIBindByName($stmt, ':the_blob', &$lob, -1, OCI_B_BLOB);
     OCIExecute($stmt, OCI_DEFAULT);
     if($lob->savefile($lob_upload)){
        OCICommit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     OCIFreeDesc($lob);
     OCIFreeStatement($stmt);
     OCILogoff($conn);
  }
?>

Esempio 2. OCINewDescriptor

<?php   
    /* Chiamata di una stored procedure PL/SQLs che contiene clobs come parametri
    * di input (PHP 4 >= 4.0.6). 
    * La signature della stored prodedure PL/SQL d'esempio è:
     *
     * PROCEDURE save_data
     *   Argument Name                  Type                    In/Out Default?
     *   ------------------------------ ----------------------- ------ --------
     *   KEY                            NUMBER(38)              IN
     *   DATA                           CLOB                    IN
     *
     */

    $conn = OCILogon($user, $password);
    $stmt = OCIParse($conn, "begin save_data(:key, :data); end;");
    $clob = OCINewDescriptor($conn, OCI_D_LOB);
	OCIBindByName($stmt, ':key', $key);
	OCIBindByName($stmt, ':data', $clob, -1, OCI_B_CLOB);
	$clob->WriteTemporary($data);
	OCIExecute($stmt, OCI_DEFAULT);
	OCICommit($conn);
	$clob->close();
	$clob->free();
	OCIFreeStatement($stmt);
?>

ocinlogon

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ocinlogon -- Stabilisce, una nuova connessione a Oracle.

Descrizione

int ocinlogon ( string username, string password [, string db] )

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()

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocinlogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test
varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"TEST").">\n\n";
  echo $conn."----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);   
select_data($c2);   

rollback($c1);      

select_data($c1);   
select_data($c2);   

insert_data($c2);   
commit($c2);        

select_data($c1);   

delete_data($c1);   
select_data($c1);   
select_data($c2);   
commit($c1);        

select_data($c1);
select_data($c2);

drop_table($c1);
print "</PRE></HTML>";
?>

Vedere anche ocilogon() e ociplogon().

ocinumcols

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ocinumcols --  Restituisce il numero di campi che risultano da un comando SQL

Descrizione

int ocinumcols ( resource stmt )

ocinumcols() restituisce il numero di campi contenuti in un'istruzione SQL.

Esempio 1. ocinumcols()

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {
        print "\n";   
        $ncols = OCINumCols($stmt);
        for ( $i = 1; $i <= $ncols; $i++ ) {
            $column_name  = OCIColumnName($stmt,$i);
            $column_value = OCIResult($stmt,$i);
            print $column_name . ': ' . $column_value . "\n";
        }
        print "\n";
    }
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

ociparse

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociparse -- Analizza una query e restituisce un'istruzione.

Descrizione

int ociparse ( int conn, string query )

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

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

ociplogon --  Stabilisce una connessione permanente a Oracle.

Descrizione

int ociplogon ( string username, string password [, string db] )

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

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociresult -- Restituisce il valore di campo della tupla estratta

Descrizione

mixed ociresult ( int statement, mixed column )

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

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocirollback -- Annulla le transazioni in sospeso

Descrizione

bool ocirollback ( resource connection )

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

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

ocirowcount -- Restituisce il numero di tuple modificate

Descrizione

int ocirowcount ( resource statement )

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()

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $stmt = OCIParse($conn,"create table emp2 as select * from emp");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " rows inserted.<BR>";
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"delete from emp2");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " rows deleted.<BR>";
    OCICommit($conn);
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"drop table emp2");
    OCIExecute($stmt);
    OCIFreeStatement($stmt);
    OCILogOff($conn);
    print "</PRE></HTML>";
?>

ocisavelob

(PHP 4, PHP 5)

ocisavelob -- Coming soon

Descrizione

bool ocisavelob ( object lob )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ocisavelobfile

(PHP 4, PHP 5)

ocisavelobfile -- Coming soon

Descrizione

bool ocisavelobfile ( object lob )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ociserverversion

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

ociserverversion -- Restituisce una stringa contenente informazioni sulla versione del server

Descrizione

string ociserverversion ( resource conn )

Esempio 1. esempio di ociserverversion()

<?php
   $conn = OCILogon("scott","tiger");
   print "Server Version: " . OCIServerVersion($conn);
   OCILogOff($conn);
?>

ocisetprefetch

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

ocisetprefetch -- Imposta il numero di tuple da precaricare

Descrizione

int ocisetprefetch ( resource stmt, int rows )

Imposta a rows il numero di tuple da precaricare. Il valore di default è 1.

ocistatementtype

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

ocistatementtype -- Restituisce il tipo di un'istruzione OCI

Descrizione

string ocistatementtype ( resource stmt )

ocistatementtype() restituisce uno dei seguenti valori:

  1. SELECT

  2. UPDATE

  3. DELETE

  4. INSERT

  5. CREATE

  6. DROP

  7. ALTER

  8. BEGIN

  9. DECLARE

  10. UNKNOWN

Esempio 1. Esempi di ocistatementtype()

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $sql  = "delete from emp where deptno = 10";
   
    $stmt = OCIParse($conn,$sql);
    if ( OCIStatementType($stmt) == "DELETE" ) {
        die "You are not allowed to delete from this table<BR>";
    }
   
    OCILogoff($conn);
    print "</PRE></HTML>";
?>

ociwritelobtofile

(PHP 4, PHP 5)

ociwritelobtofile -- Coming soon

Descrizione

bool ociwritelobtofile ( object lob [, string filename [, int start [, int lenght]]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ociwritetemporarylob

(no version information, might be only in CVS)

ociwritetemporarylob -- Alias di OCI-Lob->writeTemporary

Descrizione

This function is an alias of: OCI-Lob->writeTemporary.

XCVI. Funzioni ODBC (Unificate)

Introduzione

In 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.


Requisiti

Per potere accedere ai database supportati occorre avere installato le librerie necessarie.


Installazione

--with-adabas[=DIR]

Include il supporto per Adabas D. DIR indica la directory di installazione di Adabas, il default è /usr/local.

--with-sapdb[=DIR]

Include il supporto per SAP DB. DIR indica la directory di installazione di SAP DB, il default è /usr/local.

--with-solid[=DIR]

Include il supporto per Solid. DIR indica la directory di installazione di Solid, il default è /usr/local/solid.

--with-ibm-db2[=DIR]

Include il supporto per IBM DB2. DIR indica la directory di installazione di DB2, il default è /home/db2inst1/sqllib.

--with-empress[=DIR]

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.

--with-empress-bcs[=DIR]

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.

--with-birdstep[=DIR]

Include il supporto per Birdstep. DIR indica la directory di installazione di Birdstep, il default è /usr/local/birdstep.

--with-custom-odbc[=DIR]

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".

--with-iodbc[=DIR]

Include il supporto per iODBC. DIR indica la directory di installazione di iODBC, il default è /usr/local.

--with-esoob[=DIR]

Include il supporto per Easysoft OOB. DIR indica la directory di installazione di OOB, il default è /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Include il supporto per unixODBC. DIR indica la directory di installazione di unixODBC, il default è /usr/local.

--with-openlink[=DIR]

Include il supporto per OpenLink ODBC. DIR indica la directory di installazione di OpenLink, il default è /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametrizzazione per il modulo Funzioni ODBC Unificate

NomeDefaultModificabileLog delle modifiche
odbc.default_db *NULLPHP_INI_ALL 
odbc.default_user *NULLPHP_INI_ALL 
odbc.default_pw *NULLPHP_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.

Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

odbc.default_db string

Sorgenti di dati ODBC da utilizzare se non viene fornita in odbc_connect() o odbc_pconnect().

odbc.default_user string

Nome utente da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().

odbc.default_pw string

Password da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().

odbc.allow_persistent boolean

Indica se permettere le connessioni ODBC persistenti.

odbc.check_persistent boolean

Verifica se una connessione è ancora valida prima di ri-utilizzarla.

odbc.max_persistent integer

Imposta il numero massimo di connessioni persistenti permesse per processo.

odbc.max_links integer

Imposta il numero massimo di connessioni permesse per processo, comprese le connessioni persistenti.

odbc.defaultlrl integer

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.

odbc.defaultbinmode integer

Gestione dei dati binari.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

ODBC_TYPE (integer)

ODBC_BINMODE_PASSTHRU (integer)

ODBC_BINMODE_RETURN (integer)

ODBC_BINMODE_CONVERT (integer)

SQL_ODBC_CURSORS (integer)

SQL_CUR_USE_DRIVER (integer)

SQL_CUR_USE_IF_NEEDED (integer)

SQL_CUR_USE_ODBC (integer)

SQL_CONCURRENCY (integer)

SQL_CONCUR_READ_ONLY (integer)

SQL_CONCUR_LOCK (integer)

SQL_CONCUR_ROWVER (integer)

SQL_CONCUR_VALUES (integer)

SQL_CURSOR_TYPE (integer)

SQL_CURSOR_FORWARD_ONLY (integer)

SQL_CURSOR_KEYSET_DRIVEN (integer)

SQL_CURSOR_DYNAMIC (integer)

SQL_CURSOR_STATIC (integer)

SQL_KEYSET_SIZE (integer)

SQL_CHAR (integer)

SQL_VARCHAR (integer)

SQL_LONGVARCHAR (integer)

SQL_DECIMAL (integer)

SQL_NUMERIC (integer)

SQL_BIT (integer)

SQL_TINYINT (integer)

SQL_SMALLINT (integer)

SQL_INTEGER (integer)

SQL_BIGINT (integer)

SQL_REAL (integer)

SQL_FLOAT (integer)

SQL_DOUBLE (integer)

SQL_BINARY (integer)

SQL_VARBINARY (integer)

SQL_LONGVARBINARY (integer)

SQL_DATE (integer)

SQL_TIME (integer)

SQL_TIMESTAMP (integer)

SQL_TYPE_DATE (integer)

SQL_TYPE_TIME (integer)

SQL_TYPE_TIMESTAMP (integer)

SQL_BEST_ROWID (integer)

SQL_ROWVER (integer)

SQL_SCOPE_CURROW (integer)

SQL_SCOPE_TRANSACTION (integer)

SQL_SCOPE_SESSION (integer)

SQL_NO_NULLS (integer)

SQL_NULLABLE (integer)

SQL_INDEX_UNIQUE (integer)

SQL_INDEX_ALL (integer)

SQL_ENSURE (integer)

SQL_QUICK (integer)

Sommario
odbc_autocommit -- Valorizza il parametro autocommit
odbc_binmode -- Gestione delle colonne di dati binari
odbc_close_all -- Chiude tutte le connessioni ODBC
odbc_close -- Chiude una connessione ODBC
odbc_columnprivileges --  Restituisce un identificatore di risultato che permette di ricavare l'elenco delle colonne e dei privilegi ad esse associati.
odbc_columns --  Elenca i nomi delle colonne nella tabella specificata.
odbc_commit -- Esegue una transazione ODBC
odbc_connect -- Apre una connessione con una fonte di dati
odbc_cursor -- Restituisce il nome del cursore
odbc_data_source -- Restituisce informazionisulla connessione corrente
odbc_do -- Sinonimo di odbc_exec()
odbc_error -- Restituisce l'ultimo codice di errore
odbc_errormsg -- Restituisce l'ultimo messaggio d'errore
odbc_exec -- Prepara ed esegue una espressione SQL
odbc_execute -- Esecuzione di un'espressione memorizzata
odbc_fetch_array -- Scarica una riga da un risultato in una matrice
odbc_fetch_into -- Scarica una riga del risultato della query in un array
odbc_fetch_object -- Scarica una riga da un risultato come oggetto
odbc_fetch_row -- Estrae una riga
odbc_field_len -- Restituisce la dimensione (precisione) di un campo
odbc_field_name -- Restituisce il nome della colonna
odbc_field_num -- Restituisce il numero di colonna
odbc_field_precision -- Sinonimo di odbc_field_len()
odbc_field_scale -- Restituisce la scala di un campo
odbc_field_type -- Tipo di dato di campo
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.
odbc_free_result -- Libera le risorse associate ad un risultato
odbc_gettypeinfo --  Restituisce un identificatore di risultato contenente informazioni sui tipi di dati supportati dalla sorgente di dati
odbc_longreadlen -- Gestione di colonne LONG
odbc_next_result --  Verifica se sono disponibili più risultati
odbc_num_fields -- Numero di colonne in un esito
odbc_num_rows -- Numero di righe in un risultato
odbc_pconnect -- Apre una connessione persistente verso un database
odbc_prepare -- Predispone un'espressione all'esecuzione
odbc_primarykeys --  Restituisce un identificatore di risultato che può essere utilizzato per ricavare il nome della colonna che contiene la chiave primaria della tabella.
odbc_procedurecolumns --  Recupera informazioni sui parametri delle procedure.
odbc_procedures --  Restituisce l'elenco delle procedure memorizzate in una specifica sorgente di dati.
odbc_result_all -- Visualizza il risultato in una tabella HTML
odbc_result -- Restituisce il contenuto dei campi
odbc_rollback -- Annulla una transazione
odbc_setoption --  Impostazione dei parametri ODBC
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.
odbc_statistics -- Recupera informazioni statistiche sulla tabella
odbc_tableprivileges --  Elenca le tabelle ed i privilegi ad esse associati.
odbc_tables --  Restituisce l'elenco delle tabelle presenti in una specifica sorgente di dati

odbc_autocommit

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_autocommit -- Valorizza il parametro autocommit

Descrizione

bool odbc_autocommit ( resource id_connessione [, bool OnOff] )

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().

odbc_binmode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_binmode -- Gestione delle colonne di dati binari

Descrizione

bool odbc_binmode ( resource id_risultato, int modalità )

(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 longreadlenComportamento
ODBC_BINMODE_PASSTHRU0direttamente al client
ODBC_BINMODE_RETURN0direttamente al client
ODBC_BINMODE_CONVERT0direttamente al client
ODBC_BINMODE_PASSTHRU0passthru
ODBC_BINMODE_PASSTHRU>0direttamente al client
ODBC_BINMODE_RETURN>0restituito inalterato
ODBC_BINMODE_CONVERT>0restituito 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()

odbc_close_all

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_close_all -- Chiude tutte le connessioni ODBC

Descrizione

void odbc_close_all ( void )

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

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_close -- Chiude una connessione ODBC

Descrizione

void odbc_close ( resource id_connessione )

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.

odbc_columnprivileges

(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.

Descrizione

resource odbc_columnprivileges ( resource id_connessione, string qualifica, string proprietario, string nome_tabella, string nome_colonna )

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).

odbc_columns

(PHP 4, PHP 5)

odbc_columns --  Elenca i nomi delle colonne nella tabella specificata.

Descrizione

resource odbc_columns ( resource id_connessione [, string qualifica [, string schema [, string nome_tabella [, string nome_colonna]]]] )

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.

odbc_commit

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_commit -- Esegue una transazione ODBC

Descrizione

bool odbc_commit ( resource id_connessione )

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.

odbc_connect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_connect -- Apre una connessione con una fonte di dati

Descrizione

resource odbc_connect ( string dsn, string utente, string password [, int tipo_cursore] )

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

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_cursor -- Restituisce il nome del cursore

Descrizione

string odbc_cursor ( resource id_risultato )

odbc_cursor restituisce il nome del cursore per l'argomento id_risultato.

odbc_data_source

(PHP 4 >= 4.3.0, PHP 5)

odbc_data_source -- Restituisce informazionisulla connessione corrente

Descrizione

array odbc_data_source ( resource connection_id, int fetch_type )

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

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_do -- Sinonimo di odbc_exec()

Descrizione

resource odbc_do ( resource id_connessione, string query )

odbc_do() esegue una query sulla connessione data.

odbc_error

(PHP 4 >= 4.0.5, PHP 5)

odbc_error -- Restituisce l'ultimo codice di errore

Descrizione

string odbc_error ( [resource id_connessione] )

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().

odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5)

odbc_errormsg -- Restituisce l'ultimo messaggio d'errore

Descrizione

string odbc_errormsg ( [resource id_connessione] )

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().

odbc_exec

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_exec -- Prepara ed esegue una espressione SQL

Descrizione

resource odbc_exec ( resource id_connessione, string testo_query [, int flags] )

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.

odbc_execute

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_execute -- Esecuzione di un'espressione memorizzata

Descrizione

bool odbc_execute ( resource id_risultato [, array array_parametri] )

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().

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_array -- Scarica una riga da un risultato in una matrice

Descrizione

array odbc_fetch_array ( resource result [, int rownumber] )

Scarica, in una matrice associativa, da una query ODBC. Vedere nel successivo log delle modifiche per sapere quando questa funzione è disponibile.

Elenco dei parametri

result

Risorsa risultato da odbc_exec().

rownumber

Opzionale, indica quale nnumero di riga recuperare.

Valori restituiti

Restituisce una matrice corrispondente alla riga scaricata, oppure FALSE se non vi sono righe successive.

Log delle modifiche

VersioneDescrizione
4.3.3 La funzione è disponibile nella vesione compilata con il supporto per IBM DB2 o UnixODBC.
4.3.2 Questa funzione esiste nella versione per Windows.
4.0.2 Questa funzione esiste nella versione compilata con il supporto DBMaker.

odbc_fetch_into

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_fetch_into -- Scarica una riga del risultato della query in un array

Descrizione

int odbc_fetch_into ( resource id_risultato, array &array_dati [, int numero_riga] )

bool odbc_fetch_into ( resource id_risultato [, int numero_riga, array &array_dati] )

La 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.

Esempio 1. odbc_fetch_into() Esempi pre 4.0.6

<?php
$rc = odbc_fetch_into($id_risultato, $array_di_test);
?>

oppure

<?php
$rc = odbc_fetch_into($id_risultato, $riga, $array_di_test);
       
$rc = odbc_fetch_into($id_risultato, 1, $array_di_test);
?>

Esempio 2. odbc_fetch_into() Esempi con PHP 4.0.6

<?php
$rc = odbc_fetch_into($id_risultato, $array_di_test);
?>

oppure

<?php
$riga = 1;
$rc = odbc_fetch_into($id_risultato, $riga, $array_di_test);
?>

Esempio 3. Esempio di odbc_fetch_into()con PHP 4.2.0

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

oppure

<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_object -- Scarica una riga da un risultato come oggetto

Descrizione

object odbc_fetch_object ( resource result [, int rownumber] )

Scarica un oggetto da una query ODBC. Vedere nel successivo log delle modifiche per sapere quando questa funzione è disponibile.

Elenco dei parametri

result

Risorsa risultato da odbc_exec().

rownumber

Opzionale, indica quale nnumero di riga recuperare.

Valori restituiti

Restituisce un oggetto corrispondente alla riga scaricata, oppure FALSE se non vi sono righe successive.

Log delle modifiche

VersioneDescrizione
4.3.3 La funzione è disponibile nella vesione compilata con il supporto per IBM DB2 o UnixODBC.
4.3.2 Questa funzione esiste nella versione per Windows.
4.0.2 Questa funzione esiste nella versione compilata con il supporto DBMaker.

odbc_fetch_row

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_fetch_row -- Estrae una riga

Descrizione

bool odbc_fetch_row ( resource id_risultato [, int numero_riga] )

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.

odbc_field_len

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_len -- Restituisce la dimensione (precisione) di un campo

Descrizione

int odbc_field_len ( resource id_risultato, int numero_campo )

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.

odbc_field_name

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_name -- Restituisce il nome della colonna

Descrizione

string odbc_field_name ( resource id_risultato, int numero_campo )

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

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_num -- Restituisce il numero di colonna

Descrizione

int odbc_field_num ( resource id_risultato, string nome_campo )

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.

odbc_field_precision

(PHP 4, PHP 5)

odbc_field_precision -- Sinonimo di odbc_field_len()

Descrizione

int odbc_field_precision ( resource id_risultato, int numero_campo )

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.

odbc_field_scale

(PHP 4, PHP 5)

odbc_field_scale -- Restituisce la scala di un campo

Descrizione

int odbc_field_scale ( resource id_risultato, int numero_campo )

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.

odbc_field_type

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_field_type -- Tipo di dato di campo

Descrizione

string odbc_field_type ( resource id_risultato, int numero_campo )

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.

odbc_foreignkeys

(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.

Descrizione

resource odbc_foreignkeys ( resource id_connessione, string pk_qualifica, string pk_proprietario, string pk_tabella, string fk_qualifica, string fk_proprietario, string fk_tabella )

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.

odbc_free_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_free_result -- Libera le risorse associate ad un risultato

Descrizione

bool odbc_free_result ( resource id_risultato )

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,

odbc_gettypeinfo

(PHP 4, PHP 5)

odbc_gettypeinfo --  Restituisce un identificatore di risultato contenente informazioni sui tipi di dati supportati dalla sorgente di dati

Descrizione

resource odbc_gettypeinfo ( resource id_connessione [, int tipo_dato] )

Recupera 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.

odbc_longreadlen

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_longreadlen -- Gestione di colonne LONG

Descrizione

bool odbc_longreadlen ( resource id_risultato, int lunghezza )

(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().

odbc_next_result

(PHP 4 >= 4.0.5, PHP 5)

odbc_next_result --  Verifica se sono disponibili più risultati

Descrizione

bool odbc_next_result ( resource id_risultato )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

odbc_num_fields

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_num_fields -- Numero di colonne in un esito

Descrizione

int odbc_num_fields ( resource id_risultato )

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

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_num_rows -- Numero di righe in un risultato

Descrizione

int odbc_num_rows ( resource id_risultato )

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.

odbc_pconnect

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_pconnect -- Apre una connessione persistente verso un database

Descrizione

resource odbc_pconnect ( string dsn, string utente, string password [, int tipo_cursore] )

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.

odbc_prepare

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_prepare -- Predispone un'espressione all'esecuzione

Descrizione

resource odbc_prepare ( resource id_connessione, string testo_query )

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));
?>
Se occorre utilizzare stored procedure che richiedono parametri INOUT od OUT, si suggerisce di utilizzare i moduli nativi del database (ad esempio, mssql per MS SQL Server, o oci8 per Oracle).

odbc_primarykeys

(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.

Descrizione

resource odbc_primarykeys ( resource id_connessione, string qualifica, string proprietario, string 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

odbc_procedurecolumns

(PHP 4, PHP 5)

odbc_procedurecolumns --  Recupera informazioni sui parametri delle procedure.

Descrizione

resource odbc_procedurecolumns ( resource id_connessione [, string qualifica, string proprietario, string procedura, string colonna] )

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).

odbc_procedures

(PHP 4, PHP 5)

odbc_procedures --  Restituisce l'elenco delle procedure memorizzate in una specifica sorgente di dati.

Descrizione

resource odbc_procedures ( resource id_connessione [, string qualifica, string proprietario, string nome] )

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).

odbc_result_all

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_result_all -- Visualizza il risultato in una tabella HTML

Descrizione

int odbc_result_all ( resource id_esito [, string formato] )

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.

odbc_result

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_result -- Restituisce il contenuto dei campi

Descrizione

string odbc_result ( resource id_risultato, mixed campo )

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:

<?php
$item_3 = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>

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().

odbc_rollback

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_rollback -- Annulla una transazione

Descrizione

bool odbc_rollback ( resource id_connessione )

Annulla tutte le operazioni pendenti sulla connessione indicata da id_connessione. Se ha successo restituisce TRUE, altrimenti FALSE.

odbc_setoption

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

odbc_setoption --  Impostazione dei parametri ODBC

Descrizione

bool odbc_setoption ( resource identificativo, int funzione, int opzione, int parametro )

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
// 1. Il valore 102 per il campo opzione in SQLSetConnectOption() indica SQL_AUTOCOMMIT.
//    Il valore 1 per SQL_AUTOCOMMIT è SQL_AUTOCOMMIT_ON.
//    Pertanto questo esempio ha il medesimo effetto di:
//    odbc_autocommit($conn, true);

odbc_setoption($conn, 1, 102, 1);

// 2. Il valore 0 per il campo opzione in SQLSetStmtOption() indica SQL_QUERY_TIMEOUT.
//    In questo esempio si setta il timeout di una query a 30 secondi.

$result = odbc_prepare($conn, $sql);
odbc_setoption($result, 2, 0, 30);
odbc_execute($result);
?>

odbc_specialcolumns

(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.

Descrizione

resource odbc_specialcolumns ( resource id_connessione, int tipo, string qualifica, string proprietario, string tabella, int visibilità, int nullable )

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.

odbc_statistics

(PHP 4, PHP 5)

odbc_statistics -- Recupera informazioni statistiche sulla tabella

Descrizione

resource odbc_statistics ( resource id_connessione, string qualifica, string proprietario, string nome_tabella, int unico, int precisione )

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.

odbc_tableprivileges

(PHP 4, PHP 5)

odbc_tableprivileges --  Elenca le tabelle ed i privilegi ad esse associati.

Descrizione

resource odbc_tableprivileges ( resource id_connessione, string qualifica, string proprietario, string nome )

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).

odbc_tables

(PHP 3 >= 3.0.17, PHP 4, PHP 5)

odbc_tables --  Restituisce l'elenco delle tabelle presenti in una specifica sorgente di dati

Descrizione

resource odbc_tables ( resource Id_connessione [, string qualifica [, string proprietario [, string nome [, string tipo]]]] )

La 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.

XCVII. ODBC and DB2 functions (PDO_ODBC)

Introduzione

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:

ibm-db2

Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 client.

unixODBC

Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.

generic

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.


Installazione

PDO_ODBC on UNIX systems

  1. 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.

    ibm_db2

    ./configure --enable-pdo_odbc=ibm-db2,/opt/IBM/db2/V8.1/
    To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database support site.

    If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.

    unixODBC

    ./configure --enable-pdo_odbc=unixODBC,/usr/local
    If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local.

    generic
    ./configure --enable-pdo_odbc=generic,/usr/local,libname,ldflags,cflags


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. PDO_ODBC Configuration Options

NameDefaultChangeableChangelog
pdo_odbc.connection_pooling"strict"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

pdo_odbc.connection_pooling string

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.

Sommario
PDO_ODBC DSN -- Connecting to ODBC or DB2 databases

PDO_ODBC DSN

(no version information, might be only in CVS)

PDO_ODBC DSN -- Connecting to ODBC or DB2 databases

Descrizione

The PDO_ODBC Data Source Name (DSN) is composed of the following elements:

DSN prefix

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.

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/.

UID

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.

PWD

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.

Esempi

Esempio 1. PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:
odbc:testdb

Esempio 2. PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named SAMPLE using the full ODBC DSN syntax:
odbc:DSN={IBM DB2 ODBC};HOSTNAME=localhost;PORT=50000;DBNAME=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Esempio 3. PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at C:\db.mdb using the full ODBC DSN syntax:
odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin

XCVIII. oggvorbis

Introduzione

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.


Requisiti

This extension requires PHP >= 4.3.0, libogg >= 1.0, and libvorbis >= 1.0.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Installazione

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');


Context options

Tabella 1. OGG/Vorbis tuning options

OptionDefinitionRelevanceDefault
pcm_modePCM byte encoding used. See constants below.Read / WriteOGGVORBIS_PCM_S16_LE
ratePCM Sampling rate. Measured in Hz.Write only44100
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 only128000
channelsNumber of PCM channels. 1 == Mono, 2 == Stereo.Write only2
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 onlyRandom
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 onlyarray('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis')

Costanti predefinite

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

ConstantDefinition
OGGVORBIS_PCM_U8Unsigned 8-bit PCM.
OGGVORBIS_PCM_S8Signed 8-bit PCM.
OGGVORBIS_PCM_U16_LEUnsigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_U16_BEUnsigned 16-bit PCM. Big Endian byte order.
OGGVORBIS_PCM_S16_LESigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_S16_BESigned 16-bit PCM. Big Endian byte order.
Sommario
Usage --  Examples on using the ogg:// wrapper.

Usage

(no version information, might be only in CVS)

Usage --  Examples on using the ogg:// wrapper.

Esempi

Esempio 1. Reading an OGG/Vorbis file

<?php
dl("oggvorbis.so");

/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');

/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);

/* Inspect the first song (usually the only song, 
   but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];

echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo "  {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
    echo "  $comment\n";
}

while ($audio_data = fread($fp, 8192)) {
  /* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems, 
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?>

Esempio 2. Encode an audio file to OGG/Vorbis

<?php
dl('oggvorbis.so');

$context = stream_context_create(array('ogg'=>array(
             'pcm_mode' => OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             'rate' => 44100,                 /* 44kHz CD quality */
             'bitrate' => 0.5,                /* Midquality VBR */
             'channels' => 1,                 /* Mono */
             'serialno' => 12345)));          /* Unique within our stream */

/* Open file for appending.  This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);

$pcm = fopen('mysample.pcm', 'r');

/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);

fclose($pcm);
fclose($ogg);
?>

XCIX. OpenAL Audio Bindings

Introduzione

Platform independent audio bindings. Requires the OpenAL library.


Installazione

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/.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

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().


Costanti predefinite

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.

ALC_FREQUENCY (integer)

Context Attribute

ALC_REFRESH (integer)

Context Attribute

ALC_SYNC (integer)

Context Attribute

AL_FREQUENCY (integer)

Buffer Setting

AL_BITS (integer)

Buffer Setting

AL_CHANNELS (integer)

Buffer Setting

AL_SIZE (integer)

Buffer Setting

AL_BUFFER (integer)

Source/Listener Setting (Integer)

AL_SOURCE_RELATIVE (integer)

Source/Listener Setting (Integer)

AL_SOURCE_STATE (integer)

Source/Listener Setting (Integer)

AL_PITCH (integer)

Source/Listener Setting (Float)

AL_GAIN (integer)

Source/Listener Setting (Float)

AL_MIN_GAIN (integer)

Source/Listener Setting (Float)

AL_MAX_GAIN (integer)

Source/Listener Setting (Float)

AL_MAX_DISTANCE (integer)

Source/Listener Setting (Float)

AL_ROLLOFF_FACTOR (integer)

Source/Listener Setting (Float)

AL_CONE_OUTER_GAIN (integer)

Source/Listener Setting (Float)

AL_CONE_INNER_ANGLE (integer)

Source/Listener Setting (Float)

AL_CONE_OUTER_ANGLE (integer)

Source/Listener Setting (Float)

AL_REFERENCE_DISTANCE (integer)

Source/Listener Setting (Float)

AL_POSITION (integer)

Source/Listener Setting (Float Vector)

AL_VELOCITY (integer)

Source/Listener Setting (Float Vector)

AL_DIRECTION (integer)

Source/Listener Setting (Float Vector)

AL_ORIENTATION (integer)

Source/Listener Setting (Float Vector)

AL_FORMAT_MONO8 (integer)

PCM Format

AL_FORMAT_MONO16 (integer)

PCM Format

AL_FORMAT_STEREO8 (integer)

PCM Format

AL_FORMAT_STEREO16 (integer)

PCM Format

AL_INITIAL (integer)

Source State

AL_PLAYING (integer)

Source State

AL_PAUSED (integer)

Source State

AL_STOPPED (integer)

Source State

AL_LOOPING (integer)

Source State

AL_TRUE (integer)

Boolean value recognized by OpenAL

AL_FALSE (integer)

Boolean value recognized by OpenAL

Sommario
openal_buffer_create --  Generate OpenAL buffer
openal_buffer_data --  Load a buffer with data
openal_buffer_destroy --  Destroys an OpenAL buffer
openal_buffer_get --  Retrieve an OpenAL buffer property
openal_buffer_loadwav --  Load a .wav file into a buffer
openal_context_create --  Create an audio processing context
openal_context_current --  Make the specified context current
openal_context_destroy --  Destroys a context
openal_context_process --  Process the specified context
openal_context_suspend --  Suspend the specified context
openal_device_close --  Close an OpenAL device
openal_device_open --  Initialize the OpenAL audio layer
openal_listener_get --  Retrieve a listener property
openal_listener_set --  Set a listener property
openal_source_create --  Generate a source resource
openal_source_destroy --  Destroy a source resource
openal_source_get --  Retrieve an OpenAL source property
openal_source_pause --  Pause the source
openal_source_play --  Start playing the source
openal_source_rewind --  Rewind the source
openal_source_set --  Set source property
openal_source_stop --  Stop playing the source
openal_stream --  Begin streaming on a source

openal_buffer_create

(PECL)

openal_buffer_create --  Generate OpenAL buffer

Descrizione

resource openal_buffer_create ( void )

Valori restituiti

Returns an Open AL(Buffer) resource on success or FALSE on failure.

openal_buffer_data

(PECL)

openal_buffer_data --  Load a buffer with data

Descrizione

bool openal_buffer_data ( resource buffer, int format, string data, int freq )

Elenco dei parametri

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

format

Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 e AL_FORMAT_STEREO16

data

Block of binary audio data in the format and freq specified.

frew

Frequency of data given in Hz.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_buffer_destroy

(PECL)

openal_buffer_destroy --  Destroys an OpenAL buffer

Descrizione

bool openal_buffer_destroy ( resource buffer )

Elenco dei parametri

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

openal_buffer_create()

openal_buffer_get

(PECL)

openal_buffer_get --  Retrieve an OpenAL buffer property

Descrizione

int openal_buffer_get ( resource buffer, int property )

Elenco dei parametri

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

property

Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS e AL_SIZE.

Valori restituiti

Returns an integer value appropriate to the property requested or FALSE on failure.

Vedere anche:

openal_buffer_create()

openal_buffer_loadwav

(PECL)

openal_buffer_loadwav --  Load a .wav file into a buffer

Descrizione

bool openal_buffer_loadwav ( resource buffer, string wavfile )

Elenco dei parametri

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .WAV file on local file system.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_context_create

(PECL)

openal_context_create --  Create an audio processing context

Descrizione

resource openal_context_create ( resource device )

Elenco dei parametri

device

An Open AL(Device) resource (previously created by openal_device_open()).

Valori restituiti

Returns an Open AL(Context) resource on success or FALSE on failure.

openal_context_current

(PECL)

openal_context_current --  Make the specified context current

Descrizione

bool openal_context_current ( resource context )

Elenco dei parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_context_destroy

(PECL)

openal_context_destroy --  Destroys a context

Descrizione

bool openal_context_destroy ( resource context )

Elenco dei parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_context_process

(PECL)

openal_context_process --  Process the specified context

Descrizione

bool openal_context_process ( resource context )

Elenco dei parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_context_suspend

(PECL)

openal_context_suspend --  Suspend the specified context

Descrizione

bool openal_context_suspend ( resource context )

Elenco dei parametri

context

An Open AL(Context) resource (previously created by openal_context_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_device_close

(PECL)

openal_device_close --  Close an OpenAL device

Descrizione

bool openal_device_close ( resource device )

Elenco dei parametri

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

openal_device_open()

openal_device_open

(PECL)

openal_device_open --  Initialize the OpenAL audio layer

Descrizione

resource openal_device_open ( [string device_desc] )

Elenco dei parametri

device_desc

Open an audio device optionally specified by device_desc. If device_desc is not specified the first available audio device will be used.

Valori restituiti

Returns an Open AL(Device) resource on success or FALSE on failure.

openal_listener_get

(PECL)

openal_listener_get --  Retrieve a listener property

Descrizione

mixed openal_listener_get ( int property )

Elenco dei parametri

property

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)).

Valori restituiti

Returns a float or array of floats (as appropriate), or FALSE on failure.

Vedere anche:

openal_listener_set()

openal_listener_set

(PECL)

openal_listener_set --  Set a listener property

Descrizione

bool openal_listener_set ( int property, mixed setting )

Elenco dei parametri

property

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)).

setting

Value to set, either float, or an array of floats as appropriate.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

openal_listener_get()

openal_source_create

(PECL)

openal_source_create --  Generate a source resource

Descrizione

resource openal_source_create ( void )

Valori restituiti

Returns an Open AL(Source) resource on success or FALSE on failure.

openal_source_destroy

(PECL)

openal_source_destroy --  Destroy a source resource

Descrizione

bool openal_source_destroy ( resource source )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

openal_source_create()

openal_source_get

(PECL)

openal_source_get --  Retrieve an OpenAL source property

Descrizione

mixed openal_source_get ( resource source, int property )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

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)).

Valori restituiti

Returns the type associated with the property being retrieved or FALSE on failure.

openal_source_pause

(PECL)

openal_source_pause --  Pause the source

Descrizione

bool openal_source_pause ( resource source )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_source_play

(PECL)

openal_source_play --  Start playing the source

Descrizione

bool openal_source_play ( resource source )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_source_rewind

(PECL)

openal_source_rewind --  Rewind the source

Descrizione

bool openal_source_rewind ( resource source )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_source_set

(PECL)

openal_source_set --  Set source property

Descrizione

bool openal_source_set ( resource source, int property, mixed setting )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

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)).

setting

Value to assign to specified property. Refer to the description of property for a description of the value(s) expected.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_source_stop

(PECL)

openal_source_stop --  Stop playing the source

Descrizione

bool openal_source_stop ( resource source )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

openal_stream

(PECL)

openal_stream --  Begin streaming on a source

Descrizione

resource openal_stream ( resource source, int format, int rate )

Elenco dei parametri

source

An Open AL(Source) resource (previously created by openal_source_create()).

format

Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 e AL_FORMAT_STEREO16

rate

Frequency of data to stream given in Hz.

Valori restituiti

Returns a stream resource on success, or FALSE on failure.

C. OpenSSL Functions

Introduzione

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.


Requisiti

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.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()

    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate

    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()

    2. For public keys only: an X.509 resource

    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)

    4. A string containing the content of a certificate/key, PEM encoded

    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key


Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.


Costanti predefinite

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.


Purpose checking flags

X509_PURPOSE_SSL_CLIENT (integer)

X509_PURPOSE_SSL_SERVER (integer)

X509_PURPOSE_NS_SSL_SERVER (integer)

X509_PURPOSE_SMIME_SIGN (integer)

X509_PURPOSE_SMIME_ENCRYPT (integer)

X509_PURPOSE_CRL_SIGN (integer)

X509_PURPOSE_ANY (integer)


Padding flags

OPENSSL_PKCS1_PADDING (integer)

OPENSSL_SSLV23_PADDING (integer)

OPENSSL_NO_PADDING (integer)

OPENSSL_PKCS1_OAEP_PADDING (integer)


Key types

OPENSSL_KEYTYPE_RSA (integer)

OPENSSL_KEYTYPE_DSA (integer)

OPENSSL_KEYTYPE_DH (integer)


PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

Tabella 1. PKCS7 CONSTANTS

ConstantDescription
PKCS7_TEXTAdds 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_BINARYNormally 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_NOINTERNWhen 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_NOVERIFYDo not verify the signers certificate of a signed message.
PKCS7_NOCHAINDo not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTSWhen 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_NOATTRNormally 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_DETACHEDWhen 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_NOSIGSDon't try and verify the signatures on a message

Nota: These constants were added in 4.0.6.

Sommario
openssl_csr_export_to_file -- Exports a CSR to a file
openssl_csr_export -- Exports a CSR as a string
openssl_csr_new -- Generates a CSR
openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate
openssl_error_string -- Return openSSL error message
openssl_free_key -- Free key resource
openssl_get_privatekey -- Alias di openssl_pkey_get_private()
openssl_get_publickey -- Alias di openssl_pkey_get_public()
openssl_open -- Open sealed data
openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt -- Encrypt an S/MIME message
openssl_pkcs7_sign -- Sign an S/MIME message
openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file
openssl_pkey_export -- Gets an exportable representation of a key into a string
openssl_pkey_free -- Frees a private key
openssl_pkey_get_private -- Get a private key
openssl_pkey_get_public -- Extract public key from certificate and prepare it for use
openssl_pkey_new -- Generates a new private key
openssl_private_decrypt -- Decrypts data with private key
openssl_private_encrypt -- Encrypts data with private key
openssl_public_decrypt -- Decrypts data with public key
openssl_public_encrypt -- Encrypts data with public key
openssl_seal -- Seal (encrypt) data
openssl_sign -- Generate signature
openssl_verify -- Verify signature
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file -- Exports a certificate to file
openssl_x509_export -- Exports a certificate as a string
openssl_x509_free -- Free certificate resource
openssl_x509_parse -- Parse an X509 certificate and return the information as an array
openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export_to_file -- Exports a CSR to a file

Description

bool openssl_csr_export_to_file ( resource csr, string outfilename [, bool notext] )

openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename.

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

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export -- Exports a CSR as a string

Description

bool openssl_csr_export ( resource csr, string &out [, bool notext] )

openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out, which is passed by reference.

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

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_new -- Generates a CSR

Description

mixed openssl_csr_new ( array dn, resource &privkey [, array configargs [, array extraattribs]] )

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.

privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify 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 keytypeopenssl.conf equivalentdescription
digest_algstringdefault_mdSelects which digest method to use
x509_extensionsstringx509_extensionsSelects which extensions should be used when creating an x509 certificate
req_extensionsstringreq_extensionsSelects which extensions should be used when creating a CSR
private_key_bitsstringdefault_bitsSpecifies how many bits should be used to generate a private key
private_key_typeintegernoneSpecifies 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_keybooleanencrypt_keyShould 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
// Fill in data for the distinguished name to be used in the cert
// You must change the values of these keys to match your name and
// company, or more precisely, the name and company of the person/site
// that you are generating the certificate for.
// For SSL certificates, the commonName is usually the domain name of
// that will be using the certificate, but for S/MIME certificates,
// the commonName will be the name of the individual who will use the
// certificate.
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365);

// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($sscert, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate

Description

resource openssl_csr_sign ( mixed csr, mixed cacert, mixed priv_key, int days [, array configargs [, int serial]] )

openssl_csr_sign() generates an x509 certificate resource from the csr previously generated by openssl_csr_new(), but it can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export(). The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate. priv_key is the private key that corresponds to cacert. days specifies the length of time for which the generated certificate will be valid, in days. 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)

<?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate.  You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$userscert = openssl_csr_sign($csrdata, $cacert, $privkey, 365);

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5)

openssl_error_string -- Return openSSL error message

Description

string openssl_error_string ( void )

Returns an error message string, or FALSE if there are no more error messages to return.

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

Esempio 1. openssl_error_string() example

<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "<br />\n";
?>

openssl_free_key

(PHP 4 >= 4.0.4, PHP 5)

openssl_free_key -- Free key resource

Description

void openssl_free_key ( resource key_identifier )

openssl_free_key() frees the key associated with the specified key_identifier from memory.

openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_privatekey -- Alias di openssl_pkey_get_private()

Descrizione

This function is an alias of: openssl_pkey_get_private().

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_publickey -- Alias di openssl_pkey_get_public()

Descrizione

This function is an alias of: openssl_pkey_get_public().

openssl_open

(PHP 4 >= 4.0.4, PHP 5)

openssl_open -- Open sealed data

Description

bool openssl_open ( string sealed_data, string &open_data, string env_key, mixed priv_key_id )

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

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid)) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

// free the private key from memory
openssl_free_key($pkeyid);
?>

See also openssl_seal().

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message

Description

bool openssl_pkcs7_decrypt ( string infilename, string outfilename, mixed recipcert [, mixed recipkey] )

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and 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

<?php
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
    echo "decrypted!";
} else {
    echo "failed to decrypt!";
}
?>

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_encrypt -- Encrypt an S/MIME message

Description

bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, int flags [, int cipherid]] )

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

<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = file_get_contents("nighthawk.pem");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "nighthawk@example.com", // keyed syntax
          "From: HQ <hq@example.com>", // indexed syntax
          "Subject" => "Eyes only"))) {
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_sign -- Sign an S/MIME message

Description

bool openssl_pkcs7_sign ( string infilename, string outfilename, mixed signcert, mixed privkey, array headers [, int flags [, string extracerts]] )

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

<?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("file://mycert.pem", "mypassphrase"),
    array("To" => "joes@example.com", // keyed syntax
          "From: HQ <ceo@example.com>", // indexed syntax
          "Subject" => "Eyes only")
    )) {
    // message signed - send it!
    exec(ini_get("sendmail_path") . " < signed.txt");
}
?>

openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message

Description

mixed openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts]]] )

openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file

Description

bool openssl_pkey_export_to_file ( mixed key, string outfilename [, string passphrase [, array configargs]] )

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename. The key can be optionally protected by a passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. 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.

openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export -- Gets an exportable representation of a key into a string

Description

bool openssl_pkey_export ( mixed key, string &out [, string passphrase [, array configargs]] )

openssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference). The key is optionally protected by passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. 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.

openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_free -- Frees a private key

Description

void openssl_pkey_free ( resource key )

This function frees a private key created by openssl_pkey_new().

openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_private -- Get a private key

Description

resource openssl_pkey_get_private ( mixed key [, string passphrase] )

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_privatekey() parses key and prepares it for use by other functions. key can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  2. A PEM formatted private key.

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_public -- Extract public key from certificate and prepare it for use

Description

resource openssl_pkey_get_public ( mixed certificate )

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions. certificate can be one of the following:

  1. an X.509 certificate resource

  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  3. A PEM formatted private key.

openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_new -- Generates a new private key

Description

resource openssl_pkey_new ( [array configargs] )

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public(). You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_decrypt -- Decrypts data with private key

Description

bool openssl_private_decrypt ( string data, string &decrypted, mixed key [, int padding] )

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_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

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_encrypt -- Encrypts data with private key

Description

bool openssl_private_encrypt ( string data, string &crypted, mixed key [, int padding] )

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

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_decrypt -- Decrypts data with public key

Description

bool openssl_public_decrypt ( string data, string &decrypted, mixed key [, int padding] )

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

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_encrypt -- Encrypts data with public key

Description

bool openssl_public_encrypt ( string data, string &crypted, mixed key [, int padding] )

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().

openssl_seal

(PHP 4 >= 4.0.4, PHP 5)

openssl_seal -- Seal (encrypt) data

Description

int openssl_seal ( string data, string &sealed_data, array &env_keys, array pub_key_ids )

Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Esempio 1. openssl_seal() example

<?php
// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);
?>

See also openssl_open().

openssl_sign

(PHP 4 >= 4.0.4, PHP 5)

openssl_sign -- Generate signature

Description

bool openssl_sign ( string data, string &signature, mixed priv_key_id [, int signature_alg] )

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

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

See also openssl_verify().

openssl_verify

(PHP 4 >= 4.0.4, PHP 5)

openssl_verify -- Verify signature

Description

int openssl_verify ( string data, string signature, mixed pub_key_id )

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

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

See also openssl_sign().

openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate

Description

bool openssl_x509_check_private_key ( mixed cert, mixed key )

openssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose

Description

int openssl_x509_checkpurpose ( mixed x509cert, int purpose [, array cainfo [, string untrustedfile]] )

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification. 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

ConstantDescription
X509_PURPOSE_SSL_CLIENTCan the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVERCan the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVERCan the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGNCan the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPTCan the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGNCan the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANYCan the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!

openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export_to_file -- Exports a certificate to file

Description

bool openssl_x509_export_to_file ( mixed x509, string outfilename [, bool notext] )

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

The optional parameter notext 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

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export -- Exports a certificate as a string

Description

bool openssl_x509_export ( mixed x509, string &output [, bool notext] )

openssl_x509_export() stores x509 into a 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

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_free -- Free certificate resource

Description

void openssl_x509_free ( resource x509cert )

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_parse -- Parse an X509 certificate and return the information as an array

Description

array openssl_x509_parse ( mixed x509cert [, bool shortnames] )

openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

Description

resource openssl_x509_read ( mixed x509certdata )

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

CI. Funzioni Oracle

Introduzione

Questa estensione permette l'accesso ai server database Oracle. Vedere anche l'estensione OCI8.


Installazione

You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environment variable ORACLE_HOME.


Costanti predefinite

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.

ORA_BIND_INOUT (integer)

ORA_BIND_IN (integer)

ORA_BIND_OUT (integer)

ORA_FETCHINTO_ASSOC (integer)

ORA_FETCHINTO_NULLS (integer)

Sommario
Ora_Bind -- effettua il binding di una variabile PHP ad un parametro di Oracle
Ora_Close -- chiude un cursore Oracle
ora_columnname -- restituisce il nome di un campo risultato Oracle
ora_columnsize -- restituisce la dimensione di un campo risultato Oracle
ora_columntype -- restituisce il tipo di un campo risultato Oracle
ora_commit -- esegue una transazione Oracle
ora_commitoff -- disabilita il commit automatico
Ora_CommitOn -- abilita il commit automatico
Ora_Do -- Parse, Exec, Fetch
ora_error -- restituisce il messaggio di errore di Oracle
ora_errorcode -- restituisce il codice di errore di Oracle
ora_exec -- esegue dei comandi già analizzati su un cursore Oracle
Ora_Fetch_Into -- Scarica una tupla nell'array specificato
Ora_Fetch -- scarica una tupla di dati da un cursore
ora_getcolumn -- restituisce i dati di un campo acquisito
ora_logoff -- chiude una connessione Oracle
ora_logon -- apre una connessione Oracle
ora_numcols -- Restituisce il numero di campi/colonne
ora_numrows -- Restituisce il numero di tuple
ora_open -- apre un cursore Oracle
ora_parse -- analizza un comando SQL
ora_plogon --  Apre una connessione Oracle permanente
Ora_Rollback -- esegue il rollback della transazione

Ora_Bind

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_Bind -- effettua il binding di una variabile PHP ad un parametro di Oracle

Descrizione

int ora_bind ( int cursor, string PHP variable name, string SQL parameter name, int length [, int type] )

Restituisce 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";
?>

Ora_Close

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_Close -- chiude un cursore Oracle

Descrizione

int ora_close ( int cursor )

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().

ora_columnname

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_columnname -- restituisce il nome di un campo risultato Oracle

Descrizione

string ora_columnname ( int cursor, int column )

Restituisce il nome del campo/colonna column nel cursore cursor. Il nome è restituito in lettere maiuscole. La colonna 0 è la prima.

ora_columnsize

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_columnsize -- restituisce la dimensione di un campo risultato Oracle

Descrizione

int ora_columnsize ( int cursor, int column )

Restituisce la dimensione del campo/colonna column nel cursore cursor. La colonna 0 è la prima.

ora_columntype

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_columntype -- restituisce il tipo di un campo risultato Oracle

Descrizione

string ora_columntype ( resource cursor, int column )

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"

ora_commit

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_commit -- esegue una transazione Oracle

Descrizione

int ora_commit ( int conn )

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().

ora_commitoff

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_commitoff -- disabilita il commit automatico

Descrizione

int ora_commitoff ( int conn )

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().

Ora_CommitOn

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_CommitOn -- abilita il commit automatico

Descrizione

int ora_commiton ( int conn )

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().

Ora_Do

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_Do -- Parse, Exec, Fetch

Descrizione

int ora_do ( int conn, string query )

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().

ora_error

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_error -- restituisce il messaggio di errore di Oracle

Descrizione

string ora_error ( int cursor_or_connection )

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

ora_errorcode

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_errorcode -- restituisce il codice di errore di Oracle

Descrizione

int ora_errorcode ( int cursor_or_connection )

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

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_exec -- esegue dei comandi già analizzati su un cursore Oracle

Descrizione

bool ora_exec ( resource cursor )

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().

Ora_Fetch_Into

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_Fetch_Into -- Scarica una tupla nell'array specificato

Descrizione

int ora_fetch_into ( int cursor, array result [, int flags] )

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.

Esempio 1. ora_fetch_into()

<?php
$risultato = array();
ora_fetch_into($cursore, $results);
echo $risultato[0];
echo $risultato[1];
$risultato = array();
ora_fetch_into($cursore, $risultato, ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
echo $risultato['MioCampo'];
?>

Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().

Ora_Fetch

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_Fetch -- scarica una tupla di dati da un cursore

Descrizione

int ora_fetch ( int cursor )

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().

ora_getcolumn

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_getcolumn -- restituisce i dati di un campo acquisito

Descrizione

mixed ora_getcolumn ( int cursor, mixed column )

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").

ora_logoff

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_logoff -- chiude una connessione Oracle

Descrizione

int ora_logoff ( int connection )

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().

ora_logon

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_logon -- apre una connessione Oracle

Descrizione

resource ora_logon ( string user, string password )

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:

$conn = Ora_Logon("user@TNSNAME", "pass");

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

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_numcols -- Restituisce il numero di campi/colonne

Descrizione

int ora_numcols ( int cursor_ind )

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

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_numrows -- Restituisce il numero di tuple

Descrizione

int ora_numrows ( int cursor_ind )

ora_numrows() restituisce il numero di tuple in un risultato.

ora_open

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_open -- apre un cursore Oracle

Descrizione

int ora_open ( int connection )

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().

ora_parse

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_parse -- analizza un comando SQL

Descrizione

int ora_parse ( int cursor_ind, string sql_statement, int defer )

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().

ora_plogon

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

ora_plogon --  Apre una connessione Oracle permanente

Descrizione

int ora_plogon ( string user, string password )

Stabilisce una connessione permanente tra PHP ed un database Oracle con le username and password specificate.

Vedere anche ora_logon().

Ora_Rollback

(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)

Ora_Rollback -- esegue il rollback della transazione

Descrizione

int ora_rollback ( int connection )

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.

CII. Oracle Functions (PDO_OCI)

Introduzione

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.

PDO_OCI is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Oracle databases through the OCI library.

Sommario
PDO_OCI DSN -- Connecting to Oracle databases

PDO_OCI DSN

(no version information, might be only in CVS)

PDO_OCI DSN -- Connecting to Oracle databases

Descrizione

The PDO_OCI Data Source Name (DSN) is composed of the following elements:

DSN prefix

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.

dbname (Oracle Instant Client)

The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database.

Esempi

Esempio 1. PDO_OCI DSN examples

The following examples show a PDO_OCI DSN for connecting to Oracle databases:
oci:mydb
oci:dbname=//localhost:1521/mydb

CIII. Output Control Functions

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Output Control configuration options

NameDefaultChangeableChangelog
output_buffering"0"PHP_INI_PERDIR 
output_handlerNULLPHP_INI_PERDIRAvailable since PHP 4.0.4.
implicit_flush"0"PHP_INI_ALLPHP_INI_PERDIR in PHP <= 4.2.3.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Nota: You cannot use both mb_output_handler() with ob_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().

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

See also ob_implicit_flush().


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Esempio 1. Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

Nota: When upgrading from PHP 4.1 (and 4.2) to 4.3 that due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.

Sommario
flush -- Flush the output buffer
ob_clean --  Clean (erase) the output buffer
ob_end_clean --  Clean (erase) the output buffer and turn off output buffering
ob_end_flush --  Flush (send) the output buffer and turn off output buffering
ob_flush --  Flush (send) the output buffer
ob_get_clean --  Get current buffer contents and delete current output buffer
ob_get_contents --  Return the contents of the output buffer
ob_get_flush --  Flush the output buffer, return it as a string and turn off output buffering
ob_get_length --  Return the length of the output buffer
ob_get_level --  Return the nesting level of the output buffering mechanism
ob_get_status --  Get status of output buffers
ob_gzhandler --  ob_start callback function to gzip output buffer
ob_implicit_flush --  Turn implicit flush on/off
ob_list_handlers --  List all output handlers in use
ob_start -- Turn on output buffering
output_add_rewrite_var --  Add URL rewriter values
output_reset_rewrite_vars --  Reset URL rewriter values

flush

(PHP 3, PHP 4, PHP 5)

flush -- Flush the output buffer

Description

void flush ( void )

Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.

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.

ob_clean

(PHP 4 >= 4.2.0, PHP 5)

ob_clean --  Clean (erase) the output buffer

Description

void ob_clean ( void )

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

See also ob_flush(), ob_end_flush() and ob_end_clean().

ob_end_clean

(PHP 4, PHP 5)

ob_end_clean --  Clean (erase) the output buffer and turn off output buffering

Description

bool ob_end_clean ( void )

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:

Esempio 1. ob_end_clean() example

<?php
while (@ob_end_clean());
?>

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().

ob_end_flush

(PHP 4, PHP 5)

ob_end_flush --  Flush (send) the output buffer and turn off output buffering

Description

bool ob_end_flush ( void )

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:

Esempio 1. ob_end_flush() example

<?php
  while (@ob_end_flush());
?>

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().

ob_flush

(PHP 4 >= 4.2.0, PHP 5)

ob_flush --  Flush (send) the output buffer

Description

void ob_flush ( void )

This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

This function does not destroy the output buffer like ob_end_flush() does.

See also ob_get_contents(), ob_clean(), ob_end_flush() and ob_end_clean().

ob_get_clean

(PHP 4 >= 4.3.0, PHP 5)

ob_get_clean --  Get current buffer contents and delete current output buffer

Description

string ob_get_clean ( void )

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().

Esempio 1. A simple ob_get_clean() example

<?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?>

Our example will output:

string(11) "hello world"

See also ob_start() and ob_get_contents().

ob_get_contents

(PHP 4, PHP 5)

ob_get_contents --  Return the contents of the output buffer

Description

string ob_get_contents ( void )

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

See also ob_start() and ob_get_length().

ob_get_flush

(PHP 4 >= 4.3.0, PHP 5)

ob_get_flush --  Flush the output buffer, return it as a string and turn off output buffering

Description

string ob_get_flush ( void )

ob_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

<?php
//using output_buffering=On
print_r(ob_list_handlers());

//save buffer in a file
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);

print_r(ob_list_handlers());
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => default output handler
)
Array
(
)

See also ob_end_clean(), ob_end_flush() and ob_list_handlers().

ob_get_length

(PHP 4 >= 4.0.2, PHP 5)

ob_get_length --  Return the length of the output buffer

Description

int ob_get_length ( void )

This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.

See also ob_start() and ob_get_contents().

ob_get_level

(PHP 4 >= 4.2.0, PHP 5)

ob_get_level --  Return the nesting level of the output buffering mechanism

Description

int ob_get_level ( void )

This will return the level of nested output buffering handlers or zero if output buffering is not activated.

See also ob_start() and ob_get_contents().

ob_get_status

(PHP 4 >= 4.2.0, PHP 5)

ob_get_status --  Get status of output buffers

Description

array ob_get_status ( [bool full_status] )

This will return the current status of output buffers. It returns array contains buffer status or FALSE for error.

See also ob_get_level().

ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5)

ob_gzhandler --  ob_start callback function to gzip output buffer

Description

string ob_gzhandler ( string buffer, int mode )

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.

Esempio 1. ob_gzhandler() example

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>

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

(PHP 4, PHP 5)

ob_implicit_flush --  Turn implicit flush on/off

Description

void ob_implicit_flush ( [int flag] )

ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

Turning implicit flushing on will disable output buffering, the output buffers current output will be sent as if ob_end_flush() had been called.

See also flush(), ob_start(), and ob_end_flush().

ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5)

ob_list_handlers --  List all output handlers in use

Description

array ob_list_handlers ( void )

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

<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// anonymous functions
ob_start(create_function('$string', 'return $string;'));
print_r(ob_list_handlers());
ob_end_flush();
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => default output handler
)

See also ob_end_clean(), ob_end_flush(), ob_get_flush(), ob_start().

ob_start

(PHP 4, PHP 5)

ob_start -- Turn on output buffering

Description

bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]] )

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

<?php

function callback($buffer) 
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>

Would produce:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

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().

output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5)

output_add_rewrite_var --  Add URL rewriter values

Description

bool output_add_rewrite_var ( string name, string value )

This function rewrite the URLs and forms with the given variable.

Nota: This function buffers the output.

Esempio 1. output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// a link
echo '<a href="file.php">link</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

Il precedente esempio visualizzerà:

<a href="file.php?var=value">link</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

See also output_reset_rewrite_vars(), ob_flush() and ob_list_handlers().

output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5)

output_reset_rewrite_vars --  Reset URL rewriter values

Description

bool output_reset_rewrite_vars ( void )

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

<?php
session_start();
output_add_rewrite_var('var', 'value');

echo '<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>

Il precedente esempio visualizzerà:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

See also output_add_rewrite_var(), ob_flush(), ob_list_handlers() and session_start().

CIV. Ovrimos SQL Functions

Introduzione

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.


Requisiti

You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Esempi

Esempio 1. Connect to Ovrimos SQL Server and select from a system table

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This will just connect to an Ovrimos SQL server.

Sommario
ovrimos_close -- Closes the connection to ovrimos
ovrimos_commit -- Commits the transaction
ovrimos_connect -- Connect to the specified database
ovrimos_cursor -- Returns the name of the cursor
ovrimos_exec -- Executes an SQL statement
ovrimos_execute -- Executes a prepared SQL statement
ovrimos_fetch_into -- Fetches a row from the result set
ovrimos_fetch_row -- Fetches a row from the result set
ovrimos_field_len -- Returns the length of the output column
ovrimos_field_name -- Returns the output column name
ovrimos_field_num --  Returns the (1-based) index of the output column
ovrimos_field_type --  Returns the (numeric) type of the output column
ovrimos_free_result -- Frees the specified result_id
ovrimos_longreadlen --  Specifies how many bytes are to be retrieved from long datatypes
ovrimos_num_fields -- Returns the number of columns
ovrimos_num_rows --  Returns the number of rows affected by update operations
ovrimos_prepare -- Prepares an SQL statement
ovrimos_result_all --  Prints the whole result set as an HTML table
ovrimos_result -- Retrieves the output column
ovrimos_rollback -- Rolls back the transaction

ovrimos_close

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_close -- Closes the connection to ovrimos

Description

void ovrimos_close ( int connection )

ovrimos_close() is used to close the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.

ovrimos_commit

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_commit -- Commits the transaction

Description

bool ovrimos_commit ( int connection_id )

ovrimos_commit() is used to commit the transaction. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ovrimos_connect

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_connect -- Connect to the specified database

Description

int ovrimos_connect ( string host, string db, string user, string password )

ovrimos_connect() is used to connect to the specified database.

ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of host and 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

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
The above example will connect to the database and print out the specified table.

ovrimos_cursor

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_cursor -- Returns the name of the cursor

Description

string ovrimos_cursor ( int result_id )

ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.

ovrimos_exec

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_exec -- Executes an SQL statement

Description

int ovrimos_exec ( int connection_id, string query )

ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE. Evidently, the SQL statement should not contain parameters.

ovrimos_execute

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_execute -- Executes a prepared SQL statement

Description

bool ovrimos_execute ( int result_id [, array parameters_array] )

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

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_fetch_into -- Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int result_id, array &result_array [, string how [, int rownumber]] )

ovrimos_fetch_into() 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

<?php
$conn=ovrimos_connect("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into($res, &$row)) {
            list($table_id, $table_name) = $row;
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_into($res, &$row)) {
                list($table_id, $table_name) = $row;
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This example will fetch a row.

ovrimos_fetch_row

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_fetch_row -- Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int result_id [, int how [, int row_number]] )

ovrimos_fetch_row() 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

<?php
$conn = ovrimos_connect("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row($res, "First")) {
            $table_id = ovrimos_result($res, 1);
            $table_name = ovrimos_result($res, 2);
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_row($res, "Next")) {
                $table_id = ovrimos_result($res, "table_id");
                $table_name = ovrimos_result($res, "table_name");
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
This will fetch a row and print the result.

ovrimos_field_len

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_len -- Returns the length of the output column

Description

int ovrimos_field_len ( int result_id, int field_number )

ovrimos_field_len() is used to get the length of the output column with number field_number (1-based), in result result_id.

ovrimos_field_name

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_name -- Returns the output column name

Description

string ovrimos_field_name ( int result_id, int field_number )

ovrimos_field_name() returns the output column name at the (1-based) index specified.

ovrimos_field_num

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_num --  Returns the (1-based) index of the output column

Description

int ovrimos_field_num ( int result_id, string field_name )

ovrimos_field_num() returns the (1-based) index of the output column specified by field_name, or FALSE.

ovrimos_field_type

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_field_type --  Returns the (numeric) type of the output column

Description

int ovrimos_field_type ( int result_id, int field_number )

ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified by field_number.

ovrimos_free_result

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_free_result -- Frees the specified result_id

Description

bool ovrimos_free_result ( int result_id )

ovrimos_free_result() frees the specified result_id. Returns TRUE.

ovrimos_longreadlen

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_longreadlen --  Specifies how many bytes are to be retrieved from long datatypes

Description

bool ovrimos_longreadlen ( int result_id, int length )

ovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.

ovrimos_num_fields

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_num_fields -- Returns the number of columns

Description

int ovrimos_num_fields ( int result_id )

ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.

ovrimos_num_rows

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_num_rows --  Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int result_id )

ovrimos_num_rows() returns the number of rows affected by update operations.

ovrimos_prepare

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_prepare -- Prepares an SQL statement

Description

int ovrimos_prepare ( int connection_id, string query )

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

<?php
$conn=ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_prepare($conn, "select table_id, table_name 
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will connect to Ovrimos SQL Server, prepare a statement and the execute it.

ovrimos_result_all

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_result_all --  Prints the whole result set as an HTML table

Description

int ovrimos_result_all ( int result_id [, string format] )

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

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare($conn, "select table_id, table_name 
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will execute an SQL statement and print the result in an HTML table.

Esempio 2. ovrimos_result_all() with meta-information

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "select table_id, table_name 
                                 from sys.tables where table_id = 1");
    if ($res != 0) {
        echo "Statement ok! cursor=" . ovrimos_cursor($res) . "\n";
        $colnb = ovrimos_num_fields($res);
        echo "Output columns=" . $colnb . "\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name($res, $i);
            $type = ovrimos_field_type($res, $i);
            $len = ovrimos_field_len($res, $i);  
            echo "Column " . $i . " name=" . $name . " type=" . $type . " len=" . $len . "\n";
        }
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

Esempio 3. ovrimos_result_all() example

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec($conn, "update test set i=5");
    if ($res != 0) {
        echo "Statement ok!";
        echo ovrimos_num_rows($res)." rows affected\n";
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

ovrimos_result

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_result -- Retrieves the output column

Description

string ovrimos_result ( int result_id, mixed field )

ovrimos_result() retrieves the output column specified by field, either as a string or as an 1-based index. Returns FALSE on failure.

ovrimos_rollback

(PHP 4 >= 4.0.3, PHP 5)

ovrimos_rollback -- Rolls back the transaction

Description

bool ovrimos_rollback ( int connection_id )

ovrimos_rollback() is used to roll back the transaction. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

CV. Paradox File Access

Introduzione

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.


Requisiti

You need at least PHP 5.0.0 and libpx >= 0.1.9. The paradox library (libpx) is available at http://pxlib.sourceforge.net.


Installazione

A short installation note: just type
$ pear install paradox
in your console.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Object oriented API

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 methodEquivalent function
Constructorpx_new()
Destructorpx_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()


Costanti predefinite

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

NameMeaning
PX_FIELD_ALPHACharacter data with fixed length
PX_FIELD_DATEDate
PX_FIELD_SHORTShort integer (2 Bytes)
PX_FIELD_LONGLong integer (4 Bytes)
PX_FIELD_CURRENCYsame as PX_FIELD_NUMBER
PX_FIELD_NUMBERDouble
PX_FIELD_LOGICALBoolean
PX_FIELD_MEMOBLOBBinary large object (not supported)
PX_FIELD_BLOBBinary large object (not supported)
PX_FIELD_FMTMEMOBLOBBinary large object (not supported)
PX_FIELD_OLEOLE object (basically a blob, not supported)
PX_FIELD_GRAPHICGraphic (basically a blob, not supported)
PX_FIELD_TIMEtime
PX_FIELD_TIMESTAMPtimestamp (like the unix timestamp)
PX_FIELD_AUTOINCAuto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCDDecimal number stored in bcd format (not supported)
PX_FIELD_BYTESArray of Bytes with not more than 255 bytes (not supported)
PX_KEYTOLOWER 
PX_KEYTOUPPER 

Tabella 3. Contants for file types

NameMeaning
PX_FILE_INDEX_DBIndexed database
PX_FILE_PRIM_INDEXPrimary index
PX_FILE_NON_INDEX_DBNone indexed database
PX_FILE_NON_INC_SEC_INDEXNone incremental secondary index (not supported)
PX_FILE_SEC_INDEXSecondary index (not supported)
PX_FILE_INC_SEC_INDEXIncremental 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)

Sommario
px_close -- Closes a paradox database
px_create_fp -- Create a new paradox database
px_delete -- Deletes resource of paradox database
px_get_field -- Returns the specification of a single field
px_get_info -- Return lots of information about a paradox file
px_get_parameter -- Gets a parameter
px_get_record -- Returns record of paradox database
px_get_schema -- Returns the database schema
px_get_value -- Gets a value
px_new -- Create a new paradox object
px_numfields -- Returns number of fields in a database
px_numrecords -- Returns number of records in a database
px_open_fp -- Open paradox database
px_put_record -- Stores record into paradox database
px_set_blob_file -- Sets the file where blobs are read from
px_set_parameter -- Sets a parameter
px_set_tablename -- Sets the name of a table (deprecated)
px_set_targetencoding -- Sets the encoding for character fields (deprecated)
px_set_value -- Sets a value
px_timestamp2string --  Converts the timestamp into a string.

px_close

(PECL)

px_close -- Closes a paradox database

Descrizione

bool px_close ( resource pxdoc )

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

px_open_fp()
another_func()
The example at px_new()

px_create_fp

(PECL)

px_create_fp -- Create a new paradox database

Descrizione

bool px_create_fp ( resource pxdoc, resource file, array fielddesc )

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Creating a Paradox database with two fields

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "w+");
$fields = array(array("col1", "S"), array("col2", "I"));
if(!px_create_fp($pxdoc, $fp, $fields)) {
  /* Error handling */
}
px_set_tablename($pxdoc, "testtable");
for($i=-50; $i<50; $i++) {
  $rec = array($i, -$i);
  px_put_record($pxdoc, $rec);
}   
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

px_delete

(PECL)

px_delete -- Deletes resource of paradox database

Descrizione

bool px_delete ( resource pxdoc )

Deletes the resource of the paradox file and frees all memory.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

px_get_field

(PECL)

px_get_field -- Returns the specification of a single field

Descrizione

array px_get_field ( resource pxdoc, int fieldno )

Valori restituiti

Returns the specification of the fieldno'th database field as an associated array. The array contains three fields named name, type, and size.

px_get_info

(PECL)

px_get_info -- Return lots of information about a paradox file

Descrizione

array px_get_info ( resource pxdoc )

Valori restituiti

Returns an associated array with lots of information about a paradox file. This array is likely to extend in the future.

fileversion

Version of file multiplied by 10.

tablename

Name of table as stored in the file.

numrecords

Number of records in this table.

numfields

Number of fields in this table.

headersize

Number of bytes used for the header. This is usually 0x800.

maxtablesize

This value multiplied by 0x400 is the size of a data block in bytes.

numdatablocks

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.

numindexfields

Number of fields used for the primary index. The fields do always start as field number 1.

codepage

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().

px_get_parameter

(PECL)

px_get_parameter -- Gets a parameter

Descrizione

string px_get_parameter ( resource pxdoc, string name )

Gets various parameters.

Elenco dei parametri

The name can be one of the following:

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is being recode into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

px_get_record

(PECL)

px_get_record -- Returns record of paradox database

Descrizione

array px_get_record ( resource pxdoc, int num [, int mode] )

Elenco dei parametri

pxdoc

num

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.

mode

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.

Valori restituiti

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

(PECL)

px_get_schema -- Returns the database schema

Descrizione

array px_get_schema ( resource pxdoc [, int mode] )

px_get_schema() returns the database schema.

Elenco dei parametri

pxdoc

mode

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.

Valori restituiti

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.

px_get_value

(PECL)

px_get_value -- Gets a value

Descrizione

float px_get_value ( resource pxdoc, string name )

Gets various values.

Elenco dei parametri

pxdoc

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

px_new

(PECL)

px_new -- Create a new paradox object

Descrizione

resource px_new ( void )

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.

Valori restituiti

Returns FALSE on failure.

Esempi

Esempio 1. Opening a Paradox database

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "r");
if(!px_open_fp($pxdoc, $fp)) {
  /* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

If you prefer the object oriented API, then the above example will look like the following.

Esempio 2. Opening a Paradox database

<?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc->open_fp($fp)) {
  /* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>

px_numfields

(PECL)

px_numfields -- Returns number of fields in a database

Descrizione

int px_numfields ( resource pxdoc )

Get the number of fields in a database file.

Valori restituiti

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().

px_numrecords

(PECL)

px_numrecords -- Returns number of records in a database

Descrizione

int px_numrecords ( resource pxdoc )

Get the number of records in a database file.

Valori restituiti

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().

px_open_fp

(PECL)

px_open_fp -- Open paradox database

Descrizione

bool px_open_fp ( resource pxdoc, resource file )

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.

Elenco dei parametri

pxdoc

pxdoc is the return value of px_new().

file

file is the return value from fopen() with the actual database file as parameter.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

fopen()
The example at px_new()

px_put_record

(PECL)

px_put_record -- Stores record into paradox database

Descrizione

bool px_put_record ( resource pxdoc, array record )

Stores a record into a paradox database. The record is added at the end of the database.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

px_set_blob_file

(PECL)

px_set_blob_file -- Sets the file where blobs are read from

Descrizione

bool px_set_blob_file ( resource pxdoc, string filename )

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

px_set_parameter

(PECL)

px_set_parameter -- Sets a parameter

Descrizione

bool px_set_parameter ( resource pxdoc, string name, string value )

Sets various parameters.

Elenco dei parametri

pxdoc

name

name can be one of the following.

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is being recode into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

value

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

px_get_info() to determine the DOS code page.

px_set_tablename

(PECL)

px_set_tablename -- Sets the name of a table (deprecated)

Descrizione

void px_set_tablename ( resource pxdoc, string name )

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.

Valori restituiti

Returns NULL on success or FALSE on failure.

px_set_targetencoding

(PECL)

px_set_targetencoding -- Sets the encoding for character fields (deprecated)

Descrizione

bool px_set_targetencoding ( resource pxdoc, string encoding )

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.

Valori restituiti

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.

px_set_value

(PECL)

px_set_value -- Sets a value

Descrizione

bool px_set_value ( resource pxdoc, string name, float value )

Sets various values.

Elenco dei parametri

pxdoc

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

value

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

px_timestamp2string

(PECL)

px_timestamp2string --  Converts the timestamp into a string.

Descrizione

string px_timestamp2string ( resource pxdoc, float value, string format )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

pxdoc

value

format

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

CVI. Parsekit Functions

Introduzione

These functions allow runtime analysis of opcodes compiled from PHP scripts.


Installazione

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/.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

PARSEKIT_QUIET (int)

Return full detail, but without unnecessary NULL extries.

PARSEKIT_SIMPLE (int)

Return shorthand opcode notation.

PARSEKIT_EXTENDED_VALUE (int)

Opnode Flag

PARSEKIT_RESULT_CONST (int)

Opnode Flag

PARSEKIT_RESULT_EA_TYPE (int)

Opnode Flag

PARSEKIT_RESULT_JMP_ADDR (int)

Opnode Flag

PARSEKIT_RESULT_OPARRAY (int)

Opnode Flag

PARSEKIT_RESULT_OPLINE (int)

Opnode Flag

PARSEKIT_RESULT_VAR (int)

Opnode Flag

PARSEKIT_USAGE_UNKNOWN (int)

Opnode Flag

PARSEKIT_ZEND_INTERNAL_CLASS (int)

Class Type

PARSEKIT_ZEND_USER_CLASS (int)

Class Type

PARSEKIT_ZEND_EVAL_CODE (int)

Function Type

PARSEKIT_ZEND_INTERNAL_FUNCTION (int)

Function Type

PARSEKIT_ZEND_OVERLOADED_FUNCTION (int)

Function Type

PARSEKIT_ZEND_OVERLOADED_FUNCTION_TEMPORARY (int) PHP >= 5.0.0

Function Type

PARSEKIT_ZEND_USER_FUNCTION (int)

Function Type

PARSEKIT_IS_CONST (int)

Node Type

PARSEKIT_IS_TMP_VAR (int)

Node Type

PARSEKIT_IS_UNUSED (int)

Node Type

PARSEKIT_IS_VAR (int)

Node Type

PARSEKIT_ZEND_ADD (int)

Opcode

PARSEKIT_ZEND_ADD_ARRAY_ELEMENT (int)

Opcode

PARSEKIT_ZEND_ADD_CHAR (int)

Opcode

PARSEKIT_ZEND_ADD_INTERFACE (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ADD_STRING (int)

Opcode

PARSEKIT_ZEND_ADD_VAR (int)

Opcode

PARSEKIT_ZEND_ASSIGN (int)

Opcode

PARSEKIT_ZEND_ASSIGN_ADD (int)

Opcode

PARSEKIT_ZEND_ASSIGN_BW_AND (int)

Opcode

PARSEKIT_ZEND_ASSIGN_BW_OR (int)

Opcode

PARSEKIT_ZEND_ASSIGN_BW_XOR (int)

Opcode

PARSEKIT_ZEND_ASSIGN_CONCAT (int)

Opcode

PARSEKIT_ZEND_ASSIGN_DIM (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ASSIGN_DIV (int)

Opcode

PARSEKIT_ZEND_ASSIGN_MOD (int)

Opcode

PARSEKIT_ZEND_ASSIGN_MUL (int)

Opcode

PARSEKIT_ZEND_ASSIGN_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ASSIGN_REF (int)

Opcode

PARSEKIT_ZEND_ASSIGN_SL (int)

Opcode

PARSEKIT_ZEND_ASSIGN_SR (int)

Opcode

PARSEKIT_ZEND_ASSIGN_SUB (int)

Opcode

PARSEKIT_ZEND_BEGIN_SILENCE (int)

Opcode

PARSEKIT_ZEND_BOOL (int)

Opcode

PARSEKIT_ZEND_BOOL_NOT (int)

Opcode

PARSEKIT_ZEND_BOOL_XOR (int)

Opcode

PARSEKIT_ZEND_BRK (int)

Opcode

PARSEKIT_ZEND_BW_AND (int)

Opcode

PARSEKIT_ZEND_BW_NOT (int)

Opcode

PARSEKIT_ZEND_BW_OR (int)

Opcode

PARSEKIT_ZEND_BW_XOR (int)

Opcode

PARSEKIT_ZEND_CASE (int)

Opcode

PARSEKIT_ZEND_CAST (int)

Opcode

PARSEKIT_ZEND_CATCH (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_CLONE (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_CONCAT (int)

Opcode

PARSEKIT_ZEND_CONT (int)

Opcode

PARSEKIT_ZEND_DECLARE_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_DECLARE_FUNCTION (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_DECLARE_INHERITED_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_DIV (int)

Opcode

PARSEKIT_ZEND_DO_FCALL (int)

Opcode

PARSEKIT_ZEND_DO_FCALL_BY_NAME (int)

Opcode

PARSEKIT_ZEND_ECHO (int)

Opcode

PARSEKIT_ZEND_END_SILENCE (int)

Opcode

PARSEKIT_ZEND_EXIT (int)

Opcode

PARSEKIT_ZEND_EXT_FCALL_BEGIN (int)

Opcode

PARSEKIT_ZEND_EXT_FCALL_END (int)

Opcode

PARSEKIT_ZEND_EXT_NOP (int)

Opcode

PARSEKIT_ZEND_EXT_STMT (int)

Opcode

PARSEKIT_ZEND_FETCH_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_FETCH_CONSTANT (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_FUNC_ARG (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_IS (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_R (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_RW (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_TMP_VAR (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_UNSET (int)

Opcode

PARSEKIT_ZEND_FETCH_DIM_W (int)

Opcode

PARSEKIT_ZEND_FETCH_FUNC_ARG (int)

Opcode

PARSEKIT_ZEND_FETCH_IS (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_FUNC_ARG (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_IS (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_R (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_RW (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_UNSET (int)

Opcode

PARSEKIT_ZEND_FETCH_OBJ_W (int)

Opcode

PARSEKIT_ZEND_FETCH_R (int)

Opcode

PARSEKIT_ZEND_FETCH_RW (int)

Opcode

PARSEKIT_ZEND_FETCH_UNSET (int)

Opcode

PARSEKIT_ZEND_FETCH_W (int)

Opcode

PARSEKIT_ZEND_FE_FETCH (int)

Opcode

PARSEKIT_ZEND_FE_RESET (int)

Opcode

PARSEKIT_ZEND_FREE (int)

Opcode

PARSEKIT_ZEND_HANDLE_EXCEPTION (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IMPORT_CLASS (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IMPORT_CONST (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IMPORT_FUNCTION (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INCLUDE_OR_EVAL (int)

Opcode

PARSEKIT_ZEND_INIT_ARRAY (int)

Opcode

PARSEKIT_ZEND_INIT_CTOR_CALL (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INIT_FCALL_BY_NAME (int)

Opcode

PARSEKIT_ZEND_INIT_METHOD_CALL (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INIT_STATIC_METHOD_CALL (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_INIT_STRING (int)

Opcode

PARSEKIT_ZEND_INSTANCEOF (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY (int) PHP < 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY_DIM_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY_PROP_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_ISSET_ISEMPTY_VAR (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_IS_EQUAL (int)

Opcode

PARSEKIT_ZEND_IS_IDENTICAL (int)

Opcode

PARSEKIT_ZEND_IS_NOT_EQUAL (int)

Opcode

PARSEKIT_ZEND_IS_NOT_IDENTICAL (int)

Opcode

PARSEKIT_ZEND_IS_SMALLER (int)

Opcode

PARSEKIT_ZEND_IS_SMALLER_OR_EQUAL (int)

Opcode

PARSEKIT_ZEND_JMP (int)

Opcode

PARSEKIT_ZEND_JMPNZ (int)

Opcode

PARSEKIT_ZEND_JMPNZ_EX (int)

Opcode

PARSEKIT_ZEND_JMPZ (int)

Opcode

PARSEKIT_ZEND_JMPZNZ (int)

Opcode

PARSEKIT_ZEND_JMPZ_EX (int)

Opcode

PARSEKIT_ZEND_JMP_NO_CTOR (int)

Opcode

PARSEKIT_ZEND_MOD (int)

Opcode

PARSEKIT_ZEND_MUL (int)

Opcode

PARSEKIT_ZEND_NEW (int)

Opcode

PARSEKIT_ZEND_NOP (int)

Opcode

PARSEKIT_ZEND_OP_DATA (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_POST_DEC (int)

Opcode

PARSEKIT_ZEND_POST_DEC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_POST_INC (int)

Opcode

PARSEKIT_ZEND_POST_INC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_PRE_DEC (int)

Opcode

PARSEKIT_ZEND_PRE_DEC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_PRE_INC (int)

Opcode

PARSEKIT_ZEND_PRE_INC_OBJ (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_PRINT (int)

Opcode

PARSEKIT_ZEND_QM_ASSIGN (int)

Opcode

PARSEKIT_ZEND_RAISE_ABSTRACT_ERROR (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_RECV (int)

Opcode

PARSEKIT_ZEND_RECV_INIT (int)

Opcode

PARSEKIT_ZEND_RETURN (int)

Opcode

PARSEKIT_ZEND_SEND_REF (int)

Opcode

PARSEKIT_ZEND_SEND_VAL (int)

Opcode

PARSEKIT_ZEND_SEND_VAR (int)

Opcode

PARSEKIT_ZEND_SEND_VAR_NO_REF (int)

Opcode

PARSEKIT_ZEND_SL (int)

Opcode

PARSEKIT_ZEND_SR (int)

Opcode

PARSEKIT_ZEND_SUB (int)

Opcode

PARSEKIT_ZEND_SWITCH_FREE (int)

Opcode

PARSEKIT_ZEND_THROW (int) PHP >= 5.0.0

Opcode

PARSEKIT_ZEND_TICKS (int)

Opcode

PARSEKIT_ZEND_UNSET_DIM_OBJ (int)

Opcode

PARSEKIT_ZEND_UNSET_VAR (int)

Opcode

PARSEKIT_ZEND_VERIFY_ABSTRACT_CLASS (int) PHP >= 5.0.0

Opcode

Sommario
parsekit_compile_file -- Compile a string of PHP code and return the resulting op array
parsekit_compile_string -- Compile a string of PHP code and return the resulting op array
parsekit_func_arginfo -- Return information regarding function argument(s)

parsekit_compile_file

(PECL)

parsekit_compile_file -- Compile a string of PHP code and return the resulting op array

Descrizione

array parsekit_compile_file ( string filename [, array &errors [, int options]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Elenco dei parametri

filename

A string containing the name of the file to compile. Similar to the argument to include().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Valori restituiti

Returns a complex multi-layer array structure as detailed below.

Esempi

Esempio 1. parsekit_compile_file() example

<?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?>

Il precedente esempio visualizzerà:

array(5) {
  [0]=>
  string(37) "ZEND_ECHO UNUSED 'Hello World' UNUSED"
  [1]=>
  string(30) "ZEND_RETURN UNUSED NULL UNUSED"
  [2]=>
  string(42) "ZEND_HANDLE_EXCEPTION UNUSED UNUSED UNUSED"
  ["function_table"]=>
  NULL
  ["class_table"]=>
  NULL
}

parsekit_compile_string

(PECL)

parsekit_compile_string -- Compile a string of PHP code and return the resulting op array

Descrizione

array parsekit_compile_string ( string phpcode [, array &errors [, int options]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Elenco dei parametri

phpcode

A string containing phpcode. Similar to the argument to eval().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Valori restituiti

Returns a complex multi-layer array structure as detailed below.

Esempi

Esempio 1. parsekit_compile_string() example

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

Il precedente esempio visualizzerà:

array(20) {
  ["type"]=>
  int(4)
  ["type_name"]=>
  string(14) "ZEND_EVAL_CODE"
  ["fn_flags"]=>
  int(0)
  ["num_args"]=>
  int(0)
  ["required_num_args"]=>
  int(0)
  ["pass_rest_by_reference"]=>
  bool(false)
  ["uses_this"]=>
  bool(false)
  ["line_start"]=>
  int(0)
  ["line_end"]=>
  int(0)
  ["return_reference"]=>
  bool(false)
  ["refcount"]=>
  int(1)
  ["last"]=>
  int(3)
  ["size"]=>
  int(3)
  ["T"]=>
  int(0)
  ["last_brk_cont"]=>
  int(0)
  ["current_brk_cont"]=>
  int(-1)
  ["backpatch_count"]=>
  int(0)
  ["done_pass_two"]=>
  bool(true)
  ["filename"]=>
  string(17) "Parsekit Compiler"
  ["opcodes"]=>
  array(3) {
    [8594800]=>
    array(5) {
      ["opcode"]=>
      int(40)
      ["opcode_name"]=>
      string(9) "ZEND_ECHO"
      ["flags"]=>
      int(768)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &string(4) "Foo
"
      }
      ["lineno"]=>
      int(2)
    }
    ["859484C"]=>
    array(6) {
      ["opcode"]=>
      int(62)
      ["opcode_name"]=>
      string(11) "ZEND_RETURN"
      ["flags"]=>
      int(16777984)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &NULL
      }
      ["extended_value"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
    [8594898]=>
    array(4) {
      ["opcode"]=>
      int(149)
      ["opcode_name"]=>
      string(21) "ZEND_HANDLE_EXCEPTION"
      ["flags"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
  }
}

parsekit_func_arginfo

(PECL)

parsekit_func_arginfo -- Return information regarding function argument(s)

Descrizione

array parsekit_func_arginfo ( mixed 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.

Elenco dei parametri

function

A string describing a function, or an array describing a class/method.

Valori restituiti

Returns an array containing argument information.

Esempi

Esempio 1. parsekit_func_arginfo() example

<?php
function foo($bar, stdClass $baz, &$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?>

Il precedente esempio visualizzerà:

array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(3) "bar"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(3) "baz"
    ["class_name"]=>
    string(8) "stdClass"
    ["allow_null"]=>
    bool(false)
    ["pass_by_reference"]=>
    bool(false)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(4) "bomb"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "bling"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
}

CVII. Process Control Functions

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

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).


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)

WUNTRACED (integer)

SIG_IGN (integer)

SIG_DFL (integer)

SIG_ERR (integer)

SIGHUP (integer)

SIGINT (integer)

SIGQUIT (integer)

SIGILL (integer)

SIGTRAP (integer)

SIGABRT (integer)

SIGIOT (integer)

SIGBUS (integer)

SIGFPE (integer)

SIGKILL (integer)

SIGUSR1 (integer)

SIGSEGV (integer)

SIGUSR2 (integer)

SIGPIPE (integer)

SIGALRM (integer)

SIGTERM (integer)

SIGSTKFLT (integer)

SIGCLD (integer)

SIGCHLD (integer)

SIGCONT (integer)

SIGSTOP (integer)

SIGTSTP (integer)

SIGTTIN (integer)

SIGTTOU (integer)

SIGURG (integer)

SIGXCPU (integer)

SIGXFSZ (integer)

SIGVTALRM (integer)

SIGPROF (integer)

SIGWINCH (integer)

SIGPOLL (integer)

SIGIO (integer)

SIGPWR (integer)

SIGSYS (integer)

SIGBABY (integer)


Esempi

This example forks off a daemon process with a signal handler.

Esempio 1. Process Control Example

<?php
declare(ticks=1);

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork"); 
} else if ($pid) {
     exit(); // we are the parent 
} else {
     // we are the child
}

// detatch from the controlling terminal
if (!posix_setsid()) {
    die("could not detach from terminal");
}

// loop forever performing tasks
while (1) {

    // do something interesting here

}

function sig_handler($signo) 
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

?>

Vedere anche:

A look at the section about POSIX functions may be useful.

Sommario
pcntl_alarm --  Set an alarm clock for delivery of a signal
pcntl_exec --  Executes specified program in current process space
pcntl_fork -- Forks the currently running process
pcntl_getpriority --  Get the priority of any process
pcntl_setpriority --  Change the priority of any process
pcntl_signal -- Installs a signal handler
pcntl_wait --  Waits on or returns the status of a forked child
pcntl_waitpid -- Waits on or returns the status of a forked child
pcntl_wexitstatus --  Returns the return code of a terminated child
pcntl_wifexited --  Returns TRUE if status code represents a successful exit
pcntl_wifsignaled --  Returns TRUE if status code represents a termination due to a signal
pcntl_wifstopped --  Returns TRUE if child process is currently stopped
pcntl_wstopsig --  Returns the signal which caused the child to stop
pcntl_wtermsig --  Returns the signal which caused the child to terminate

pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5)

pcntl_alarm --  Set an alarm clock for delivery of a signal

Description

int pcntl_alarm ( int seconds )

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

(PHP 4 >= 4.2.0, PHP 5)

pcntl_exec --  Executes specified program in current process space

Description

void pcntl_exec ( string path [, array args [, array envs]] )

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.

pcntl_fork

(PHP 4 >= 4.1.0, PHP 5)

pcntl_fork -- Forks the currently running process

Description

int pcntl_fork ( void )

The pcntl_fork() function creates a child process that differs from the parent process only in 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.

Esempio 1. pcntl_fork() example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

?>

See also pcntl_waitpid() and pcntl_signal().

pcntl_getpriority

(PHP 5)

pcntl_getpriority --  Get the priority of any process

Description

int pcntl_getpriority ( [int pid [, int process_identifier]] )

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

(PHP 5)

pcntl_setpriority --  Change the priority of any process

Description

bool pcntl_setpriority ( int priority [, int pid [, int process_identifier]] )

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.

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5)

pcntl_signal -- Installs a signal handler

Description

bool pcntl_signal ( int signo, callback handle [, bool restart_syscalls] )

The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL. The optional restart_syscalls specifies whether system call restarting should be used when this signal arrives and defaults to TRUE.

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

<?php
// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo) 
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

echo"Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n"

?>

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().

pcntl_wait

(PHP 5)

pcntl_wait --  Waits on or returns the status of a forked child

Description

int pcntl_wait ( int &status [, int options] )

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().

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5)

pcntl_waitpid -- Waits on or returns the status of a forked child

Description

int pcntl_waitpid ( int pid, int &status [, int options] )

The pcntl_waitpid() function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

The value of pid can be one of the following:

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().

pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wexitstatus --  Returns the return code of a terminated child

Description

int pcntl_wexitstatus ( int status )

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifexited().

pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifexited --  Returns TRUE if status code represents a successful exit

Description

bool pcntl_wifexited ( int status )

Returns TRUE if the child status code represents a successful exit.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wexitstatus().

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifsignaled --  Returns TRUE if status code represents a termination due to a signal

Description

bool pcntl_wifsignaled ( int status )

Returns TRUE if the child process exited because of a signal which was not caught.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_signal().

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifstopped --  Returns TRUE if child process is currently stopped

Description

bool pcntl_wifstopped ( int status )

Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid().

pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wstopsig --  Returns the signal which caused the child to stop

Description

int pcntl_wstopsig ( int status )

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifstopped().

pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wtermsig --  Returns the signal which caused the child to terminate

Description

int pcntl_wtermsig ( int status )

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().

CVIII. Funzioni per le espressioni regolari (Perl compatibili)

Introduzione

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.


Requisiti

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/.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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

costantedescrizione
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().

Esempi

Esempio 1. Esempi di espressioni di riconoscimento valide

  • /<\/\w+>/

  • |(\d{3})-\d+|Sm

  • /^(?i)php[34]/

  • {^\s+(\s+)?$}

Esempio 2. Esempi di espressioni errate

  • /href='(.*)' - manca il delimitatore finale

  • /\w+\s*\w+/J - il modificatore 'J' è sconosciuto

  • 1-\d3-\d3-\d4| - manca il delimitatore iniziale

Sommario
Modificatori di criterio (Pattern Modifiers) -- Questo capitolo descrive i possibili modificatori applicabili ad una espressione regolare
Sintassi delle espressioni regolari -- Descrizione della sintassi utilizzata da PCRE per la definizione delle espressioni regolari
preg_grep --  Restituisce una matrice degli elementi riconosciuti tramite le espressioni regolari
preg_match_all -- Esegue un riconoscimento globale con le espressioni regolari
preg_match -- Riconoscimento con espressioni regolari
preg_quote -- Inserisce il carattere di escape nei caratteri delle espressioni regolari
preg_replace_callback -- Esegue ricerche e sostituzioni con espressioni regolari usando il callback
preg_replace -- Esegue una ricerca ed una sostituzione con le espressioni regolari
preg_split -- Suddivisione di una stringa tramite le espressioni regolari

Modificatori di criterio (Pattern Modifiers)

Modificatori di criterio (Pattern Modifiers) -- Questo capitolo descrive i possibili modificatori applicabili ad una espressione regolare

Descrizione

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.

Sintassi delle espressioni regolari

Sintassi delle espressioni regolari -- Descrizione della sintassi utilizzata da PCRE per la definizione delle espressioni regolari

Descrizione

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.

Differenze rispetto a Perl

In questo capitolo saranno descritte le differenze rispetto a Perl 5.005.

  1. 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.

  2. 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".

  3. 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.

  4. 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.

  5. 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.

  6. L'asserzione di Perl \G non è supportata.

  7. Ovviamente PCRE non supporta il costrutto (?{code}).

  8. 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.

  9. 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.

  10. PCRE prevede alcune estensione alla gestione delle espressioni regolari di Perl:

    1. 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.

    2. Se viene settato PCRE_DOLLAR_ENDONLY e non viene attivato PCRE_MULTILINE, il meta-carattere $ indica soltanto la fine della stringa.

    3. Se si attiva PCRE_EXTRA, un carattere backslash (\) seguito da una lettera che non abbia un significato speciale genera un errore.

    4. 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 "?".

Dettagli sulle espressioni regolari

Introduzione

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.

Meta-caratteri

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

La parte del criterio che si trova tra parentesi quadrate viene detta "classe di caratteri". In una classe di caratteri i meta-caratteri previsti sono:

\

carattere di escape generico con diversi utilizzi

^

nega la classe, ma solo se posto all'inizio

-

indica un intervallo

]

chiude la classe di caratteri

Le sezioni seguenti descriveranno l'uso di ciascuno dei meta-caratteri.

Backslash

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.

\a

allarme, il carattere BEL (hex 07)

\cx

"control-x", dove x è un qualsiasi carattere

\e

escape (hex 1B)

\f

salto pagina (hex 0C)

\n

"a capo" (newline) (hex 0A)

\r

carriage return (hex 0D)

\t

tabulazione (hex 09)

\xhh

carattere il cui codice esadecimale è hh

\ddd

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:

\040

è un'altro modo per indicare uno spazio

\40

ha il medesimo significato dell'esempio precedente che non vi sono 40 sotto-criteri

\7

è sempre un riferimento all'indietro

\11

può essere un riferimento all'indietro o un'altro modo per indicare il carattere di tabulazione

\011

è ancora il carattere di tabulazione

\0113

il carattere di tabulazione seguito da "3"

\113

è il carattere con il codice ottale 113 (poiché non ci possono essere più di 99 riferimenti all'indietro)

\377

è un byte con tutti i bit a 1

\81

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:

\d

qualsiasi cifra decimale

\D

qualsiasi carattere che non sia una cifra decimale

\s

qualsiasi carattere identificato come spazio bianco

\S

qualsiasi carattere che non sia identificato come spazio bianco

\w

qualsiasi carattere che sia una "parola" (word)

\W

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:

\b

limite di una parola

\B

non limite di una parola

\A

inizio dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)

\Z

fine dell'oggetto di ricerca oppure newline alla fine (a prescindere dalla modalità multi-linea)

\z

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.

I caratteri "^" e "$"

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.

FULL STOP

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.

Parentesi quadrate

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 (\).

Barra verticale (|)

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.

Settaggio delle opzioni interne

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
mper PCRE_MULTILINE
sper PCRE_DOTALL
xper PCRE_EXTENDED
Uper 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.

Sotto-regole

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.

Ripetizioni

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:

Tabella 2. Indicatore di occorrenza

*equivale a {0,}
+equivale a {1,}
?equivale a {0,1}

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".

Riferimenti all'indietro

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.

Asserzioni

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.

Sotto-regole a riconoscimento singolo (Once-only 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.

Sotto-regole condizionali (Conditional subpatterns)

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.

Commenti

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".

Criteri ricorsivi

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.

Performances

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.

preg_grep

(PHP 4, PHP 5)

preg_grep --  Restituisce una matrice degli elementi riconosciuti tramite le espressioni regolari

Descrizione

array preg_grep ( string espressione_regolare, array testo [, int flags] )

La 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:

PREG_GREP_INVERT

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.

Esempio 1. Esempio di preg_grep()

<?php
// esempio di restituzione di tutti gli elementi della matrice
// contenenti numeri in virgola mobile
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>

preg_match_all

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_match_all -- Esegue un riconoscimento globale con le espressioni regolari

Descrizione

int preg_match_all ( string espressione_regolare, string testo, array &TestiRiconosciuti [, int flags [, int offset]] )

La 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):

PREG_PATTERN_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.

PREG_SET_ORDER

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.

PREG_OFFSET_CAPTURE

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 1. Esempio di come ottenere tutti i numeri di telefono da un testo.

<?php
preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $numeri);
?>

Esempio 2. Ricerca di tag HTML

<?php
// Il parametro \\2 è un esempio di riferimento all'indietro. Questo dato informa la 
// libreria pcre che deve considerare il secondo set di parentesi tonde (in questo 
// caso il testo "([\w]+)"). Il backslash (\) aggiuntivo è reso obbligatorio dall'uso
// dei doppi apici.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches);

for ($i=0; $i< count($matches[0]); $i++) {
   echo "intero criterio: ".$matches[0][$i]."\n";
   echo "parte 1: " . $matches[1][$i] . "\n";
   echo "parte 2: " . $matches[3][$i] . "\n";
   echo "parte 3: " . $matches[4][$i] . "\n\n";
}
?>

Questo esempio visualizzerà:

intero criterio: <b>bold text</b>
parte 1: <b>
parte 2: bold text
parte 3: </b>

intero criterio: <a href=howdy.html>click me</a>
parte 1: <a href=howdy.html>
parte 2: click me
parte 3: </a>

Vedere anche preg_match(), preg_replace() e preg_split().

preg_match

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_match -- Riconoscimento con espressioni regolari

Descrizione

mixed preg_match ( string criterio, string testo [, array &testi_riconosciuti [, int flags [, int offset]]] )

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:

PREG_OFFSET_CAPTURE

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.

Il parametro flags è 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 1. Ricerca del testo "php"

<?php
// La lettera "i" dopo i delimitatori indica una ricerca case-insensitive
if (preg_match("/php/i", "PHP è il linguaggio scelto.")) {
    echo "Il riconoscimento è avvenuto.";
} else {
    echo "Testo non riconosciuto.";
}
?>

Esempio 2. Cerca la parola "web"

<?php
// La lettera \b nel criterio indica i limiti della parola. Così verrà riconosciuta solo
// la parola "web" e non parte di una parola più lunga come "webbing" oppure "cobweb"
if (preg_match("/\bweb\b/i", "PHP è un linguaggio di programmazione per il web scelto da molti.")) {
    echo "Il riconoscimento è avvenuto.";
} else {
    echo "Testo non riconosciuto.";
}
if (preg_match("/\bweb\b/i", "PHP è un linguaggio di programmazione installato su molti website")) {
    echo "Il riconoscimento è avvenuto.";
} else {
    echo "Testo non riconosciuto.";
}
?>

Esempio 3. Estrapolazione del dominio da un URL

<?php
// come ottenere il nome dell'host da un URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$NomeHost = $matches[2];
// come ottenere gli ultimi due segmenti del nome dell'host
preg_match("/[^\.\/]+\.[^\.\/]+$/",$NomeHost,$matches);
echo "Nome del dominio:  {$matches[0]}\n";
?>

L'esempio visualizzerà:

Nome del dominio: php.net

Vedere anche preg_match_all(), preg_replace() e preg_split().

preg_quote

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_quote -- Inserisce il carattere di escape nei caratteri delle espressioni regolari

Descrizione

string preg_quote ( string stringa [, string delimitatori] )

La 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 1. Esempio di preg_quote()

<?php
$keywords = "$40 for a g3/400";
$keywords = preg_quote($keywords, "/");
echo $keywords; // returns \$40 for a g3\/400
?>

Esempio 2. Esempio di come rendere in corsivo una qualsiasi parola di un testo

<?php
// In questo esempio, la funzione preg_quote($word) viene usata
// per impedire agli asterischi di avere il loro significato
// speciale per le espressioni regolari.

$testo = "Questo libro è *molto* difficile da trovare.";
$parola = "*molto*";
$testo = preg_replace("/". preg_quote($parola) . "/",
                          "<i>" . $parola . "</i>",
                          $testo);
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5)

preg_replace_callback -- Esegue ricerche e sostituzioni con espressioni regolari usando il callback

Descrizione

mixed preg_replace_callback ( mixed espressione_regolare, callback callback, mixed testo [, int limite] )

Fondamentalmente 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()

<?php 
// questo test è stato usato nel 2002
// lo si vuole avere aggiornato per il 2003
$text = "April fools day is 04/01/2002\n"; 
$text.= "Last christmas was 12/24/2001\n"; 
// la funzione di callback
function next_year($matches) 
{ 
// come solito: $matches[0] è il testo riconosciuto completo
// $matches[1] la parte riconosciuta per il primo criterio
// racchiuso in '(...)' e così via
return $matches[1].($matches[2]+1); 
}
echo preg_replace_callback(
     "|(\d{2}/\d{2}/)(\d{4})|",
     "next_year",
     $text);
// il risultato sarà:
// April fools day is 04/01/2003
// Last christmas was 12/24/2002
?>

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()

<?php
/* Un filtro da linea di comando stile Unix che converte
 * la maiuscole poste all'inizio delle parole in minuscolo */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
      $line = fgets($fp);
      $line = preg_replace_callback(
             '|<p>\s*\w|',
             create_function(
                  // l'apice singolo è essenziale qui, 
                  // o in alternativa occorre usare la sequenza di escape \$ 
                  // per tutte le occorrenze di $ 
                 '$matches',
                 'return strtolower($matches[0]);' 
                 ), 
               $line 
      );
      echo $line; 
}
fclose($fp);
?>

Vedere anche preg_replace() create_function(), e information about the callback type.

preg_replace

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_replace -- Esegue una ricerca ed una sostituzione con le espressioni regolari

Descrizione

mixed preg_replace ( mixed espressione_regolare, mixed sostituto, mixed testo [, int limite] )

La 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.

Esempio 1. Uso dei riferimenti all'indietro seguiti da numeri

<?php 
$string = "April 15, 2003"; 
$pattern = "/(\w+) (\d+), (\d+)/i";
$replacement = "\${1}1,\$3";
echo preg_replace($pattern, $replacement, $string);
?>

This example will output :

April1,2003

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()

<?php
$string = "The quick brown fox jumped over the lazy dog.";
 
$patterns[0] = "/quick/";
$patterns[1] = "/brown/";
$patterns[2] = "/fox/";
 
$replacements[2] = "bear";
$replacements[1] = "black";
$replacements[0] = "slow";
 
echo preg_replace($patterns, $replacements, $string);
?>

Output:

The bear black slow jumped over the lazy dog.

Utilizzando ksort su entrambe le matrici otteniamo cio che vogliamo.

<?php 
ksort($patterns);
ksort($replacements);
 
echo preg_replace($patterns, $replacements, $string);
?>

Output :

The slow black bear jumped over the lazy dog.

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 3. Esempi di sostituzione di valori

<?php
$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",
                   "/^\s*{(\w+)}\s*=/");
$replace = array ("\\3/\\4/\\1\\2", "$\\1 =");
echo preg_replace($patterns, $replace, "{startDate} = 1999-5-27");
?>

Questo esempio visualizzerà:

$startDate = 5/27/1999

Esempio 4. Utilizzo del modificatore /e

<?php
preg_replace("/(<\/?)(\w+)([^>]*>)/e",
              "'\\1'.strtoupper('\\2').'\\3'", 
              $html_body);
?>

Nell'esempio precedente tutti i tag HTML presenti nel testo di input saranno convertiti in maiuscolo.

Esempio 5. Esempio di conversione di codice HTML in testo

<?php
// $document contiene un documento HTML.
// In questo esempio la funzione rimuove i tag HTML,
// le sezioni javascript e gli spazi bianchi.
// Inoltre si convertirà le entità HTML nella loro
// rappresentazione testuale.
$search = array ("'<script[^>]*?>.*?</script>'si",  // Rimozione del javascript
                 "'<[\/\!]*?[^<>]*?>'si",           // Rimozione dei tag HTML
                 "'([\r\n])[\s]+'",                 // Rimozione degli spazi bianchi
                 "'&(quot|#34);'i",                 // Sostituzione delle entità HTML
                 "'&(amp|#38);'i",
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'&#(\d+);'e");                    // Valuta come codice PHP

$replace = array ("",
                  "",
                  "\\1",
                  "\"",
                  "&",
                  "<",
                  ">",
                  " ",
                  chr(161),
                  chr(162),
                  chr(163),
                  chr(169),
                  "chr(\\1)");

$text = preg_replace($search, $replace, $document);
?>

Nota: Il parametro limite è stato aggiunto successivamente alla versione 4.0.1pl2 di PHP.

Vedere anche preg_match(), preg_match_all() e preg_split().

preg_split

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_split -- Suddivisione di una stringa tramite le espressioni regolari

Descrizione

array preg_split ( string espressione_regolare, string testo [, int limite [, int flags]] )

La 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 |):

PREG_SPLIT_NO_EMPTY

Specificando questo flag, la funzione preg_split() restituisce spezzoni di testo non vuoti.

PREG_SPLIT_DELIM_CAPTURE

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.

PREG_SPLIT_OFFSET_CAPTURE

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 1. Esempio di preg_split(): Come ottenere le parti di un testo.

<?php
// Suddivide la seguente frase in base alla presenza di virgole, spazi bianchi,
// e altri caratteri speciali quali \r, \t, \n ed \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
?>

Esempio 2. Esempio di suddivisione di un testo in caratteri.

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

Esempio 3. Suddivisione di una stringa in testi riconosciuti con i relativi offset.

<?php
$str = 'hypertext language programming'; 
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); 
print_r($chars); 
?>

visualizzerà

Array 
( 
    [0] => Array 
        ( 
            [0] => hypertext 
            [1] => 0 
        ) 
  
    [1] => Array 
        ( 
            [0] => language 
            [1] => 10 
        ) 
  
    [2] => Array 
        ( 
            [0] => programming 
            [1] => 19 
        ) 
  
)

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().

CIX. PDF functions

Introduzione

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.


Requisiti

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.


Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Confusion with old PDFlib versions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons, this binding for PDFlib still supports the old functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions.

Tabella 1. Deprecated functions and their replacements

Old functionReplacement
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.


Esempi

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

<?php
$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo "<A HREF=getpdf.php>finished</A>";
?>
The script getpdf.php just returns the pdf document.

Esempio 2. Outputting a precalculated PDF

<?php
$len = filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>

The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in-memory creation feature of PDFlib to alleviate the need to use temporary files. The example was converted to PHP from the PDFlib example. (The same example is available in the CLibPDF documentation.)

Esempio 3. pdfclock example from PDFlib distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 10;

$pdf = pdf_new();

if (!pdf_open_file($pdf, "")) {
    echo error;
    exit;
};

pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Creator", "pdf_clock.php");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Analog Clock");

while ($pagecount-- > 0) {
    pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

    pdf_set_parameter($pdf, "transition", "wipe");
    pdf_set_value($pdf, "duration", 0.5);
  
    pdf_translate($pdf, $radius + $margin, $radius + $margin);
    pdf_save($pdf);
    pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

    /* minute strokes */
    pdf_setlinewidth($pdf, 2.0);
    for ($alpha = 0; $alpha < 360; $alpha += 6) {
        pdf_rotate($pdf, 6.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin/3, 0.0);
        pdf_stroke($pdf);
    }

    pdf_restore($pdf);
    pdf_save($pdf);

    /* 5 minute strokes */
    pdf_setlinewidth($pdf, 3.0);
    for ($alpha = 0; $alpha < 360; $alpha += 30) { 
        pdf_rotate($pdf, 30.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin, 0.0);
        pdf_stroke($pdf);
    }

    $ltime = getdate();

    /* draw hour hand */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['minutes']/60.0)+$ltime['hours']-3.0)*30.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius/2, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* draw minute hand */
    pdf_save($pdf);
    pdf_rotate($pdf,-(($ltime['seconds']/60.0)+$ltime['minutes']-15.0)*6.0);
    pdf_moveto($pdf, -$radius/10, -$radius/20);
    pdf_lineto($pdf, $radius * 0.8, 0.0);
    pdf_lineto($pdf, -$radius/10, $radius/20);
    pdf_closepath($pdf);
    pdf_fill($pdf);
    pdf_restore($pdf);

    /* draw second hand */
    pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
    pdf_setlinewidth($pdf, 2);
    pdf_save($pdf);
    pdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
    pdf_moveto($pdf, -$radius/5, 0.0);
    pdf_lineto($pdf, $radius, 0.0);
    pdf_stroke($pdf);
    pdf_restore($pdf);

    /* draw little circle at center */
    pdf_circle($pdf, 0, 0, $radius/30);
    pdf_fill($pdf);

    pdf_restore($pdf);

    pdf_end_page($pdf);

    # to see some difference
    sleep(1);
}

pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
echo $buf;

pdf_delete($pdf);
?>


Vedere anche:

Nota: An alternative PHP module for PDF document creation based on FastIO's ClibPDF is available. Please see the ClibPDF section for details. Note that ClibPDF has a slightly different API than PDFlib.

Sommario
pdf_add_annotation -- Deprecated: Adds annotation
pdf_add_bookmark -- Adds bookmark for current page
pdf_add_launchlink -- Add a launch annotation for current page
pdf_add_locallink -- Add a link annotation for current page
pdf_add_note -- Sets annotation for current page
pdf_add_outline -- Deprecated: Adds bookmark for current page
pdf_add_pdflink -- Adds file link annotation for current page
pdf_add_thumbnail -- Adds thumbnail for current page
pdf_add_weblink -- Adds weblink for current page
pdf_arc -- Draws an arc (counterclockwise)
pdf_arcn -- Draws an arc (clockwise)
pdf_attach_file -- Adds a file attachment for current page
pdf_begin_page -- Starts new page
pdf_begin_pattern -- Starts new pattern
pdf_begin_template -- Starts new template
pdf_circle -- Draws a circle
pdf_clip -- Clips to current path
pdf_close_image -- Closes an image
pdf_close_pdi_page --  Close the page handle
pdf_close_pdi --  Close the input PDF document
pdf_close -- Closes a pdf resource
pdf_closepath_fill_stroke -- Closes, fills and strokes current path
pdf_closepath_stroke -- Closes path and draws line along path
pdf_closepath -- Closes path
pdf_concat -- Concatenate a matrix to the CTM
pdf_continue_text -- Outputs text in next line
pdf_curveto -- Draws a curve
pdf_delete -- Deletes a PDF object
pdf_end_page -- Ends a page
pdf_end_pattern -- Finish pattern
pdf_end_template -- Finish template
pdf_endpath -- Deprecated: Ends current path
pdf_fill_stroke -- Fills and strokes current path
pdf_fill -- Fills current path
pdf_findfont -- Prepare font for later use with pdf_setfont()
pdf_get_buffer -- Fetch the buffer containing the generated PDF data
pdf_get_font -- Deprecated: font handling
pdf_get_fontname -- Deprecated: font handling
pdf_get_fontsize -- Deprecated: font handling
pdf_get_image_height -- Deprecated: returns height of an image
pdf_get_image_width -- Deprecated: Returns width of an image
pdf_get_majorversion --  Returns the major version number of the PDFlib
pdf_get_minorversion --  Returns the minor version number of the PDFlib
pdf_get_parameter -- Gets certain parameters
pdf_get_pdi_parameter -- Get some PDI string parameters
pdf_get_pdi_value -- Gets some PDI numerical parameters
pdf_get_value -- Gets certain numerical value
pdf_initgraphics -- Resets graphic state
pdf_lineto -- Draws a line
pdf_makespotcolor -- Makes a spotcolor
pdf_moveto -- Sets current point
pdf_new -- Creates a new pdf resource
pdf_open_ccitt -- Opens a new image file with raw CCITT data
pdf_open_file -- Opens a new pdf object
pdf_open_gif -- Deprecated: Opens a GIF image
pdf_open_image_file -- Reads an image from a file
pdf_open_image -- Versatile function for images
pdf_open_jpeg -- Deprecated: Opens a JPEG image
pdf_open_memory_image -- Opens an image created with PHP's image functions
pdf_open_pdi_page --  Prepare a page
pdf_open_pdi --  Opens a PDF file
pdf_open_png --  Deprecated: Opens a PNG image
pdf_open_tiff -- Deprecated: Opens a TIFF image
pdf_open -- Deprecated: Open a new pdf object
pdf_place_image -- Places an image on the page
pdf_place_pdi_page -- Places an image on the page
pdf_rect -- Draws a rectangle
pdf_restore -- Restores formerly saved environment
pdf_rotate -- Sets rotation
pdf_save -- Saves the current environment
pdf_scale -- Sets scaling
pdf_set_border_color -- Sets color of border around links and annotations
pdf_set_border_dash -- Sets dash style of border around links and annotations
pdf_set_border_style -- Sets style of border around links and annotations
pdf_set_char_spacing -- Deprecated: Sets character spacing
pdf_set_duration -- Deprecated: Sets duration between pages
pdf_set_font -- Deprecated: Selects a font face and size
pdf_set_horiz_scaling -- Sets horizontal scaling of text [deprecated]
pdf_set_info_author --  Deprecated: Fills the author field of the document
pdf_set_info_creator --  Deprecated: Fills the creator field of the document
pdf_set_info_keywords --  Deprecated: Fills the keywords field of the document
pdf_set_info_subject --  Deprecated: Fills the subject field of the document
pdf_set_info_title --  Deprecated: Fills the title field of the document
pdf_set_info -- Fills a field of the document information
pdf_set_leading -- Deprecated: Sets distance between text lines
pdf_set_parameter -- Sets certain parameters
pdf_set_text_matrix -- Deprecated: Sets the text matrix
pdf_set_text_pos -- Sets text position
pdf_set_text_rendering -- Deprecated: Determines how text is rendered
pdf_set_text_rise -- Deprecated: Sets the text rise
pdf_set_value -- Sets certain numerical value
pdf_set_word_spacing -- Deprecated: Sets spacing between words
pdf_setcolor -- Sets fill and stroke color
pdf_setdash -- Sets dash pattern
pdf_setflat -- Sets flatness
pdf_setfont -- Set the current font
pdf_setgray_fill -- Sets filling color to gray value
pdf_setgray_stroke -- Sets drawing color to gray value
pdf_setgray -- Sets drawing and filling color to gray value
pdf_setlinecap -- Sets linecap parameter
pdf_setlinejoin -- Sets linejoin parameter
pdf_setlinewidth -- Sets line width
pdf_setmatrix -- Sets current transformation matrix
pdf_setmiterlimit -- Sets miter limit
pdf_setpolydash -- Deprecated: Sets complicated dash pattern
pdf_setrgbcolor_fill -- Sets filling color to rgb color value
pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
pdf_setrgbcolor -- Sets drawing and filling color to rgb color value
pdf_show_boxed -- Output text in a box
pdf_show_xy -- Output text at given position
pdf_show -- Output text at current position
pdf_skew -- Skews the coordinate system
pdf_stringwidth -- Returns width of text using current font
pdf_stroke -- Draws line along path
pdf_translate -- Sets origin of coordinate system

pdf_add_annotation

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_add_annotation -- Deprecated: Adds annotation

Description

This function is deprecated, use pdf_add_note() instead.

pdf_add_bookmark

(PHP 4 >= 4.0.1, PECL)

pdf_add_bookmark -- Adds bookmark for current page

Description

int pdf_add_bookmark ( resource pdfdoc, string text, int parent, int open )

Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0. Parameters parent and open are optional before PHP 4.3.5 or with PDFlib less than 5.

Esempio 1. pdf_add_bookmark() example

<?php
// create a new PDF

$pdf = pdf_new();
pdf_open_file($pdf);
pdf_set_info($pdf, "Author", "Bob Nijman");

// begin a new page
pdf_begin_page($pdf, 300, 300);

// add a top-level bookmark
$bookmark = pdf_add_bookmark($pdf, "People");

// add a nested bookmark
pdf_add_bookmark($pdf, "Rasmus", $bookmark);

// and some text
pdf_set_font($pdf, "Helvetica", 20, "host");
$text = "This is R's page";
$width = pdf_stringwidth($pdf, $text);
pdf_set_text_pos($pdf, (300-$width)/2, 100);
pdf_show($pdf, $text);

// close the page and the PDF
pdf_end_page($pdf); 
pdf_close($pdf);

?>

pdf_add_launchlink

(PHP 4 >= 4.0.5, PECL)

pdf_add_launchlink -- Add a launch annotation for current page

Description

bool pdf_add_launchlink ( resource pdfdoc, float llx, float lly, float urx, float ury, string filename )

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().

pdf_add_locallink

(PHP 4 >= 4.0.5, PECL)

pdf_add_locallink -- Add a link annotation for current page

Description

bool pdf_add_locallink ( resource pdfdoc, float lowerleftx, float lowerlefty, float upperrightx, float upperrighty, int page, string dest )

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().

pdf_add_note

(PHP 4 >= 4.0.5, PECL)

pdf_add_note -- Sets annotation for current page

Description

bool pdf_add_note ( resource pdfdoc, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open )

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

<?php
$pdfdoc = pdf_new();
if (!pdf_open_file($pdfdoc, '')) {
  echo 'error!';
  exit;
}
pdf_begin_page($pdfdoc, 300, 300);
if ($font = pdf_findfont($pdfdoc, 'Times-Roman', 'host', 0)) {
  pdf_setfont($pdfdoc, $font, 10);
}
pdf_set_value($pdfdoc, 'textrendering', 0);
pdf_add_note($pdfdoc, 100, 100, 180, 40, 'Note Content', 'Title', 'help', 0);
pdf_show_xy($pdfdoc, 'Example', 100, 100);
pdf_end_page($pdfdoc);
pdf_close($pdfdoc);
$data = pdf_get_buffer($pdfdoc);
header('Content-type: application/pdf');
header('Content-disposition: inline; filename=example.pdf');
header('Content-length: '.strlen($data));
echo $data;
?>

pdf_add_outline

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_add_outline -- Deprecated: Adds bookmark for current page

Description

This function is deprecated, use pdf_add_bookmark() instead.

pdf_add_pdflink

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_add_pdflink -- Adds file link annotation for current page

Description

bool pdf_add_pdflink ( resource pdfdoc, float bottom_left_x, float bottom_left_y, float up_right_x, float up_right_y, string filename, int page, string dest )

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().

pdf_add_thumbnail

(PHP 4 >= 4.0.5, PECL)

pdf_add_thumbnail -- Adds thumbnail for current page

Description

bool pdf_add_thumbnail ( resource pdfdoc, int image )

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().

pdf_add_weblink

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_add_weblink -- Adds weblink for current page

Description

bool pdf_add_weblink ( resource pdfdoc, float lowerleftx, float lowerlefty, float upperrightx, float upperrighty, string url )

Add a weblink annotation to a target url on the Web. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_arc

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_arc -- Draws an arc (counterclockwise)

Description

bool pdf_arc ( resource pdfdoc, float x, float y, float r, float alpha, float beta )

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

<?php
// prepare document
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);

// an outlined arc
pdf_arc($pdf, 200, 700, 100, 0, 90);
pdf_stroke($pdf);

// a filled arc
pdf_arc($pdf, 200, 700, 50, 0, 90);
pdf_fill($pdf);

// an outlined and filled arc
pdf_setcolor($pdf, "fill", "gray", 0.8);
pdf_arc($pdf, 400, 700, 50, 0, 90);
pdf_fill_stroke($pdf);

// finish document
pdf_end_page($pdf);
pdf_close($pdf);

header("Content-type: application/pdf");
echo pdf_get_buffer($pdf);

pdf_delete($pdf);
?>

See also: pdf_arcn(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().

pdf_arcn

(PHP 4 >= 4.0.5, PECL)

pdf_arcn -- Draws an arc (clockwise)

Description

bool pdf_arcn ( resource pdfdoc, float x, float y, float r, float alpha, float beta )

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

<?php

// prepare document
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);

// an outlined arcn
pdf_arcn($pdf, 200, 700, 100, 0, 90);
pdf_stroke($pdf);

// a filled arcn
pdf_arcn($pdf, 200, 700, 50, 0, 90);
pdf_fill($pdf);

// an outlined and filled arcn
pdf_setcolor($pdf, "fill", "gray", 0.8);
pdf_arcn($pdf, 400, 700, 50, 0, 90);
pdf_fill_stroke($pdf);

// finish document
pdf_end_page($pdf);
pdf_close($pdf);

header("Content-type: application/pdf");
echo pdf_get_buffer($pdf);

pdf_delete($pdf);
?>

See also: pdf_arc(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fillstroke().

pdf_attach_file

(PHP 4 >= 4.0.5, PECL)

pdf_attach_file -- Adds a file attachment for current page

Description

bool pdf_attach_file ( resource pdfdoc, float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon )

Add a file attachment annotation. icon is one of graph, paperclip, pushpin, or tag. 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.

pdf_begin_page

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_begin_page -- Starts new page

Description

bool pdf_begin_page ( resource pdfdoc, float width, float height )

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

namesize
A02380✗3368
A11684✗2380
A21190✗1684
A3842✗1190
A4595✗842
A5421✗595
A6297✗421
B5501✗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().

pdf_begin_pattern

(PHP 4 >= 4.0.5, PECL)

pdf_begin_pattern -- Starts new pattern

Description

int pdf_begin_pattern ( resource pdfdoc, float width, float height, float xstep, float ystep, int painttype )

Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.

See also pdf_end_pattern().

pdf_begin_template

(PHP 4 >= 4.0.5, PECL)

pdf_begin_template -- Starts new template

Description

int pdf_begin_template ( resource pdfdoc, float width, float height )

Start a new template definition.

pdf_circle

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_circle -- Draws a circle

Description

bool pdf_circle ( resource pdfdoc, float x, float y, float r )

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

<?php
// prepare document
$pdf = pdf_new();
pdf_open_file($pdf, "");
pdf_begin_page($pdf, 595, 842);

// an outlined circle
pdf_circle($pdf, 200, 700, 100);
pdf_stroke($pdf);

// a filled circle
pdf_circle($pdf, 200, 700, 50);
pdf_fill($pdf);

// an outlined and filled circle
pdf_setcolor($pdf, "fill", "gray", 0.3);
pdf_circle($pdf, 400, 700, 50);
pdf_fill_stroke($pdf);

// finish document
pdf_end_page($pdf);
pdf_close($pdf);

header("Content-type: application/pdf");
echo pdf_get_buffer($pdf);

pdf_delete($pdf);
?>

See also: pdf_arc(), pdf_arcn(), pdf_curveto(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().

pdf_clip

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_clip -- Clips to current path

Description

bool pdf_clip ( resource pdfdoc )

Use the current path as clipping path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_close_image

(PHP 3 >= 3.0.7, PHP 4, PECL)

pdf_close_image -- Closes an image

Description

void pdf_close_image ( resource pdfdoc, int image )

Close an image retrieved with the pdf_open_image() function.

pdf_close_pdi_page

(PHP 4 >= 4.0.5, PECL)

pdf_close_pdi_page --  Close the page handle

Description

bool pdf_close_pdi_page ( resource pdfdoc, int pagehandle )

Close the page handle, and free all page-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_close_pdi

(PHP 4 >= 4.0.5, PECL)

pdf_close_pdi --  Close the input PDF document

Description

bool pdf_close_pdi ( resource pdfdoc, int dochandle )

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().

pdf_close

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_close -- Closes a pdf resource

Description

bool pdf_close ( resource pdfdoc )

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().

pdf_closepath_fill_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_closepath_fill_stroke -- Closes, fills and strokes current path

Description

bool pdf_closepath_fill_stroke ( resource pdfdoc )

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().

pdf_closepath_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_closepath_stroke -- Closes path and draws line along path

Description

bool pdf_closepath_stroke ( resource pdfdoc )

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().

pdf_closepath

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_closepath -- Closes path

Description

bool pdf_closepath ( resource pdfdoc )

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().

pdf_concat

(PHP 4 >= 4.0.5, PECL)

pdf_concat -- Concatenate a matrix to the CTM

Description

bool pdf_concat ( resource pdfdoc, float a, float b, float c, float d, float e, float f )

Concatenate a matrix to the CTM. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_continue_text

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_continue_text -- Outputs text in next line

Description

bool pdf_continue_text ( resource pdfdoc, string text )

Print text at the next line. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_curveto

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_curveto -- Draws a curve

Description

bool pdf_curveto ( resource pdfdoc, float x1, float y1, float x2, float y2, float x3, float y3 )

Draw a Bezier curve from the current point, using 3 more control points. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_delete

(PHP 4 >= 4.0.5, PECL)

pdf_delete -- Deletes a PDF object

Description

bool pdf_delete ( resource pdfdoc )

Delete the PDF resource, and free all internal resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also pdf_new().

pdf_end_page

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_end_page -- Ends a page

Description

bool pdf_end_page ( resource pdfdoc )

Finish the page. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also pdf_begin_page().

pdf_end_pattern

(PHP 4 >= 4.0.5, PECL)

pdf_end_pattern -- Finish pattern

Description

bool pdf_end_pattern ( resource pdfdoc )

Finish the pattern definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also pdf_begin_pattern().

pdf_end_template

(PHP 4 >= 4.0.5, PECL)

pdf_end_template -- Finish template

Description

bool pdf_end_template ( resource pdfdoc )

Finish the template definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_endpath

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_endpath -- Deprecated: Ends current path

Description

This function is deprecated, use one of the pdf_stroke(), pdf_clip() or pdf_closepath_fill_stroke() functions instead.

pdf_fill_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_fill_stroke -- Fills and strokes current path

Description

bool pdf_fill_stroke ( resource pdfdoc )

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().

pdf_fill

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_fill -- Fills current path

Description

bool pdf_fill ( resource pdfdoc )

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().

pdf_findfont

(PHP 4 >= 4.0.5, PECL)

pdf_findfont -- Prepare font for later use with pdf_setfont()

Description

int pdf_findfont ( resource pdfdoc, string fontname, string encoding, int embed )

Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, 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.

Esempio 1. pdf_findfont() example

<?php

$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
if ($font) {
    pdf_setfont($pdf, $font, 10);
}

?>

pdf_get_buffer

(PHP 4 >= 4.0.5, PECL)

pdf_get_buffer -- Fetch the buffer containing the generated PDF data

Description

string pdf_get_buffer ( resource pdfdoc )

Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.

pdf_get_font

(PHP 4, PECL)

pdf_get_font -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_fontname

(PHP 4, PECL)

pdf_get_fontname -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_parameter() instead.

pdf_get_fontsize

(PHP 4, PECL)

pdf_get_fontsize -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_image_height

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_get_image_height -- Deprecated: returns height of an image

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_image_width

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_get_image_width -- Deprecated: Returns width of an image

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_majorversion

(PHP 4 >= 4.2.0, PECL)

pdf_get_majorversion --  Returns the major version number of the PDFlib

Description

int pdf_get_majorversion ( void )

Returns the major version number of the PDFlib.

See also pdf_get_minorversion().

pdf_get_minorversion

(PHP 4 >= 4.2.0, PECL)

pdf_get_minorversion --  Returns the minor version number of the PDFlib

Description

int pdf_get_minorversion ( void )

Returns the minor version number of the PDFlib.

See also pdf_get_majorversion().

pdf_get_parameter

(PHP 4 >= 4.0.1, PECL)

pdf_get_parameter -- Gets certain parameters

Description

string pdf_get_parameter ( resource pdfdoc, string key, float modifier )

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.

pdf_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL)

pdf_get_pdi_parameter -- Get some PDI string parameters

Description

string pdf_get_pdi_parameter ( resource pdfdoc, string key, int document, int page, int index )

Get the contents of some PDI document parameter with string type.

pdf_get_pdi_value

(PHP 4 >= 4.0.5, PECL)

pdf_get_pdi_value -- Gets some PDI numerical parameters

Description

float pdf_get_pdi_value ( resource pdfdoc, string key, int doc, int page, int index )

Get the contents of some PDI document parameter with numerical type.

pdf_get_value

(PHP 4 >= 4.0.1, PECL)

pdf_get_value -- Gets certain numerical value

Description

float pdf_get_value ( resource pdfdoc, string key, float modifier )

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.

pdf_initgraphics

(PHP 4 >= 4.0.5, PECL)

pdf_initgraphics -- Resets graphic state

Description

bool pdf_initgraphics ( resource pdfdoc )

Reset all implicit color and graphics state parameters to their defaults. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_lineto

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_lineto -- Draws a line

Description

bool pdf_lineto ( resource pdfdoc, float x, float y )

Draw a line from the current point to (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_makespotcolor

(PHP 4 >= 4.0.5, PECL)

pdf_makespotcolor -- Makes a spotcolor

Description

int pdf_makespotcolor ( resource pdfdoc, string spotname )

Make a named spot color from the current color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also pdf_setcolor().

pdf_moveto

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_moveto -- Sets current point

Description

bool pdf_moveto ( resource pdfdoc, float x, float y )

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.

pdf_new

(PHP 4 >= 4.0.5, PECL)

pdf_new -- Creates a new pdf resource

Description

resource pdf_new ( )

Create a new PDF resource, using default error handling and memory management.

See also pdf_close().

pdf_open_ccitt

(PHP 4 >= 4.0.5, PECL)

pdf_open_ccitt -- Opens a new image file with raw CCITT data

Description

int pdf_open_ccitt ( resource pdfdoc, string filename, int width, int height, int BitReverse, int k, int Blackls1 )

Open a raw CCITT image.

pdf_open_file

(PHP 4 >= 4.0.5, PECL)

pdf_open_file -- Opens a new pdf object

Description

bool pdf_open_file ( resource pdfdoc, string filename )

Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function. 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

<?php

$pdf = pdf_new();

pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document created in memory!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);

$data = pdf_get_buffer($pdf);

header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));

echo $data;

?>

pdf_open_gif

(PHP 3 >= 3.0.7, PHP 4, PECL)

pdf_open_gif -- Deprecated: Opens a GIF image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_image_file

(PHP 3 CVS only, PHP 4, PECL)

pdf_open_image_file -- Reads an image from a file

Description

int pdf_open_image_file ( resource pdfdoc, string imagetype, string filename, string stringparam, int intparam )

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.

pdf_open_image

(PHP 4 >= 4.0.5, PECL)

pdf_open_image -- Versatile function for images

Description

int pdf_open_image ( resource pdfdoc, string imagetype, string source, string data, int length, int width, int height, int components, int bpc, string params )

Use image data from a variety of data sources. Supported types are jpeg, ccitt, raw. Supported sources are memory, fileref, url. len is only used when type is raw, params is only used when type is ccitt.

pdf_open_jpeg

(PHP 3 >= 3.0.7, PHP 4, PECL)

pdf_open_jpeg -- Deprecated: Opens a JPEG image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_memory_image

(PHP 3 >= 3.0.10, PHP 4, PECL)

pdf_open_memory_image -- Opens an image created with PHP's image functions

Description

int pdf_open_memory_image ( resource pdfdoc, resource image )

The 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.

Esempio 1. Including a memory image

<?php
$im = imagecreate(100, 100);
$col = imagecolorallocate($im, 80, 45, 190);
imagefill($im, 10, 10, $col);
$pim = pdf_open_memory_image($pdf, $im);
imagedestroy($im);
pdf_place_image($pdf, $pim, 100, 100, 1);
pdf_close_image($pdf, $pim);
?>

See also pdf_close_image() and pdf_place_image().

pdf_open_pdi_page

(PHP 4 >= 4.0.5, PECL)

pdf_open_pdi_page --  Prepare a page

Description

int pdf_open_pdi_page ( resource pdfdoc, int dochandle, int pagenumber, string pagelabel )

Prepare a page for later use with pdf_place_image()

pdf_open_pdi

(PHP 4 >= 4.0.5, PECL)

pdf_open_pdi --  Opens a PDF file

Description

int pdf_open_pdi ( resource pdfdoc, string filename, string stringparam, int intparam )

Opens an existing PDF document and prepares it for later use.

See also pdf_close_pdi().

pdf_open_png

(PHP 4, PECL)

pdf_open_png --  Deprecated: Opens a PNG image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_tiff

(PHP 4, PECL)

pdf_open_tiff -- Deprecated: Opens a TIFF image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_open -- Deprecated: Open a new pdf object

Description

This function is deprecated, use pdf_new() plus pdf_open_file() instead.

pdf_place_image

(PHP 3 >= 3.0.7, PHP 4, PECL)

pdf_place_image -- Places an image on the page

Description

bool pdf_place_image ( resource pdfdoc, int image, float x, float y, float scale )

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.

pdf_place_pdi_page

(PHP 4 >= 4.0.6, PECL)

pdf_place_pdi_page -- Places an image on the page

Description

bool pdf_place_pdi_page ( resource pdfdoc, int page, float x, float y, float sx, float sy )

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.

pdf_rect

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_rect -- Draws a rectangle

Description

bool pdf_rect ( resource pdfdoc, float x, float y, float width, float height )

Draw a (width * height) rectangle at lower left (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_restore

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_restore -- Restores formerly saved environment

Description

bool pdf_restore ( resource pdfdoc )

Restore the most recently saved graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_rotate

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_rotate -- Sets rotation

Description

bool pdf_rotate ( resource pdfdoc, float phi )

Rotate the coordinate system by phi degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_save

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_save -- Saves the current environment

Description

bool pdf_save ( resource pdfdoc )

Save the current graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_scale

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_scale -- Sets scaling

Description

bool pdf_scale ( resource pdfdoc, float x_scale, float y_scale )

Scale the coordinate system. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_set_border_color

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_set_border_color -- Sets color of border around links and annotations

Description

bool pdf_set_border_color ( resource pdfdoc, float red, float green, float blue )

Set the border color for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_set_border_dash

(PHP 4 >= 4.0.1, PECL)

pdf_set_border_dash -- Sets dash style of border around links and annotations

Description

bool pdf_set_border_dash ( resource pdfdoc, float black, float white )

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().

pdf_set_border_style

(PHP 3 >= 3.0.12, PHP 4, PECL)

pdf_set_border_style -- Sets style of border around links and annotations

Description

bool pdf_set_border_style ( resource pdfdoc, string style, float width )

Sets the border style for all kinds of annotations. style is solid or dashed. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_set_char_spacing

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_char_spacing -- Deprecated: Sets character spacing

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_duration

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_duration -- Deprecated: Sets duration between pages

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_font

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_font -- Deprecated: Selects a font face and size

Description

This function is deprecated, use pdf_findfont() plus pdf_setfont() instead.

pdf_set_horiz_scaling

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_horiz_scaling -- Sets horizontal scaling of text [deprecated]

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_info_author

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_info_author --  Deprecated: Fills the author field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_creator

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_info_creator --  Deprecated: Fills the creator field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_keywords

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_info_keywords --  Deprecated: Fills the keywords field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_subject

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_info_subject --  Deprecated: Fills the subject field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info_title

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_info_title --  Deprecated: Fills the title field of the document

Description

This function is deprecated, use pdf_set_info() instead.

pdf_set_info

(PHP 4 >= 4.0.1, PECL)

pdf_set_info -- Fills a field of the document information

Description

bool pdf_set_info ( resource pdfdoc, string key, string value )

Fill 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.

pdf_set_leading

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_leading -- Deprecated: Sets distance between text lines

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_parameter

(PHP 4, PECL)

pdf_set_parameter -- Sets certain parameters

Description

bool pdf_set_parameter ( resource pdfdoc, string key, string value )

Sets some PDFlib parameters with string type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also pdf_set_value().

pdf_set_text_matrix

(PHP 3 >= 3.0.6)

pdf_set_text_matrix -- Deprecated: Sets the text matrix

Description

This function is deprecated, use pdf_set_parameter() instead.

pdf_set_text_pos

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_text_pos -- Sets text position

Description

bool pdf_set_text_pos ( resource pdfdoc, float x, float y )

Set the text output position specified by x and y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_set_text_rendering

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_text_rendering -- Deprecated: Determines how text is rendered

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_text_rise

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_text_rise -- Deprecated: Sets the text rise

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_value

(PHP 4 >= 4.0.1, PECL)

pdf_set_value -- Sets certain numerical value

Description

bool pdf_set_value ( resource pdfdoc, string key, float value )

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().

pdf_set_word_spacing

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_set_word_spacing -- Deprecated: Sets spacing between words

Description

This function is deprecated, use pdf_set_value() instead.

pdf_setcolor

(PHP 4 >= 4.0.5, PECL)

pdf_setcolor -- Sets fill and stroke color

Description

bool pdf_setcolor ( resource pdfdoc, string type, string colorspace, float c1, float c2, float c3, float c4 )

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.

<?php
// Set fill and stroke colors to white.
pdf_setcolor($pdf, "both", "rgb", 1, 1, 1);
?>

For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.

<?php
// Set fill and stroke colors to black.
pdf_setcolor($pdf, "both", "cmyk", 0, 0, 0, 1);
?>

For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.

For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().

pdf_setdash

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setdash -- Sets dash pattern

Description

bool pdf_setdash ( resource pdfdoc, float b, float w )

Set the current dash pattern to b black and w white units. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_setflat

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setflat -- Sets flatness

Description

bool pdf_setflat ( resource pdfdoc, float flatness )

Sets the flatness to a value between 0 and 100 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_setfont

(PHP 4 >= 4.0.5, PECL)

pdf_setfont -- Set the current font

Description

bool pdf_setfont ( resource pdfdoc, int font, float size )

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().

pdf_setgray_fill

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setgray_fill -- Sets filling color to gray value

Description

bool pdf_setgray_fill ( resource pdfdoc, float gray )

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.

pdf_setgray_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setgray_stroke -- Sets drawing color to gray value

Description

bool pdf_setgray_stroke ( resource pdfdoc, float gray )

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.

pdf_setgray

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setgray -- Sets drawing and filling color to gray value

Description

bool pdf_setgray ( resource pdfdoc, float gray )

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.

pdf_setlinecap

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setlinecap -- Sets linecap parameter

Description

bool pdf_setlinecap ( resource pdfdoc, int linecap )

Set the linecap parameter to a value between 0 and 2 inclusive.

pdf_setlinejoin

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setlinejoin -- Sets linejoin parameter

Description

bool pdf_setlinejoin ( resource pdfdoc, int value )

Sets the line join parameter to a value between 0 and 2 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_setlinewidth

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setlinewidth -- Sets line width

Description

bool pdf_setlinewidth ( resource pdfdoc, float width )

Sets the current linewidth to width. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_setmatrix

(PHP 4 >= 4.0.5, PECL)

pdf_setmatrix -- Sets current transformation matrix

Description

bool pdf_setmatrix ( resource pdfdoc, float a, float b, float c, float d, float e, float f )

Explicitly set the current transformation matrix. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_setmiterlimit

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setmiterlimit -- Sets miter limit

Description

bool pdf_setmiterlimit ( resource pdfdoc, float miter )

Set the miter limit to a value greater than or equal to 1. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_setpolydash

(PHP 4 >= 4.0.5, PECL)

pdf_setpolydash -- Deprecated: Sets complicated dash pattern

Description

This function is deprecated, use pdf_setdash() instead.

pdf_setrgbcolor_fill

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

bool pdf_setrgbcolor_fill ( resource pdfdoc, float red_value, float green_value, float blue_value )

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.

pdf_setrgbcolor_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

bool pdf_setrgbcolor_stroke ( resource pdfdoc, float red_value, float green_value, float blue_value )

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.

pdf_setrgbcolor

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

bool pdf_setrgbcolor ( resource pdfdoc, float red_value, float green_value, float blue_value )

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.

pdf_show_boxed

(PHP 4, PECL)

pdf_show_boxed -- Output text in a box

Description

int pdf_show_boxed ( resource pdfdoc, string text, float left, float top, float width, float height, string mode, string feature )

Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of left, right, center, justify or fulljustify. If width and height are 0, only a single line is placed at the point (left, top) in the requested mode. 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.

pdf_show_xy

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_show_xy -- Output text at given position

Description

bool pdf_show_xy ( resource pdfdoc, string text, float x, float y )

Print text in the current font at ( x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_show

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_show -- Output text at current position

Description

bool pdf_show ( resource pdfdoc, string text )

Print text in the current font and size at the current position. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_skew

(PHP 4, PECL)

pdf_skew -- Skews the coordinate system

Description

bool pdf_skew ( resource pdfdoc, float alpha, float beta )

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.

pdf_stringwidth

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_stringwidth -- Returns width of text using current font

Description

float pdf_stringwidth ( resource pdfdoc, string text, int font, float size )

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().

pdf_stroke

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_stroke -- Draws line along path

Description

bool pdf_stroke ( resource pdfdoc )

Stroke the path with the current color and line width, and clear it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

pdf_translate

(PHP 3 >= 3.0.6, PHP 4, PECL)

pdf_translate -- Sets origin of coordinate system

Description

bool pdf_translate ( resource pdfdoc, float tx, float ty )

Translate the origin of the coordinate system.

CX. PDO Functions

Introduzione

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.


Installazione

PHP 5.1 and up on Unix systems

  1. 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

  2. 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

  3. 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

  1. 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.

  2. Run the following command to download, build, and install the latest stable version of PDO:
    pear install pdo

  3. 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

  4. 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

  1. 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

  2. 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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. PDO Configuration Options

NameDefaultChangeableChangelog
pdo.dsn.* php.ini only 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

pdo.dsn.* string

Defines DSN alias. See PDO::__construct for thorough explanation.


PDO Drivers

The following drivers currently implement the PDO interface:

Driver nameSupported databases
PDO_DBLIBFreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRDFirebird/Interbase 6
PDO_MYSQLMySQL 3.x/4.x
PDO_OCIOracle Call Interface
PDO_ODBCODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQLPostgreSQL
PDO_SQLITESQLite 3 and SQLite 2


Connections and Connection management

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).

Esempio 1. Connecting to mysql

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

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().

Esempio 2. Handling connection errors

<?php
try {
   $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   foreach ($dbh->query('SELECT * from FOO') as $row) {
      print_r($row);
   }
   $dbh = null;
} catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>

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.

Esempio 3. Closing a connection

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here


// and now we're done; close it
$dbh = null;
?>

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.

Esempio 4. Persistent connections

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
  PDO::ATTR_PERSISTENT => true
));
?>

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.


Transactions and auto-commit

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.

<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2', 
      array(PDO::ATTR_PERSISTENT => true));
  echo "Connected\n";
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $dbh->beginTransaction();
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate) 
      values (23, 50000, NOW())");
  $dbh->commit();
  
} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

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.


Prepared statements and stored procedures

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.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Esempio 7. Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

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.

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
?>

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.

Esempio 9. Calling a stored procedure with an output parameter

<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000); 

// call the stored procedure
$stmt->execute();

print "procedure returned $return_value\n";
?>

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

<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); 

// call the stored procedure
$stmt->execute();

print "procedure returned $value\n";
?>


Errors and error handling

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.


Large Objects (LOBs)

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.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?>

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.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$stmt->execute();
?>


Classi predefinite

PDO

Represents a connection between PHP and a database server.


Costruttori

  • PDO - constructs a new PDO object


Metodi

  • 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


PDOStatement

Represents a prepared statement and, after the statement is executed, an associated result set.


Metodi

  • 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


PDOException

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

<?php
class PDOException extends Exception
{
    public $errorInfo = null;    // corresponds to PDO::errorInfo()
                                 // or PDOStatement::errorInfo()
    protected $message;          // textual error message
                                 // use Exception::getMessage() to access it
    protected $code;             // SQLSTATE error code
                                 // use Exception::getCode() to access it
}
?>

Costanti predefinite

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.

PDO::PARAM_BOOL (integer)

Represents a boolean data type.

PDO::PARAM_NULL (integer)

Represents the SQL NULL data type.

PDO::PARAM_INT (integer)

Represents the SQL INTEGER data type.

PDO::PARAM_STR (integer)

Represents the SQL CHAR, VARCHAR, or other string data type.

PDO::PARAM_LOB (integer)

Represents the SQL large object data type.

PDO::PARAM_STMT (integer)

Represents a recordset type. Not currently supported by any drivers.

PDO::PARAM_INPUT_OUTPUT (integer)

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.

PDO::FETCH_LAZY (integer)

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.

PDO::FETCH_ASSOC (integer)

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.

PDO::FETCH_NAMED (integer)

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.

PDO::FETCH_NUM (integer)

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.

PDO::FETCH_BOTH (integer)

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.

PDO::FETCH_OBJ (integer)

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.

PDO::FETCH_BOUND (integer)

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.

PDO::FETCH_COLUMN (integer)

Specifies that the fetch method shall return only a single requested column from the next row in the result set.

PDO::FETCH_CLASS (integer)

Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

PDO::FETCH_INTO (integer)

Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.

PDO::FETCH_FUNC (integer)

PDO::FETCH_GROUP (integer)

PDO::FETCH_UNIQUE (integer)

PDO::FETCH_CLASSTYPE (integer)

PDO::ATTR_AUTOCOMMIT (integer)

If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.

PDO::ATTR_PREFETCH (integer)

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.

PDO::ATTR_TIMEOUT (integer)

Sets the timeout value in seconds for communications with the database.

PDO::ATTR_ERRMODE (integer)

See the Errors and error handling section for more information about this attribute.

PDO::ATTR_SERVER_VERSION (integer)

This is a read only attribute; it will return information about the version of the database server to which PDO is connected.

PDO::ATTR_CLIENT_VERSION (integer)

This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.

PDO::ATTR_SERVER_INFO (integer)

This is a read only attribute; it will return some meta information about the database server to which PDO is connected.

PDO::ATTR_CONNECTION_STATUS (integer)

PDO::ATTR_CASE (integer)

Force column names to a specific case specified by the PDO::CASE_* constants.

PDO::ATTR_CURSOR_NAME (integer)

Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.

PDO::ATTR_CURSOR (integer)

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.

PDO::ATTR_DRIVER_NAME (string)

Returns the name of the driver.

Esempio 14. using PDO::ATTR_DRIVER_NAME

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
}
?>

PDO::ATTR_ORACLE_NULLS (integer)

Convert empty strings to SQL NULL values on data fetches.

PDO::ATTR_PERSISTENT (integer)

Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.

PDO::ATTR_FETCH_CATALOG_NAMES (integer)

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.

PDO::ATTR_FETCH_TABLE_NAMES (integer)

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.

PDO::ERRMODE_SILENT (integer)

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.

PDO::ERRMODE_WARNING (integer)

Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.

PDO::ERRMODE_EXCEPTION (integer)

Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.

PDO::CASE_NATURAL (integer)

Leave column names as returned by the database driver.

PDO::CASE_LOWER (integer)

Force column names to lower case.

PDO::CASE_UPPER (integer)

Force column names to upper case.

PDO::FETCH_ORI_NEXT (integer)

Fetch the next row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_PRIOR (integer)

Fetch the previous row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_FIRST (integer)

Fetch the first row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_LAST (integer)

Fetch the last row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_ABS (integer)

Fetch the requested row by row number from the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_REL (integer)

Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.

PDO::CURSOR_FWDONLY (integer)

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.

PDO::CURSOR_SCROLL (integer)

Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.

PDO::ERR_NONE (string)

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.

Sommario
PDO::beginTransaction --  Initiates a transaction
PDO::commit --  Commits a transaction
PDO::__construct --  Creates a PDO instance representing a connection to a database
PDO::errorCode --  Fetch the SQLSTATE associated with the last operation on the database handle
PDO::errorInfo --  Fetch extended error information associated with the last operation on the database handle
PDO::exec --  Execute an SQL statement and return the number of affected rows
PDO::getAttribute --  Retrieve a database connection attribute
PDO::getAvailableDrivers --  Return an array of available PDO drivers
PDO::lastInsertId --  Returns the ID of the last inserted row or sequence value
PDO::prepare --  Prepares a statement for execution and returns a statement object
PDO::query --  Executes an SQL statement, returning a result set as a PDOStatement object
PDO::quote --  Quotes a string for use in a query.
PDO::rollBack --  Rolls back a transaction
PDO::setAttribute --  Set an attribute
PDOStatement::bindColumn --  Bind a column to a PHP variable
PDOStatement::bindParam --  Binds a parameter to the specified variable name
PDOStatement::bindValue --  Binds a value to a parameter
PDOStatement::closeCursor --  Closes the cursor, enabling the statement to be executed again.
PDOStatement::columnCount --  Returns the number of columns in the result set
PDOStatement::errorCode --  Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement::errorInfo --  Fetch extended error information associated with the last operation on the statement handle
PDOStatement::execute --  Executes a prepared statement
PDOStatement::fetch --  Fetches the next row from a result set
PDOStatement::fetchAll --  Returns an array containing all of the result set rows
PDOStatement::fetchColumn --  Returns a single column from the next row of a result set
PDOStatement::getAttribute --  Retrieve a statement attribute
PDOStatement::getColumnMeta --  Returns metadata for a column in a result set
PDOStatement::nextRowset --  Advances to the next rowset in a multi-rowset statement handle
PDOStatement::rowCount --  Returns the number of rows affected by the last SQL statement
PDOStatement::setAttribute --  Set a statement attribute
PDOStatement::setFetchMode --  Set the default fetch mode for this statement

PDO::beginTransaction

(no version information, might be only in CVS)

PDO::beginTransaction --  Initiates a transaction

Descrizione

bool PDO::beginTransaction ( void )

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.

Esempi

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.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

Vedere anche:

PDO::commit()
PDO::rollBack()

PDO::commit

(no version information, might be only in CVS)

PDO::commit --  Commits a transaction

Descrizione

bool PDO::commit ( void )

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.

Esempi

Esempio 1. Commit a transaction

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");

/* Commit the changes */
$dbh->commit();

/* Database connection is now back in autocommit mode */
?>

Vedere anche:

PDO::beginTransaction()
PDO::rollBack()

PDO::__construct

(no version information, might be only in CVS)

PDO::__construct --  Creates a PDO instance representing a connection to a database

Descrizione

PDO PDO::__construct ( string dsn [, string username [, string password [, array driver_options]]] )

Creates a PDO instance to represent a connection to the requested database.

Elenco dei parametri

dsn

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:

Driver invocation

dsn contains the full DSN.

URI invocation

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

Aliasing

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

username

The user name for the DSN string. This parameter is optional for some PDO drivers.

password

The password for the DSN string. This parameter is optional for some PDO drivers.

driver_options

A key=>value array of driver-specific connection options.

Valori restituiti

Returns a PDO object on success.

Eccezioni

PDO::construct() throws a PDOException if the attempt to connect to the requested database fails.

Esempi

Esempio 1. Create a PDO instance via driver invocation

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

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:

odbc:DSN=SAMPLE;UID=john;PWD=mypass

The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

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:
[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"

<?php
/* Connect to an ODBC database using an alias */
$dsn = 'mydb';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
}catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

PDO::errorCode

(no version information, might be only in CVS)

PDO::errorCode --  Fetch the SQLSTATE associated with the last operation on the database handle

Descrizione

int PDO::errorCode ( void )

Valori restituiti

Returns 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.

Esempi

Esempio 1. Retrieving a SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ";
print $dbh->errorCode();
?>

Il precedente esempio visualizzerà:

PDO::errorCode(): 42S02

Vedere anche:

PDO::errorInfo()
PDOStatement::errorCode()
PDOStatement::errorInfo()

PDO::errorInfo

(no version information, might be only in CVS)

PDO::errorInfo --  Fetch extended error information associated with the last operation on the database handle

Descrizione

array PDO::errorInfo ( void )

Valori restituiti

PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:

ElementInformation
0SQLSTATE error code (a five-character alphanumeric identifier defined in the ANSI SQL standard).
1Driver-specific error code.
2Driver-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.

Esempi

Esempio 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();
echo "\nPDO::errorInfo():\n";
print_r($err->errorInfo());
?>

Il precedente esempio visualizzerà:

PDO::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

Vedere anche:

PDO::errorCode()
PDOStatement::errorCode()
PDOStatement::errorInfo()

PDO::exec

(no version information, might be only in CVS)

PDO::exec --  Execute an SQL statement and return the number of affected rows

Descrizione

int PDO::exec ( string statement )

PDO::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().

Elenco dei parametri

statement

The SQL statement to prepare and execute.

Valori restituiti

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());
?>

Esempi

Esempio 1. Issuing a DELETE statement

Count the number of rows deleted by a DELETE statement with no WHERE clause.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

/* Delete all rows from the FRUIT table */
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

/* Return number of rows that were deleted */
print("Deleted $count rows.\n");
?>

Il precedente esempio visualizzerà:

Deleted 1 rows.

Vedere anche:

PDO::prepare()
PDO::query()
PDOStatement::execute()

PDO::getAttribute

(no version information, might be only in CVS)

PDO::getAttribute --  Retrieve a database connection attribute

Descrizione

mixed PDO::getAttribute ( int attribute )

This 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.

Elenco dei parametri

attribute

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

Valori restituiti

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.

Esempi

Esempio 1. Retrieving database connection attributes

<?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

print "\nPDO::ATTR_AUTOCOMMIT: ";
print $conn->getAttribute(PDO::ATTR_AUTOCOMMIT);

print "\nPDO::ATTR_ERRMODE: ";
print $conn->getAttribute(PDO::ATTR_ERRMODE);

print "\nPDO::ATTR_CASE: ";
print $conn->getAttribute(PDO::ATTR_CASE);

print "\nPDO::ATTR_CLIENT_VERSION: ";
print $conn->getAttribute(PDO::ATTR_CLIENT_VERSION);

print "\nPDO::ATTR_CONNECTION_STATUS: ";
print $conn->getAttribute(PDO::ATTR_CONNECTION_STATUS);

print "\nPDO::ATTR_ORACLE_NULLS: ";
print $conn->getAttribute(PDO::ATTR_ORACLE_NULLS);

print "\nPDO::ATTR_PERSISTENT: ";
print $conn->getAttribute(PDO::ATTR_PERSISTENT);

print "\nPDO::ATTR_PREFETCH: ";
print $conn->getAttribute(PDO::ATTR_PREFETCH);

print "\nPDO::ATTR_SERVER_INFO: ";
print $conn->getAttribute(PDO::ATTR_SERVER_INFO);

print "\nPDO::ATTR_SERVER_VERSION: ";
print $conn->getAttribute(PDO::ATTR_SERVER_VERSION);

print "\nPDO::ATTR_TIMEOUT: ";
print $conn->getAttribute(PDO::ATTR_TIMEOUT);
?>

Vedere anche:

PDO::setAttribute()
PDOStatement::getAttribute()
PDOStatement::setAttribute()

PDO::getAvailableDrivers

(no version information, might be only in CVS)

PDO::getAvailableDrivers --  Return an array of available PDO drivers

Descrizione

array PDO::getAvailableDrivers ( void )

This function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct(). This is a static method.

Valori restituiti

PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

Esempi

Esempio 1. A PDO::getAvailableDrivers() example

<?php
print_r(PDO::getAvailableDrivers());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => mysql
    [1] => sqlite
)

PDO::lastInsertId

(no version information, might be only in CVS)

PDO::lastInsertId --  Returns the ID of the last inserted row or sequence value

Description

string PDO::lastInsertId ( [string name] )

Returns 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.

Elenco dei parametri

name

Name of the sequence object from which the ID should be returned.

Valori restituiti

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.

PDO::prepare

(no version information, might be only in CVS)

PDO::prepare --  Prepares a statement for execution and returns a statement object

Descrizione

PDOStatement PDO::prepare ( string statement [, array driver_options] )

Prepares 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.

Elenco dei parametri

statement

This must be a valid SQL statement for the target database server.

driver_options

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.

Valori restituiti

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object.

Esempi

Esempio 1. Prepare an SQL statement with named parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Esempio 2. Prepare an SQL statement with question mark parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>

Vedere anche:

PDO::exec()
PDO::query()
PDOStatement::execute()

PDO::query

(no version information, might be only in CVS)

PDO::query --  Executes an SQL statement, returning a result set as a PDOStatement object

Descrizione

PDOStatement PDO::query ( string statement )

PDO::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().

Elenco dei parametri

statement

The SQL statement to prepare and execute.

Valori restituiti

PDO::query() returns a PDOStatement object.

Esempi

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.

<?php
function getFruit($conn) {
    $sql = 'SELECT name, colour, calories FROM fruit ORDER BY name';
    foreach ($conn->query($sql) as $row) {
        print $row['NAME'] . "\t";
        print $row['COLOUR'] . "\t";
        print $row['CALORIES'] . "\n";
    }
}
?>

Il precedente esempio visualizzerà:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

Vedere anche:

PDO::exec()
PDO::prepare()
PDOStatement::execute()

PDO::quote

(no version information, might be only in CVS)

PDO::quote --  Quotes a string for use in a query.

Descrizione

string PDO::quote ( string string [, int parameter_type] )

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.

Elenco dei parametri

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles. The default value is PDO_PARAM_STR.

Valori restituiti

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.

Esempi

Esempio 1. Quoting a normal string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

Il precedente esempio visualizzerà:

Unquoted string: Nice
Quoted string: 'Nice'

Esempio 2. Quoting a dangerous string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>

Il precedente esempio visualizzerà:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Esempio 3. Quoting a complex string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Complex string */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

Il precedente esempio visualizzerà:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

Vedere anche:

PDO::prepare()
PDOStatement::execute()

PDO::rollBack

(no version information, might be only in CVS)

PDO::rollBack --  Rolls back a transaction

Descrizione

bool PDO::rollBack ( void )

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.

Esempi

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.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

Vedere anche:

PDO::beginTransaction()
PDO::commit()

PDO::setAttribute

(no version information, might be only in CVS)

PDO::setAttribute --  Set an attribute

Description

bool PDO::setAttribute ( int attribute, mixed value )

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.

PDOStatement::bindColumn

(no version information, might be only in CVS)

PDOStatement::bindColumn --  Bind a column to a PHP variable

Descrizione

bool PDOStatement::bindColumn ( mixed column, mixed &param [, int type] )

PDOStatement::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().

Elenco dei parametri

column

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.

param

Name of the PHP variable to which the column will be bound.

type

Data type of the parameter, specified by the PDO::PARAM_* constants.

Esempi

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.

<?php
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /* Bind by column number */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);
    
    /* Bind by column name */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);
?>

Il precedente esempio visualizzerà:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

Vedere anche:

PDOStatement::execute()
PDOStatement::fetch()
PDOStatement::fetchAll()
PDOStatement::fetchColumn()

PDOStatement::bindParam

(no version information, might be only in CVS)

PDOStatement::bindParam --  Binds a parameter to the specified variable name

Descrizione

bool PDOStatement::bindParam ( mixed parameter, mixed &variable [, int data_type [, int length [, mixed driver_options]]] )

Binds 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.

Elenco dei parametri

parameter

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.

variable

Name of the PHP variable to bind to the SQL statement parameter.

data_type

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

Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.

driver_options

Esempi

Esempio 1. Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Esempio 2. Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Esempio 3. Call a stored procedure with an INOUT parameter

<?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>

Vedere anche:

PDO::prepare()
PDOStatement::execute()
PDOStatement::bindValue()

PDOStatement::bindValue

(no version information, might be only in CVS)

PDOStatement::bindValue --  Binds a value to a parameter

Descrizione

bool PDOStatement::bindValue ( mixed parameter, mixed value [, int data_type] )

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement.

Elenco dei parametri

parameter

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.

value

The value to bind to the parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants.

Esempi

Esempio 1. Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Esempio 2. Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

Vedere anche:

PDO::prepare()
PDOStatement::execute()
PDOStatement::bindParam()

PDOStatement::closeCursor

(no version information, might be only in CVS)

PDOStatement::closeCursor --  Closes the cursor, enabling the statement to be executed again.

Descrizione

bool PDOStatement::closeCursor ( void )

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);
?>

Esempi

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.

<?php
/* Create a PDOStatement object */
$stmt = $dbh->prepare('SELECT foo FROM bar');

/* Create a second PDOStatement object */
$stmt = $dbh->prepare('SELECT foobaz FROM foobar');

/* Execute the first statement */
$stmt->execute();

/* Fetch only the first row from the results */
$stmt->fetch();

/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();

/* Now we can execute the second statement */
$otherStmt->execute();
?>

Vedere anche:

PDOStatement::execute()

PDOStatement::columnCount

(no version information, might be only in CVS)

PDOStatement::columnCount --  Returns the number of columns in the result set

Descrizione

int PDOStatement::columnCount ( void )

Use 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().

Valori restituiti

Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

Esempi

Esempio 1. Counting columns

This example demonstrates how PDOStatement::columnCount() operates with and without a result set.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

/* Count the number of columns in the (non-existent) result set */
$colcount = $sth->columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");

$sth->execute();

/* Count the number of columns in the result set */
$colcount = $sth->columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");

?>

Il precedente esempio visualizzerà:

Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)

Vedere anche:

PDO::prepare()
PDOStatement::execute()
PDOStatement::rowCount()

PDOStatement::errorCode

(no version information, might be only in CVS)

PDOStatement::errorCode --  Fetch the SQLSTATE associated with the last operation on the statement handle

Descrizione

int PDOStatement::errorCode ( void )

Valori restituiti

Identical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.

Esempi

Esempio 1. Retrieving a SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();

echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>

Il precedente esempio visualizzerà:

PDOStatement::errorCode(): 42S02

Vedere anche:

PDO::errorCode()
PDO::errorInfo()
PDOStatement::errorInfo()

PDOStatement::errorInfo

(no version information, might be only in CVS)

PDOStatement::errorInfo --  Fetch extended error information associated with the last operation on the statement handle

Descrizione

array PDOStatement::errorInfo ( void )

Valori restituiti

PDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of the following fields:

ElementInformation
0SQLSTATE error code (a five-character alphanumeric identifier defined in the ANSI SQL standard).
1Driver-specific error code.
2Driver-specific error message.

Esempi

Esempio 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>

Il precedente esempio visualizzerà:

PDOStatement::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

Vedere anche:

PDO::errorCode()
PDO::errorInfo()
PDOStatement::errorCode()

PDOStatement::execute

(no version information, might be only in CVS)

PDOStatement::execute --  Executes a prepared statement

Descrizione

bool PDOStatement::execute ( [array input_parameters] )

Execute 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

Esempi

Esempio 1. Execute a prepared statement with bound variables

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Esempio 2. Execute a prepared statement with an array of insert values

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>

Esempio 3. Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Vedere anche:

PDO::prepare()
PDOStatement::bindParam()
PDOStatement::fetch()
PDOStatement::fetchAll()
PDOStatement::fetchColumn()

PDOStatement::fetch

(no version information, might be only in CVS)

PDOStatement::fetch --  Fetches the next row from a result set

Descrizione

mixed PDOStatement::fetch ( [int fetch_style [, int cursor_orientation [, int cursor_offset]]] )

Fetches a row from a result set associated with a PDOStatement object.

Elenco dei parametri

fetch_style

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

cursor_orientation

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.

offset

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.

Esempi

Esempio 1. Fetching rows using different fetch styles

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
print("\n");
?>

Il precedente esempio visualizzerà:

PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
    [NAME] => apple
    [COLOUR] => red
)

PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
    [NAME] => banana
    [0] => banana
    [COLOUR] => yellow
    [1] => yellow
)

PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties
PDORow Object
(
    [NAME] => orange
    [COLOUR] => orange
)

PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi

Esempio 2. Fetching rows with a scrollable cursor

<?php
function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL));
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
function readDataBackwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL));
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
    do {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    } while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}

print "Reading forwards:\n";
readDataForwards($conn);

print "Reading backwards:\n";
readDataBackwards($conn);
?>

Il precedente esempio visualizzerà:

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

Vedere anche:

PDO::query()
PDOStatement::fetchAll()
PDOStatement::fetchColumn()
PDOStatement::prepare()
PDOStatement::setFetchMode()

PDOStatement::fetchAll

(no version information, might be only in CVS)

PDOStatement::fetchAll --  Returns an array containing all of the result set rows

Descrizione

array PDOStatement::fetchAll ( [int fetch_style [, int column_index]] )

Elenco dei parametri

fetch_style

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.

column_index

Returns the indicated 0-indexed column when the value of fetch_style is PDO::FETCH_COLUMN. Defaults to 0.

Valori restituiti

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.

Esempi

Esempio 1. Fetch all remaining rows in a result set

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

Il precedente esempio visualizzerà:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)

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.

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>

Il precedente esempio visualizzerà:

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

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.

<?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute('apple', 'green');
$insert->execute('pear', 'yellow');

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

Il precedente esempio visualizzerà:

array(3) {
  ["apple"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(3) "red"
  }
  ["pear"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(6) "yellow"
  }
  ["watermelon"]=>
  array(1) {
    [0]=>
    string(5) "green"
  }
}

Vedere anche:

PDO::query()
PDOStatement::fetch()
PDOStatement::fetchColumn()
PDOStatement::prepare()
PDOStatement::setFetchMode()

PDOStatement::fetchColumn

(no version information, might be only in CVS)

PDOStatement::fetchColumn --  Returns a single column from the next row of a result set

Descrizione

string PDOStatement::fetchColumn ( [int column_number] )

Returns a single column from the next row of a result set.

Elenco dei parametri

column_number

Number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.

Valori restituiti

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.

Esempi

Esempio 1. Return first column of the next row

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch the first column from the next row in the result set */
print("Fetch the first column from the next row in the result set:\n");
$result = $sth->fetchColumn();
print("$result\n");

$result = $sth->fetchColumn();
print("$result\n");
?>

Il precedente esempio visualizzerà:

Fetch the first column from the next row in the result set:
lemon
orange

Vedere anche:

PDO::query()
PDOStatement::fetch()
PDOStatement::fetchAll()
PDOStatement::prepare()
PDOStatement::setFetchMode()

PDOStatement::getAttribute

(no version information, might be only in CVS)

PDOStatement::getAttribute --  Retrieve a statement attribute

Descrizione

mixed PDOStatement::getAttribute ( int attribute )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche:

PDO::getAttribute()
PDO::setAttribute()
PDOStatement::setAttribute()

PDOStatement::getColumnMeta

(no version information, might be only in CVS)

PDOStatement::getColumnMeta --  Returns metadata for a column in a result set

Descrizione

mixed PDOStatement::getColumnMeta ( int column )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().

Elenco dei parametri

column

The 0-indexed column in the result set.

Valori restituiti

Returns an associative array containing the following values representing the metadata for a single column:

Tabella 1. Column metadata

NameValue
native_typeThe PHP native type used to represent the column value.
driver:decl_typeThe 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().
flagsAny flags set for this column.
nameThe name of this column as returned by the database.
lenThe length of this column. Normally -1 for types other than floating point decimals.
precisionThe numeric precision of this column. Normally 0 for types other than floating point decimals.
pdo_typeThe 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.

Esempi

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.

<?php
$select = $DB->query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>

Il precedente esempio visualizzerà:

array(6) {
  ["native_type"]=>
  string(7) "integer"
  ["flags"]=>
  array(0) {
  }
  ["name"]=>
  string(8) "COUNT(*)"
  ["len"]=>
  int(-1)
  ["precision"]=>
  int(0)
  ["pdo_type"]=>
  int(2)
}

Vedere anche:

PDOStatement::columnCount()
PDOStatement::rowCount()

PDOStatement::nextRowset

(no version information, might be only in CVS)

PDOStatement::nextRowset --  Advances to the next rowset in a multi-rowset statement handle

Descrizione

bool PDOStatement::nextRowset ( void )

Some 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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

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.

<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$i = 1;
do {
    $rowset = $stmt->fetchAll(PDO::FETCH_NUM);
    if ($rowset) {
        printResultSet($rowset, $i);
    }
    $i++;
} while ($stmt->nextRowset());

function printResultSet(&$rowset, $i) {
    print "Result set $i:\n";
    foreach ($rowset as $row) {
        foreach ($row as $col) {
            print $col . "\t";
        }
        print "\n";
    }
    print "\n";
}
?>

Il precedente esempio visualizzerà:

Result set 1:
apple    red
banana   yellow

Result set 2:
orange   orange    150
banana   yellow    175

Result set 3:
lime     green
apple    red
banana   yellow

Vedere anche:

PDOStatement::columnCount()
PDOStatement::execute()
PDOStatement::getColumnMeta()
PDOStatement::query()

PDOStatement::rowCount

(no version information, might be only in CVS)

PDOStatement::rowCount --  Returns the number of rows affected by the last SQL statement

Descrizione

int PDOStatement::rowCount ( void )

PDOStatement::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.

Esempi

Esempio 1. Return the number of deleted rows

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.

<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>

Il precedente esempio visualizzerà:

Deleted 9 rows.

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.

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
    if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
         foreach ($conn->query($sql) as $row) {
             print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
    else {
        print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

Il precedente esempio visualizzerà:

apple
banana
orange
pear

Vedere anche:

PDOStatement::columnCount()
PDOStatement::fetchColumn()
PDOStatement::query()

PDOStatement::setAttribute

(no version information, might be only in CVS)

PDOStatement::setAttribute --  Set a statement attribute

Descrizione

bool PDOStatement::setAttribute ( int attribute, mixed value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche:

PDO::getAttribute()
PDO::setAttribute()
PDOStatement::getAttribute()

PDOStatement::setFetchMode

(no version information, might be only in CVS)

PDOStatement::setFetchMode --  Set the default fetch mode for this statement

Descrizione

bool PDOStatement::setFetchMode ( int mode )

Elenco dei parametri

mode

The fetch mode must be one of the PDO::FETCH_* constants.

Valori restituiti

Returns 1 on success or FALSE on failure.

Esempi

Esempio 1. Setting the fetch mode

The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.

<?php
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh->query($sql);
  $result = $stmt->setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt->fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e->getMessage();
}
?>

Il precedente esempio visualizzerà:

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150
watermelon      pink    90

CXI. PHP Opzioni&Informazioni

Introduzione

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() -.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione per PHP Opzioni/informazioni

NomeDefaultModificabile
assert.active"1"PHP_INI_ALL
assert.bail"0"PHP_INI_ALL
assert.warning"1"PHP_INI_ALL
assert.callbackNULLPHP_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
Per maggiori dettagli e per le definizioni delle costanti PHP_INI_* fare riferimento a ini_set().

Breve descrizione dei parametri di configurazione.

assert.active boolean

Abilita l'analisi degli assert().

assert.bail boolean

Termina uno script a fronte di un assert fallito.

assert.warning boolean

Invia un PHP warning per ogni asserzione fallita.

assert.callback string

Funzione utente da richiamare a fronte di un assert fallito

assert.quiet_eval boolean

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().

enable_dl boolean

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().

max_execution_time integer

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.

max_input_time integer

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.

magic_quotes_gpc boolean

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()

magic_quotes_runtime boolean

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.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.

Tabella 2. Costanti predefinite per phpcredits()

CostanteValoreDescrizione
CREDITS_GROUP1Lista degli sviluppatori principali
CREDITS_GENERAL2 Lista generale: design e progetto del linguaggio, autori del PHP e del modulo SAPI.
CREDITS_SAPI4 Lista delle API server e dei loro sviluppatori.
CREDITS_MODULES8 Lista dei moduli e dei loro sviluppatori.
CREDITS_DOCS16 La lista del gruppo di documentazione.
CREDITS_FULLPAGE32 Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag.
CREDITS_QA64 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()

CostanteValoreDescrizione
INFO_GENERAL1 La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro.
INFO_CREDITS2 PHP Credits. Vedere anche phpcredits().
INFO_CONFIGURATION4 Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get().
INFO_MODULES8 Moduli caricati e le loro impostazioni.
INFO_ENVIRONMENT16 Variabili d'ambiente disponibili in $_ENV.
INFO_VARIABLES32 Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE64 Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza.
INFO_ALL-1 Visualizza tutto quanto descritto. Questo è il valore dei default.

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

Sommario
assert_options -- Imposta/ottiene vari parametri per assert
assert -- Verifica se un'asserzione è FALSE
dl -- Carica i moduli del PHP a runtime
extension_loaded -- Verifica se un modulo è già stato caricato
get_cfg_var --  Restituisce il valore di un'opzione di configurazione del PHP
get_current_user --  Restituisce il nome del proprietario dello script PHP
get_defined_constants --  Restituisve un array associativo con i nomi di tutte le costanti ed i loro valori
get_extension_funcs --  Restituisce una matrice con i nomi delle funzioni di un modulo
get_include_path --  Restituisce il valore del parametro di configurazione include_path
get_included_files --  Restituisce una matrice con i nomi dei file inclusi o richiesti
get_loaded_extensions --  Restituisce una matrice con il nome di tutti i moduli compilati e caricati
get_magic_quotes_gpc --  Restituisce l'attuale configurazione di magic quotes gpc
get_magic_quotes_runtime --  Restituisce l'impostazione corrente della direttiva magic_quotes_runtime
get_required_files -- Alias di get_included_files()
getenv -- Restituisce il valore di una variabile d'ambiente
getlastmod -- Restituisce la data dell'ultima modifica alla pagina
getmygid -- Restituisce il GID del proprietario dello script PHP
getmyinode -- Restituisce l'inode dello script
getmypid -- Restituisce l'ID del processo PHP
getmyuid -- Restituisce l'UID del proprietario dello script PHP
getopt -- Ottiene le opzioni dagli argomenti della linea di comando
getrusage -- Restituisce lo stato dell'utilizzo delle risorse
ini_alter -- Alias di ini_set()
ini_get_all -- Restituisce tutte le opzioni di configurazione
ini_get -- Restituisce il valore delle opzioni di configurazione
ini_restore -- Ripristina il valore di un'opzione di configurazione
ini_set -- Imposta le opzioni di configurazione
main -- Riferimento a main()
memory_get_usage -- Restituisce la quantità di memoria allocata dal PHP
php_ini_scanned_files -- Restituisce l'elenco dei file .ini leti dalla directory ini aggiuntiva
php_logo_guid -- Restituisce il guid del logo
php_sapi_name --  Restituisce il tipo di interfaccia tra il PHP ed il server web
php_uname --  Restituisce informazioni sul sistema operativo su cui gira il PHP
phpcredits -- Visualizza i credits per il PHP
phpinfo -- Visualizza diverse informazioni sul PHP
phpversion -- Restituisce la versione del PHP
putenv -- Imposta il valore di una variabile d'ambiente
restore_include_path --  Ripristina il valore dell'opzione include_path
set_include_path --  Imposta include_path
set_magic_quotes_runtime --  Imposta il valore attuale di magic_quotes_runtime
set_time_limit -- Limita il tempo massimo di esecuzione
version_compare --  Confronta due stringhe contenenti il numero di versione di "PHP-standardized"
zend_logo_guid -- Ottiene il guid del logo Zend
zend_version -- Restituisce il numero di versione dell'engine Zend

assert_options

(PHP 4, PHP 5)

assert_options -- Imposta/ottiene vari parametri per assert

Descrizione

mixed assert_options ( int what [, mixed value] )

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

opzioneparametro inidefaultdescrizione
ASSERT_ACTIVEassert.active1abilita l'assert()
ASSERT_WARNINGassert.warning1indica a PHP i generare un warning per ogni asserzione fallita
ASSERT_BAILassert.bail0termina l'esecuzione alla prima asserzione fallita
ASSERT_QUIET_EVALassert.quiet_eval0 disabilita la gestione degli errori nelle espressioni di asserzione
ASSERT_CALLBACKassert.callback(NULL)funzione utente da richiamare per le asserzioni fallite

assert_options() restituirà l'impostazione originale di ogni opzione, oppure FALSE se fallisce.

assert

(PHP 4, PHP 5)

assert -- Verifica se un'asserzione è FALSE

Descrizione

int assert ( mixed assertion )

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

<?php
// Attiva le asserzioni 
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Crea la funzione personalizzata
function my_assert_handler($file, $line, $code) 
{
    echo "<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />";
}

// Imposta il callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Crea una asserzione che fallisce
assert('mysql_query("")');
?>

dl

(PHP 3, PHP 4, PHP 5)

dl -- Carica i moduli del PHP a runtime

Descrizione

int dl ( string library )

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()

<?php
// Caricare un modulo in base al sistema operativo
if (!extension_loaded('sqlite')) {
    if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
        dl('php_sqlite.dll');
    } else {
        dl('sqlite.so');
    }
}

// Oppure la costante PHP_SHLIB_SUFFIX disponibile da 4.3.0
if (!extension_loaded('sqlite')) {
    $prefix = (PHP_SHLIB_SUFFIX == 'dll') ? 'php_' : '';
    dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>

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)

Quindi considerando quanto detto, la directory di default può essere <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, /usr/local/php/lib/php/extensions/debug-non-zts-20010901 oppure /usr/local/php/lib/php/extensions/no-debug-zts-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().

extension_loaded

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

extension_loaded -- Verifica se un modulo è già stato caricato

Descrizione

bool extension_loaded ( string name )

Restituisce TRUE se il modulo specificato da name è caricato, oppure FALSE.

Esempio 1. Esempio di uso di extension_loaded()

<?php
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}
?>

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().

get_cfg_var

(PHP 3, PHP 4, PHP 5)

get_cfg_var --  Restituisce il valore di un'opzione di configurazione del PHP

Descrizione

string get_cfg_var ( string varname )

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().

get_current_user

(PHP 3, PHP 4, PHP 5)

get_current_user --  Restituisce il nome del proprietario dello script PHP

Descrizione

string get_current_user ( void )

Restituisce il nome del proprietario dello script PHP.

Vedere anche getmyuid(), getmygid(), getmypid(), getmyinode() e getlastmod().

get_defined_constants

(PHP 4 >= 4.1.0, PHP 5)

get_defined_constants --  Restituisve un array associativo con i nomi di tutte le costanti ed i loro valori

Descrizione

array get_defined_constants ( void )

Questa 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().

get_extension_funcs

(PHP 4, PHP 5)

get_extension_funcs --  Restituisce una matrice con i nomi delle funzioni di un modulo

Descrizione

array get_extension_funcs ( string module_name )

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()

get_include_path

(PHP 4 >= 4.3.0, PHP 5)

get_include_path --  Restituisce il valore del parametro di configurazione include_path

Descrizione

string get_include_path ( void )

Restituisce il valore di include_path.

Esempio 1. Esempio di uso di get_include_path()

<?php
// Funziona da PHP 4.3.0
echo get_include_path();

// Funziona in tutte le versioni di PHP
echo ini_get('include_path');
?>

Vedere anche ini_get(), restore_include_path(), set_include_path() e include().

get_included_files

(PHP 4, PHP 5)

get_included_files --  Restituisce una matrice con i nomi dei file inclusi o richiesti

Descrizione

array get_included_files ( void )

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)

<?php

include 'test1.php';
include_once 'test2.php';
require 'test3.php';
require_once 'test4.php';

$included_files = get_included_files();

foreach ($included_files as $filename) {
    echo "$filename\n";
}

?>

l'esempio visualizzerà:

abc.php
test1.php
test2.php
test3.php
test4.php

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().

get_loaded_extensions

(PHP 4, PHP 5)

get_loaded_extensions --  Restituisce una matrice con il nome di tutti i moduli compilati e caricati

Descrizione

array get_loaded_extensions ( void )

Restituisce 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().

get_magic_quotes_gpc

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

get_magic_quotes_gpc --  Restituisce l'attuale configurazione di magic quotes gpc

Descrizione

int get_magic_quotes_gpc ( void )

Restituisce 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()

<?php
echo get_magic_quotes_gpc();         // 1
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>

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

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);
 
        return $value;
    }
 
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
?>
Il parametro magic-quote è stato aggiunto per ridurre il rischio di scrivere codice pericoloso da parte dei principianti. Se si disabilita magic-quote, occorre prestare molta attenzione a proteggersi dagli attacchi di SQL injection.

Vedere anche addslashes(), stripslashes(), get_magic_quotes_runtime() e ini_get().

get_magic_quotes_runtime

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

get_magic_quotes_runtime --  Restituisce l'impostazione corrente della direttiva magic_quotes_runtime

Descrizione

int get_magic_quotes_runtime ( void )

Restituisce 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().

get_required_files

(PHP 4, PHP 5)

get_required_files -- Alias di get_included_files()

Descrizione

Questa funzione è un alias di get_included_files().

getenv

(PHP 3, PHP 4, PHP 5)

getenv -- Restituisce il valore di una variabile d'ambiente

Descrizione

string getenv ( string varname )

Restituisce il valore della variabile d'ambiente varname, oppure FALSE in caso di errore.

<?php
$ip = getenv("REMOTE_ADDR"); // get the ip number of the user
?>

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().

getlastmod

(PHP 3, PHP 4, PHP 5)

getlastmod -- Restituisce la data dell'ultima modifica alla pagina

Descrizione

int getlastmod ( void )

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.

Esempio 1. Esempio di uso di getlastmod()

<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>

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().

getmygid

(PHP 4 >= 4.1.0, PHP 5)

getmygid -- Restituisce il GID del proprietario dello script PHP

Descrizione

int getmygid ( void )

Restituisce l'ID del gruppo del proprietario dello script, oppure FALSE per errore.

Vedere anche getmyuid(), getmypid(), get_current_user(), getmyinode() e getlastmod().

getmyinode

(PHP 3, PHP 4, PHP 5)

getmyinode -- Restituisce l'inode dello script

Descrizione

int getmyinode ( void )

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

getmypid

(PHP 3, PHP 4, PHP 5)

getmypid -- Restituisce l'ID del processo PHP

Descrizione

int getmypid ( void )

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().

getmyuid

(PHP 3, PHP 4, PHP 5)

getmyuid -- Restituisce l'UID del proprietario dello script PHP

Descrizione

int getmyuid ( void )

Restituisce l'ID utente del proprietario dello script, oppure FALSE in caso di errore.

Vedere anche getmygid(), getmypid(), get_current_user(), getmyinode() e getlastmod().

getopt

(PHP 4 >= 4.3.0, PHP 5)

getopt -- Ottiene le opzioni dagli argomenti della linea di comando

Descrizione

array getopt ( string options [, array longopts] )

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).

<?php
// parse the command line ($GLOBALS['argv'])
$options = getopt("f:hp:");
?>

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

getrusage

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

getrusage -- Restituisce lo stato dell'utilizzo delle risorse

Descrizione

array getrusage ( [int who] )

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.

Esempio 1. Esempio di uso di getrusage()

<?php
$dat = getrusage();
echo $dat["ru_nswap"];         // numero di swap
echo $dat["ru_majflt"];        // numero di page faults
echo $dat["ru_utime.tv_sec"];  // tempo utente utilizzato (seconds)
echo $dat["ru_utime.tv_usec"]; // tempo utente utilizzato (microseconds)
?>
Per maggior dettagli si veda la pagina di getrusage(2) nel manuale del proprio sistema.

Nota: Questa funzione non è implementata su piattaforme Windows

ini_alter

(PHP 4, PHP 5)

ini_alter -- Alias di ini_set()

Descrizione

Questa funzione è un alias di ini_set().

ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_all -- Restituisce tutte le opzioni di configurazione

Descrizione

array ini_get_all ( [string extension] )

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()

<?php
$inis = ini_get_all();

print_r($inis);

?>

Parte dell'aoutput potrebbe essere:

Array
(
    [allow_call_time_pass_reference] => Array
    (
        [global_value] => 1
        [local_value] => 1
        [access] => 6
    )
    [allow_url_fopen] => Array
    (
        [global_value] => 1
        [local_value] => 1
        [access] => 7
    )

    ...

)

Vedere anche ini_get(), ini_restore(), ini_set(), get_loaded_extensions() e phpinfo().

ini_get

(PHP 4, PHP 5)

ini_get -- Restituisce il valore delle opzioni di configurazione

Descrizione

string ini_get ( string varname )

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()

<?php
/*
Il nostro php.ini contiene i seguenti parametri:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n"; 
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));
  	 
function return_bytes($val) {
    $val = trim($val);
    $last = $val{strlen($val)-1};
    switch($last) {
        case 'k':
        case 'K':
            return (int) $val * 1024;
            break;
        case 'm':
        case 'M':
            return (int) $val * 1048576;
            break;
        default:
            return $val;
    }
}
?>

Lo script produrrà:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

Vedere anche: get_cfg_var(), ini_get_all(), ini_restore() e ini_set().

ini_restore

(PHP 4, PHP 5)

ini_restore -- Ripristina il valore di un'opzione di configurazione

Descrizione

void ini_restore ( string varname )

Ripristina il valore della data opzione di configurazione allo stato originale.

Vedere anche ini_get(), ini_get_all() e ini_set().

ini_set

(PHP 4, PHP 5)

ini_set -- Imposta le opzioni di configurazione

Descrizione

string ini_set ( string varname, string newvalue )

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()

main

(no version information, might be only in CVS)

main -- Riferimento a main()

Descrizione

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 funzioneNon 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.

memory_get_usage

(PHP 4 >= 4.3.2, PHP 5)

memory_get_usage -- Restituisce la quantità di memoria allocata dal PHP

Descrizione

int memory_get_usage ( void )

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

Esempio 1. Esempio di uso di memory_get_usage()

<?php
// Questo è solo un esempio. I numeri reali
// variano da sistema a sistema.

echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo memory_get_usage() . "\n"; // 57960

unset($a);

echo memory_get_usage() . "\n"; // 36744

?>

Vedere anche memory_limit.

php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5)

php_ini_scanned_files -- Restituisce l'elenco dei file .ini leti dalla directory ini aggiuntiva

Descrizione

string php_ini_scanned_files ( void )

php_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).

Esempio 1. Un semplice esempio di lista restuita dalla funzione

<?php
if ($filelist = php_ini_scanned_files()) {
    if (strlen($filelist) > 0) {
        $files = explode(',', $filelist);

        foreach ($files as $file) {
            echo "<li>" . trim($file) . "</li>\n";
        }
    }
}
?>

Vedere anche ini_set() e phpinfo().

php_logo_guid

(PHP 4, PHP 5)

php_logo_guid -- Restituisce il guid del logo

Descrizione

string php_logo_guid ( void )

Questa funzione restituisce l'ID che può essere utlizzato per visualizzar il logo PHP pre-inserito.

Esempio 1. Esempio di uso di php_logo_guid()

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . php_logo_guid() . '" alt="PHP Logo !" />';

?>

Vedere anche phpinfo(), phpversion(), phpcredits() e zend_logo_guid().

php_sapi_name

(PHP 4 >= 4.0.1, PHP 5)

php_sapi_name --  Restituisce il tipo di interfaccia tra il PHP ed il server web

Descrizione

string php_sapi_name ( void )

php_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.

Esempio 1. Esempio di uso di php_sapi_name()

<?php
$sapi_type = php_sapi_name();
iif (substr($sapi_type, 0, 3) == 'cgi') {
    echo "Si usa CGI PHP\n";
} else {
    echo "Non si usa CGI PHP\n";
}
?>

php_uname

(PHP 4 >= 4.0.2, PHP 5)

php_uname --  Restituisce informazioni sul sistema operativo su cui gira il PHP

Descrizione

string php_uname ( [string mode] )

php_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()

<?php
echo php_uname();
echo PHP_OS;

/* possibili output:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux

FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD

Windows NT XN1 5.1 build 2600
WINNT
*/

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

?>

Esistono alcune Costanti PHP predefinite che possono essere di aiuto, ad esempio:

Esempio 2. Alcune costanti relative al OS

<?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX;    // so
echo PATH_SEPARATOR;      // :

// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX;    // dll
echo PATH_SEPARATOR;      // ;
?>

Vedere anche phpversion(), php_sapi_name() e phpinfo().

phpcredits

(PHP 4, PHP 5)

phpcredits -- Visualizza i credits per il PHP

Descrizione

void phpcredits ( [int flag] )

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:

<?php
phpcredits(CREDITS_GENERAL);
?>

Se si vuole stampare l'elenco degli sviluppatori principali e del grupo di documentazione, in una pagina proprio conto, utilizzare:

<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>

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()

nomedescrizione
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_DOCSLa 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_GROUPLista 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().

phpinfo

(PHP 3, PHP 4, PHP 5)

phpinfo -- Visualizza diverse informazioni sul PHP

Descrizione

int phpinfo ( [int what] )

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)ValoreDescrizione
INFO_GENERAL1 La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro.
INFO_CREDITS2 PHP 4 Credits. Vedere anche phpcredits().
INFO_CONFIGURATION4 Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get().
INFO_MODULES8 Moduli caricati e le loro impostazioni. Vedere anche get_loaded_extensions().
INFO_ENVIRONMENT16 Variabili d'ambiente disponibili in $_ENV.
INFO_VARIABLES32 Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE64 Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza.
INFO_ALL-1 Visualizza tutto quanto descritto. Questo è il valore dei default.

Esempio 1. Esempio di uso di phpinfo()

<?php

// Visualizza tutte le informazioni, default: INFO_ALL
phpinfo();

// Solo le informazioni sui moduli
// phpinfo(8) visualizza il medesimo risultato
phpinfo(INFO_MODULES);

?>

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.

phpversion

(PHP 3, PHP 4, PHP 5)

phpversion -- Restituisce la versione del PHP

Descrizione

string phpversion ( void )

Restituisce una stringa contenente la versione dell'interprete PHP.

Nota: Questa informazione è anche disponibile come costante predefinita PHP_VERSION.

Esempio 1. Esempio di uso di phpversion()

<?php
// Ad esempio visualizza 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();
?>

Vedere anche version_compare(), phpinfo(), phpcredits(), php_logo_guid() e zend_version().

putenv

(PHP 3, PHP 4, PHP 5)

putenv -- Imposta il valore di una variabile d'ambiente

Descrizione

void putenv ( string setting )

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!

Esempio 1. Impostazione di una variabile d'ambiente

<?php
putenv("UNIQID=$uniqid");
?>

Vedere anche getenv().

restore_include_path

(PHP 4 >= 4.3.0, PHP 5)

restore_include_path --  Ripristina il valore dell'opzione include_path

Descrizione

void restore_include_path ( void )

Ripristina il valore del parametro di configurazione include_path al valore impostato in php.ini

Esempio 1. Esempio di uso di restore_include_path()

<?php

echo get_include_path();  // .:/usr/local/lib/php

set_include_path('/inc');

echo get_include_path();  // /inc

// A partire da PHP 4.3.0
restore_include_path();

// In tutte le versioni di PHP
ini_restore('include_path');

echo get_include_path();  // .:/usr/local/lib/php

?>

Vedere anche ini_restore(), set_include_path(), get_include_path() e include().

set_include_path

(PHP 4 >= 4.3.0, PHP 5)

set_include_path --  Imposta include_path

Descrizione

string set_include_path ( string new_include_path )

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.

Esempio 1. Esempio di uso di set_include_path()

<?php
// A partire da PHP 4.3.0
set_include_path('/inc');

// In tutte le versioni di PHP
ini_set('include_path', '/inc');
?>

Vedere anche ini_set(), get_include_path(), restore_include_path() e include().

set_magic_quotes_runtime

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

set_magic_quotes_runtime --  Imposta il valore attuale di magic_quotes_runtime

Descrizione

bool set_magic_quotes_runtime ( int new_setting )

Imposta 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().

set_time_limit

(PHP 3, PHP 4, PHP 5)

set_time_limit -- Limita il tempo massimo di esecuzione

Descrizione

void set_time_limit ( int seconds )

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.

version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compare --  Confronta due stringhe contenenti il numero di versione di "PHP-standardized"

Descrizione

int version_compare ( string version1, string version2 [, string operator] )

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.

Esempio 1. Esempio di uso di version_compare()

<?php
// prints -1
echo version_compare("4.0.4", "4.0.6");

// queste stampano 1
echo version_compare("4.0.4", "4.0.6", "<");
echo version_compare("4.0.6", "4.0.6", "eq");
?>

zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guid -- Ottiene il guid del logo Zend

Description

string zend_logo_guid ( void )

Questa funzioen restituisce l'ID che può essere utilizzato per visualizzare il logo Zend usando l'immagine inserita nel PHP.

Esempio 1. Esempio di uso di zend_logo_uid()

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . zend_logo_guid() . '" alt="Zend Logo !" />';

?>

Vedere anche php_logo_guid().

zend_version

(PHP 4, PHP 5)

zend_version -- Restituisce il numero di versione dell'engine Zend

Descrizione

string zend_version ( void )

Restituisce una stringa contenente il numero di versione dell'engine Zend.

Esempio 1. Esempio di uso di zend_version()

<?php
// ad esempio visualizza: 'Zend engine version: 1.0.4'
echo "Zend engine version: " . zend_version();
?>

Vedere anche phpinfo(), phpcredits(), php_logo_guid() e phpversion().

CXII. Funzioni POSIX

Introduzione

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.


Installazione

Le funzioni POSIX sono abilitate per default. Si possono disabilitare con --disable-posix.


Costanti predefinite

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.

POSIX_F_OK (integer)

Check whether the file exists.

POSIX_R_OK (integer)

Check whether the file exists and has read permissions.

POSIX_W_OK (integer)

Check whether the file exists and has write permissions.

POSIX_X_OK (integer)

Check whether the file exists and has execute permissions.

POSIX_S_IFBLK (integer)

Block special file

POSIX_S_IFCHR (integer)

Character special file

POSIX_S_IFIFO (integer)

FIFO (named pipe) special file

POSIX_S_IFREG (integer)

Normal file

POSIX_S_IFSOCK (integer)

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.


Vedere anche:

Potrebbe essere interessante anche la sezione Funzioni per il controllo dei processi.

Sommario
posix_access --  Determine accessibility of a file
posix_ctermid -- Restituisce il percorso del terminale
posix_get_last_error --  Recupera il numero di errore dell'ultima funzione posix non riuscita
posix_getcwd -- Percorso della directory corrente
posix_getegid --  Restituisce l'ID del gruppo per il processo corrente
posix_geteuid --  Restituisce l'ID dell'utente per il processo corrente
posix_getgid --  Restituisce il reale ID del gruppo per il processo corrente
posix_getgrgid -- Restituisce informazioni su un gruppo dato il suo ID
posix_getgrnam -- Restituisce le informazioni di un gruppo dato il nome
posix_getgroups --  Restituisce i gruppi per il processo corrente
posix_getlogin -- Restituisce il nome dell'utente
posix_getpgid -- Restituisce l'id del gruppo del processo per il controllo dei job
posix_getpgrp --  Restituisce l'identificatore di gruppo per il processo corrente
posix_getpid -- Restituisce l'ID per il processo corrente
posix_getppid -- Restituisce l'ID del processo genitore
posix_getpwnam -- Restituisce informazioni su un utente dato il nome
posix_getpwuid -- Restituisce le informazioni di un utente dato il suo ID
posix_getrlimit -- Restituisce informazioni sui limiti delle risorse del sistema
posix_getsid -- Restituisce il sid corrente per un processo
posix_getuid --  Restituisce il reale ID dell'utente per il processo corrente
posix_isatty --  Determina se il decrittore di file è un terminale
posix_kill -- Invia un segnale ad un processo
posix_mkfifo --  Crea un file speciale di tipo fifo (una pipe nominata)
posix_mknod --  Create a special or ordinary file (POSIX.1)
posix_setegid --  Imposta l'effettivo GID per il processo corrente
posix_seteuid --  Imposta l'effettivo UID del processo corrente
posix_setgid --  Imposta il GID per il processo corrente
posix_setpgid -- Imposta l'id di gruppo per il controllo dei job
posix_setsid -- Rende il processo corrente leader di sessione
posix_setuid --  Imposta l'UID per il processo corrente
posix_strerror --  Recupera il messaggio di errore di un dato codice di errore
posix_times -- Restituisce il tempo del processo
posix_ttyname -- Determina il nome del device per il terminale
posix_uname -- Restituisce il nome del sistema

posix_access

(PHP 5 >= 5.1.0RC1)

posix_access --  Determine accessibility of a file

Descrizione

bool posix_access ( string file [, int mode] )

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.

Elenco dei parametri

file

The name of the file to be tested.

mode

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. posix_access() example

This example will check if the $file is readable and writable, otherwise will print an error message.

<?php

$file = 'some_file';

if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {
    echo 'The file is readable and writable!';

} else {
    $error = posix_get_last_error();

    echo "Error $error: " . posix_strerror($error);
}

?>

posix_ctermid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_ctermid -- Restituisce il percorso del terminale

Descrizione

string posix_ctermid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5)

posix_get_last_error --  Recupera il numero di errore dell'ultima funzione posix non riuscita

Descrizione

int posix_get_last_error ( void )

Restituisce 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().

posix_getcwd

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getcwd -- Percorso della directory corrente

Descrizione

string posix_getcwd ( void )

La funzione posix_getcwd() restituisce il percorso assoluto della corrente directory di lavoro.La funzioneposix_getcwd() restituisce FALSE se si verifica un errore.

posix_getegid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getegid --  Restituisce l'ID del gruppo per il processo corrente

Descrizione

int posix_getegid ( void )

La 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.

posix_geteuid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_geteuid --  Restituisce l'ID dell'utente per il processo corrente

Descrizione

int posix_geteuid ( void )

Restituisce 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.

posix_getgid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getgid --  Restituisce il reale ID del gruppo per il processo corrente

Descrizione

int posix_getgid ( void )

La 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.

posix_getgrgid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getgrgid -- Restituisce informazioni su un gruppo dato il suo ID

Descrizione

array posix_getgrgid ( int gid )

Restituisce 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.

Esempio 1. Esempio dell'utilizzo di posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);

?>

Output dell'esempio:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array 
        ( 
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

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.

posix_getgrnam

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getgrnam -- Restituisce le informazioni di un gruppo dato il nome

Descrizione

array posix_getgrnam ( string name )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

posix_getgroups

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getgroups --  Restituisce i gruppi per il processo corrente

Descrizione

array posix_getgroups ( void )

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.

posix_getlogin

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getlogin -- Restituisce il nome dell'utente

Descrizione

string posix_getlogin ( void )

Restituisce il nome dell'utente proprietario del processo corrente. Vedere posix_getpwnam() per dettagli su come ottenere maggiori informazioni sull'utente.

posix_getpgid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getpgid -- Restituisce l'id del gruppo del processo per il controllo dei job

Descrizione

int posix_getpgid ( int pid )

La 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.

posix_getpgrp

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getpgrp --  Restituisce l'identificatore di gruppo per il processo corrente

Descrizione

int posix_getpgrp ( void )

Restituisce 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.

posix_getpid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getpid -- Restituisce l'ID per il processo corrente

Descrizione

int posix_getpid ( void )

Restituisce l'ID per il processo corrente.

posix_getppid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getppid -- Restituisce l'ID del processo genitore

Descrizione

int posix_getppid ( void )

Restituisce l'ID del processo genitore per il processo corrente.

posix_getpwnam

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getpwnam -- Restituisce informazioni su un utente dato il nome

Descrizione

array posix_getpwnam ( string username )

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

ElementoDescrizione
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.

posix_getpwuid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_getpwuid -- Restituisce le informazioni di un utente dato il suo ID

Descrizione

array posix_getpwuid ( int uid )

La 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

ElementoDescrizione
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.

posix_getrlimit

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getrlimit -- Restituisce informazioni sui limiti delle risorse del sistema

Descrizione

array posix_getrlimit ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

posix_getsid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getsid -- Restituisce il sid corrente per un processo

Descrizione

int posix_getsid ( int pid )

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.

posix_getuid

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_getuid --  Restituisce il reale ID dell'utente per il processo corrente

Descrizione

int posix_getuid ( void )

La 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.

posix_isatty

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_isatty --  Determina se il decrittore di file è un terminale

Descrizione

bool posix_isatty ( int fd )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

posix_kill

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_kill -- Invia un segnale ad un processo

Descrizione

bool posix_kill ( int pid, int sig )

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.

posix_mkfifo

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_mkfifo --  Crea un file speciale di tipo fifo (una pipe nominata)

Descrizione

bool posix_mkfifo ( string pathname, int mode )

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

(PHP 5 >= 5.1.0RC1)

posix_mknod --  Create a special or ordinary file (POSIX.1)

Descrizione

bool posix_mknod ( string pathname, int mode [, int major [, int minor]] )

posix_mknod() creates a special or ordinary file.

Elenco dei parametri

pathname

The file to create

mode

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.

major

The major device kernel identifier

minor

The minor device kernel identifier

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A posix_mknod() example

<?php

$file = '/tmp/tmpfile';  // file name
$type = POSIX_S_IFBLOCK; // file type
$permissions = 0777;     // octal

if (!posix_mknod($file, $type | $permissions)) {
    die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?>

Vedere anche:

posix_mkfifo()

posix_setegid

(PHP 4 >= 4.0.2, PHP 5)

posix_setegid --  Imposta l'effettivo GID per il processo corrente

Descrizione

bool posix_setegid ( int gid )

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..

posix_seteuid

(PHP 4 >= 4.0.2, PHP 5)

posix_seteuid --  Imposta l'effettivo UID del processo corrente

Descrizione

bool posix_seteuid ( int uid )

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().

posix_setgid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setgid --  Imposta il GID per il processo corrente

Descrizione

bool posix_setgid ( int gid )

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.

posix_setpgid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setpgid -- Imposta l'id di gruppo per il controllo dei job

Descrizione

int posix_setpgid ( int pid, int pgid )

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.

posix_setsid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setsid -- Rende il processo corrente leader di sessione

Descrizione

int posix_setsid ( void )

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.

posix_setuid

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_setuid --  Imposta l'UID per il processo corrente

Descrizione

bool posix_setuid ( int uid )

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().

posix_strerror

(PHP 4 >= 4.2.0, PHP 5)

posix_strerror --  Recupera il messaggio di errore di un dato codice di errore

Descrizione

string posix_strerror ( int errno )

La 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().

posix_times

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_times -- Restituisce il tempo del processo

Descrizione

array posix_times ( void )

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.

posix_ttyname

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

posix_ttyname -- Determina il nome del device per il terminale

Descrizione

string posix_ttyname ( int fd )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

posix_uname

(PHP 3 >= 3.0.10, PHP 4, PHP 5)

posix_uname -- Restituisce il nome del sistema

Descrizione

array posix_uname ( void )

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.

CXIII. Funzioni per le espressioni regolari (POSIX estesa)

Introduzione

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Esempio 1. Esempi di espressione regolare

<?php
/* Restituisce vero se "abc"
   viene trovata ovunque in $string. */
ereg("abc", $string);            

/* Restituisce vero se "abc"
   viene trovata all'inizio di $string. */
ereg("^abc", $string);

/* Restituisce vero se "abc"
   viene trovata alla fine di $string. */
ereg("abc$", $string);

/* Restituisce vero se il browser
   è Netscape 2, 3 oppure MSIE 3. */
eregi("(ozilla.[23]|MSIE.3)", $HTTP_USER_AGENT);

/* Posizione tre parole separate da spazio
   in $regs[1], $regs[2] e $regs[3]. */
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string, $regs); 

/* Posiziona il tag <br /> all'inizio di $string. */
$string = ereg_replace("^", "<br />", $string);

/* Posiziona il tag <br /> alla fine di $string. */ 
$string = ereg_replace("$", "<br />", $string);

/* Toglie ogni carattere di invio
   da $string. */
$string = ereg_replace("\n", "", $string);
?>


Vedere anche:

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.

Sommario
ereg_replace -- Sostituzioni con espressioni regolari
ereg -- Riconoscimento di espressione regolare
eregi_replace -- Sostituzioni con espressioni regolari senza distinzione tra maiuscole e minuscole
eregi -- Riconoscimento di espressioni regolari senza distinzione tra maiuscole e minuscole
split -- Suddivide una stringa in una matrice utilizzando le espressioni regolari
spliti --  Suddivide una stringa in una matrice usando le espressioni regolari senza distinguere tra maiuscole e minuscole
sql_regcase --  Genera una espressione regolare per riconoscimenti senza distinguere tra maiuscole e minuscole

ereg_replace

(PHP 3, PHP 4, PHP 5)

ereg_replace -- Sostituzioni con espressioni regolari

Descrizione

string ereg_replace ( string espressione_regolare, string testo_sostitutivo, string stringa )

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:

Esempio 1. ereg_replace() esempio

<?php
$stringa = "Questo è un test";
echo ereg_replace(" è", " fu", $stringa);
echo ereg_replace("( )è", "\\1fu", $stringa);
echo ereg_replace("(( )è)", "\\2fu", $stringa);
?>

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

<?php
/* Questo non si comporta come atteso. */
$num = 4;
$stringa = "Questa stringa ha quattro parole.";
$stringa = ereg_replace('quattro', $num, $stringa);
echo $stringa;   /* Risultato: 'Questa stringa ha   parole.' */

/* Questo funziona. */
$num = '4';
$stringa = "Questa stringa ha quattro parole.";
$stringa = ereg_replace('quattro', $num, $stringa);
echo $stringa;   /* Risultato: 'Questa stringa ha 4 parole' */
?>

Esempio 3. Sostituzione di URL

<?php
$testo = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">\\0</a>", $testo);
?>

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().

ereg

(PHP 3, PHP 4, PHP 5)

ereg -- Riconoscimento di espressione regolare

Descrizione

int ereg ( string epressione_regolare, string stringa [, array &regs] )

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:

Esempio 1. Esempio dell'uso di ereg() Esempio

<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $data, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Formato di data non valido: $data";
}
?>

Vedere anche eregi(), ereg_replace(), eregi_replace(), preg_match(), strpos() e strstr().

eregi_replace

(PHP 3, PHP 4, PHP 5)

eregi_replace -- Sostituzioni con espressioni regolari senza distinzione tra maiuscole e minuscole

Descrizione

string eregi_replace ( string espressione_regolare, string testo_sostitutivo, string stringa )

Questa funzione è identica a ereg_replace(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.

Esempio 1. Sottolinea i risultati della ricerca

<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

Vedere anche ereg(), eregi() e ereg_replace().

eregi

(PHP 3, PHP 4, PHP 5)

eregi -- Riconoscimento di espressioni regolari senza distinzione tra maiuscole e minuscole

Descrizione

int eregi ( string espressione_regolare, string stringa [, array &regs] )

Questa funzione è identica a ereg(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.

Esempio 1. Esempio di eregi()

<?php
$string = 'XYZ';
if (eregi("z", $stringa)) {
    echo "'$stringa' contiene una 'z' oppure una 'Z'!";
}
?>

Vedere anche ereg(), ereg_replace(), eregi_replace(), stripos() e stristr().

split

(PHP 3, PHP 4, PHP 5)

split -- Suddivide una stringa in una matrice utilizzando le espressioni regolari

Descrizione

array split ( string espressione_regolare, string stringa [, int limite] )

Suggerimento: 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:

Esempio 1. Esempio di split()

<?php
list($user, $pass, $uid, $gid, $extra) = split(":", $passwd_line, 5); 
?>

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:

Esempio 2. split() esempio

// Delimitatori di testo: barre, punti, trattini
$data = "04/30/1973"; 
list ($mese, $giorno, $anno) = split ('[/.-]', $data);
echo "Mese: $mese; Giorno: $giorno; Anno: $anno<br>\n";
?>

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().

spliti

(PHP 4 >= 4.0.1, PHP 5)

spliti --  Suddivide una stringa in una matrice usando le espressioni regolari senza distinguere tra maiuscole e minuscole

Descrizione

array spliti ( string pattern, string string [, int limit] )

Questa 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:

Esempio 1. Esempio di uso di spliti()

<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>

Il precedente esempio visualizzerà:

Array
(
  [0] => 
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

Vedere anche preg_split(), split(), explode(), e implode().

sql_regcase

(PHP 3, PHP 4, PHP 5)

sql_regcase --  Genera una espressione regolare per riconoscimenti senza distinguere tra maiuscole e minuscole

Descrizione

string sql_regcase ( string stringa )

La 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.

Esempio 1. sql_regcase() esempio

<?php
echo sql_regcase("Foo bar");
?>

Il precedente esempio visualizzerà:

[Ff][Oo][Oo] - [Bb][Aa][Rr].

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.

CXIV. Funzioni PostgreSQL

Introduzione

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.


Requisiti

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/.


Installazione

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. PostgreSQL configuration options

NameDefaultChangeableChangelog
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_SYSTEMAvailable since PHP 4.2.0.
pgsql.ignore_notice"0"PHP_INI_ALLAvailable since PHP 4.3.0.
pgsql.log_notice"0"PHP_INI_ALLAvailable since PHP 4.3.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

The maximum number of Postgres connections per process, including persistent connections.

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.


Utilizzo e suggerimenti

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

Vecchio nomeNuovo nome
pg_exec()pg_query()
pg_getlastoid()pg_last_oid()
pg_cmdtuples()pg_affected_rows()
pg_numrows()pg_num_rows()
pg_numfields()pg_num_fields()
pg_fieldname()pg_field_name()
pg_fieldsize()pg_field_size()
pg_fieldnum()pg_field_num()
pg_fieldprtlen()pg_field_prtlen()
pg_fieldisnull()pg_field_is_null()
pg_freeresult()pg_free_result()
pg_result()pg_fetch_result()
pg_loreadall()pg_lo_read_all()
pg_locreate()pg_lo_create()
pg_lounlink()pg_lo_unlink()
pg_loopen()pg_lo_open()
pg_loclose()pg_lo_close()
pg_loread()pg_lo_read()
pg_lowrite()pg_lo_write()
pg_loimport()pg_lo_import()
pg_loexport()pg_lo_export()

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

PostmasterPHPStatus
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.

Esempio 1. Impostazione dei parametri di default

PGHOST=pgsql.example.com
PGPORT=7890
PGDATABASE=web-system
PGUSER=web-user
PGPASSWORD=segreta
PGDATESTYLE=ISO
PGTZ=JST
PGCLIENTENCODING=EUC-JP

export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGDATESTYLE PGTZ PGCLIENTENCODING

Costanti predefinite

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.

PGSQL_ASSOC (integer)

Passed to pg_fetch_array(). Return an associative array of field names and values.

PGSQL_NUM (integer)

Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.

PGSQL_BOTH (integer)

Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).

PGSQL_CONNECT_FORCE_NEW (integer)

Passed to pg_connect() to force the creation of a new connection, rather then re-using an existing identical connection.

PGSQL_CONNECTION_BAD (integer)

Returned by pg_connection_status() indicating that the database connection is in an invalid state.

PGSQL_CONNECTION_OK (integer)

Returned by pg_connection_status() indicating that the database connection is in a valid state.

PGSQL_SEEK_SET (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.

PGSQL_SEEK_CUR (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the current position.

PGSQL_SEEK_END (integer)

Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.

PGSQL_EMPTY_QUERY (integer)

Returned by pg_result_status(). The string sent to the server was empty.

PGSQL_COMMAND_OK (integer)

Returned by pg_result_status(). Successful completion of a command returning no data.

PGSQL_TUPLES_OK (integer)

Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).

PGSQL_COPY_OUT (integer)

Returned by pg_result_status(). Copy Out (from server) data transfer started.

PGSQL_COPY_IN (integer)

Returned by pg_result_status(). Copy In (to server) data transfer started.

PGSQL_BAD_RESPONSE (integer)

Returned by pg_result_status(). The server's response was not understood.

PGSQL_NONFATAL_ERROR (integer)

Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.

PGSQL_FATAL_ERROR (integer)

Returned by pg_result_status(). A fatal error occurred.

PGSQL_TRANSACTION_IDLE (integer)

Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.

PGSQL_TRANSACTION_ACTIVE (integer)

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.

PGSQL_TRANSACTION_INTRANS (integer)

Returned by pg_transaction_status(). The connection is idle, in a transaction block.

PGSQL_TRANSACTION_INERROR (integer)

Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.

PGSQL_TRANSACTION_UNKNOWN (integer)

Returned by pg_transaction_status(). The connection is bad.

PGSQL_DIAG_SEVERITY (integer)

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.

PGSQL_DIAG_SQLSTATE (integer)

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.

PGSQL_DIAG_MESSAGE_PRIMARY (integer)

Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.

PGSQL_DIAG_MESSAGE_DETAIL (integer)

Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.

PGSQL_DIAG_MESSAGE_HINT (integer)

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.

PGSQL_DIAG_STATEMENT_POSITION (integer)

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.

PGSQL_DIAG_INTERNAL_POSITION (integer)

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.

PGSQL_DIAG_INTERNAL_QUERY (integer)

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.

PGSQL_DIAG_CONTEXT (integer)

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.

PGSQL_DIAG_SOURCE_FILE (integer)

Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.

PGSQL_DIAG_SOURCE_LINE (integer)

Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.

PGSQL_DIAG_SOURCE_FUNCTION (integer)

Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.

PGSQL_ERRORS_TERSE (integer)

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.

PGSQL_ERRORS_DEFAULT (integer)

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).

PGSQL_ERRORS_VERBOSE (integer)

Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.

PGSQL_STATUS_LONG (integer)

Passed to pg_result_status(). Indicates that numerical result code is desired.

PGSQL_STATUS_STRING (integer)

Passed to pg_result_status(). Indicates that textual result command tag is desired.

PGSQL_CONV_IGNORE_DEFAULT (integer)

Passed to pg_convert(). Ignore default values in the table during conversion.

PGSQL_CONV_FORCE_NULL (integer)

Passed to pg_convert(). Use SQL NULL in place of an empty string.

PGSQL_CONV_IGNORE_DEFAULT (integer)

Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.


Esempi

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
    $database = pg_connect ("dbname=jacarta");
    pg_query ($database, "begin");
    $oid = pg_lo_create ($database);
    echo "$oid\n";
    $handle = pg_lo_open ($database, $oid, "w");
    echo "$handle\n";
    pg_lo_write ($handle, "dati large object");
    pg_lo_close ($handle);
    pg_query ($database, "commit");
?>
Non chiudere la risorsa di connessione prima di aver chiuso la risorsa large object.

Sommario
pg_affected_rows -- Restituisce il numero delle tuple coinvolte dall'ultimo comando
pg_cancel_query --  Annulla una query asincrona
pg_client_encoding --  Restituisce la codifica caratteri del client
pg_close -- Chiude una connessione PostgreSQL
pg_connect -- Stabilisce una connessione PostgreSQL
pg_connection_busy --  Riferisce se una connessione è occupata o meno
pg_connection_reset --  Rpristina la connessione (riconnette)
pg_connection_status --  Restituisce lo stato di una connessione
pg_convert --  Converte i valori di un array associativo in una forma compatibile con i comandi SQL.
pg_copy_from --  Inserisce le tuple in una tabella prendendole da un array
pg_copy_to --  Copia una tabella in un array
pg_dbname -- Restituisce il nome del database
pg_delete --  Cancella le tuple.
pg_end_copy -- Esegue una sincronizzazione con il backend PostgreSQL
pg_escape_bytea --  Aggiunge le sequenze di escape ai dati binari nel tipo bytea
pg_escape_string --  Aggiunge le sequenze di escape nei tipi text/char
pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.
pg_fetch_all_columns -- Fetches all rows in a particular result column as an array
pg_fetch_all -- Carica tutte le tuple in un array
pg_fetch_array -- Carica una tupla in un array
pg_fetch_assoc -- Fetch a row as an array
pg_fetch_object -- Carica una tupla in un oggetto
pg_fetch_result -- Restituisce i valori da una risorsa di risultato
pg_fetch_row -- Carica una tupla in un array
pg_field_is_null -- Verifica se un campo è NULL
pg_field_name -- Restituisce il nome di un campo
pg_field_num -- Restituisce la posizione del campo specificato
pg_field_prtlen -- Restituisce la lunghezza "stampabile" di un valore
pg_field_size --  Restituisce la reale dimensione di memorizzazione del campo
pg_field_type_oid --  Returns the type ID (OID) for the corresponding field number
pg_field_type --  Restituisce il nome del tipo del campo specificato
pg_free_result -- Libera la memoria allocata per i risultati
pg_get_notify -- Ping database connection
pg_get_pid -- Ping database connection
pg_get_result --  Recupera i risultati di una query asincrona
pg_host --  Restituisce il nome dell'host associato alla connessione
pg_insert --  Inserisce un array in una tabella.
pg_last_error -- Restituisce l'ultimo messaggio d'errore di una connessione
pg_last_notice --  Restituisce l'ultimo messaggio di notifica dal server PostgreSQL
pg_last_oid -- Restituisce l'oid dell'ultimo oggetto
pg_lo_close -- Chiude un large object
pg_lo_create -- Crea un large object
pg_lo_export -- Esporta un large object salvandolo su un file
pg_lo_import -- Importa un large object da un file
pg_lo_open -- Apre un large object
pg_lo_read_all --  Legge interamente un large object e lo manda direttamente al browser
pg_lo_read -- Legge un large object
pg_lo_seek --  Ricerca la posizione di un large object
pg_lo_tell --  Restituisce la posizione attuale in un large object
pg_lo_unlink -- Cancella un large object
pg_lo_write -- Scrive un large object
pg_meta_data --  Ottiene la definizione di una tabella.
pg_num_fields -- Restituisce il numero di campi
pg_num_rows -- Restituiscein numero di tuple
pg_options -- Estrae le opzioni associate alla connessione
pg_parameter_status -- Looks up a current parameter setting of the server.
pg_pconnect -- Open a persistent PostgreSQL connection
pg_ping -- Ping database connection
pg_port --  Restituisce il numero di porta associato alla connessione
pg_prepare --  Submits a request to create a prepared statement with the given parameters, and waits for completion.
pg_put_line -- Invia una stringa terminata da NULL al backend PostgreSQL
pg_query_params -- Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
pg_query -- Esegue una query
pg_result_error_field -- Returns an individual field of an error report.
pg_result_error --  Restituisce i messaggio di errore associato al risultato
pg_result_seek -- Set internal row offset in result resource
pg_result_status --  Recupera lo stato del risultato di una query
pg_select --  Seleziona delle tuple.
pg_send_execute -- Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
pg_send_prepare -- Sends a request to create a prepared statement with the given parameters, without waiting for completion.
pg_send_query_params -- Submits a command and separate parameters to the server without waiting for the result(s).
pg_send_query --  Invia una query in modo asincrono
pg_set_client_encoding --  Imposta la codifica del client
pg_set_error_verbosity --  Determines the verbosity of messages returned by pg_last_error() and pg_result_error().
pg_trace -- iAbilita il tracciamento di una connessione PostgreSQL
pg_transaction_status -- Returns the current in-transaction status of the server.
pg_tty --  Restituisce il nome della tty associata alla connessione
pg_unescape_bytea --  Escape binary for bytea type
pg_untrace -- Disabilita il tracciamento di una connessione PostgreSQL
pg_update --  Modifica le tuple della tabella
pg_version --  Returns an array with client, protocol and server version (when available)

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_affected_rows -- Restituisce il numero delle tuple coinvolte dall'ultimo comando

Descrizione

int pg_affected_rows ( resource risultato )

pg_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.

Esempio 1. pg_affected_rows()

<?php
     $risultato = pg_query ($conn, "INSERT INTO editore VALUES ('Autore')");
     $numtuple = pg_affected_rows ($risultato);
     echo $numtuple . " tuple modificate.";
?>

Nota: Questa funzione si chiamava pg_cmdtuples().

Vedere anche pg_query() e pg_num_rows().

pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5)

pg_cancel_query --  Annulla una query asincrona

Descrizione

bool pg_cancel_query ( resource connessione )

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()

pg_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)

pg_client_encoding --  Restituisce la codifica caratteri del client

Descrizione

string pg_client_encoding ( [resource connessione] )

pg_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

(PHP 3, PHP 4, PHP 5)

pg_close -- Chiude una connessione PostgreSQL

Descrizione

bool pg_close ( resource connessione )

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

(PHP 3, PHP 4, PHP 5)

pg_connect -- Stabilisce una connessione PostgreSQL

Descrizione

resource pg_connect ( string stringa_connessione )

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

<?php
$dbconn = pg_connect ("dbname=mary");
//collegamento ad un database chiamato "mary"
$dbconn2 = pg_connect ("host=localhost port=5432 dbname=mary");
//collegamento ad un database chiamato "mary" su "localhost" alla porta "5432"
$dbconn3 = pg_connect ("host=sheep port=5432 dbname=mary user=lamb password=foo");
//collegamento ad un database chiamato "mary" sull'host "sheep" con una username ed una password
$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect ($conn_string);
//collegamento ad un database chiamato "test" sull'host "sheep" con una username ed una password
?>
Gli argomenti che si possono passare a connection_string includono host, port, tty, options, dbname, user, e password.

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

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_busy --  Riferisce se una connessione è occupata o meno

Descrizione

bool pg_connection_busy ( resource connessione )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_reset --  Rpristina la connessione (riconnette)

Descrizione

bool pg_connection_reset ( resource connessione )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_status --  Restituisce lo stato di una connessione

Descrizione

int pg_connection_status ( resource connessione )

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().

pg_convert

(PHP 4 >= 4.3.0, PHP 5)

pg_convert --  Converte i valori di un array associativo in una forma compatibile con i comandi SQL.

Descrizione

array pg_convert ( resource connessione, string nometabella, array arrayassoc [, int opzioni] )

pg_convert() controlla e converte arrayassoc rendendolo compatibile con i comandi SQL.

Nota: Questa funzione è sperimentale.

Vedere anche pg_meta_data()

pg_copy_from

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_from --  Inserisce le tuple in una tabella prendendole da un array

Descrizione

bool pg_copy_from ( resource connessione, string nometabella, array tuple [, string delimitatore [, string null_as]] )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_to --  Copia una tabella in un array

Descrizione

array pg_copy_to ( resource connessione, string nometabella [, string delimitatore [, string null_as]] )

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

(PHP 3, PHP 4, PHP 5)

pg_dbname -- Restituisce il nome del database

Descrizione

string pg_dbname ( resource connessione )

pg_dbname() restituisce il nome del database associato alla risorsa connessione Restituisce FALSE, if connessione non è una valida risorsa di connessione PostgreSQL.

pg_delete

(PHP 4 >= 4.3.0, PHP 5)

pg_delete --  Cancella le tuple.

Descrizione

mixed pg_delete ( resource connessione, string nometabella, array arrayassoc [, int opzioni] )

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

<?php 
    $db = pg_connect ('dbname=foo');
    // Questo è sicuro, dal momento che $_POST è convertita automaticamente
    $ris = pg_delete($db, 'post_log', $_POST);
    if ($ris) {
       echo "I dati inviati in POST sono stati cancellati: $ris\n";
    }
    else {
        echo "L'utente ha inviato dati sbagliati\n";
    }
?>

Nota: Questa funzione è sperimentale.

Vedere anche pg_convert()

pg_end_copy

(PHP 4 >= 4.0.3, PHP 5)

pg_end_copy -- Esegue una sincronizzazione con il backend PostgreSQL

Descrizione

bool pg_end_copy ( [resource connessione] )

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().

pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_bytea --  Aggiunge le sequenze di escape ai dati binari nel tipo bytea

Descrizione

string pg_escape_bytea ( string dati )

pg_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

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_string --  Aggiunge le sequenze di escape nei tipi text/char

Descrizione

string pg_escape_string ( string dati )

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()

pg_execute

(PHP 5 >= 5.1.0RC1)

pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.

Descrizione

resource pg_execute ( resource connection, string stmtname, array params )

resource pg_execute ( string stmtname, array params )

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.

Elenco dei parametri

connection

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().

stmtname

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.

params

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.

Valori restituiti

A query result resource on success, or FALSE on failure.

Esempi

Esempio 1. Using pg_execute()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

pg_fetch_all_columns

(PHP 5 >= 5.1.0RC1)

pg_fetch_all_columns -- Fetches all rows in a particular result column as an array

Descrizione

array pg_fetch_all_columns ( resource result [, int column] )

pg_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.

Elenco dei parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

column

Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.

Valori restituiti

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.

Esempi

Esempio 1. pg_fetch_all_columns() example

<?php 
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

Vedere anche:

pg_fetch_all()

pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_all -- Carica tutte le tuple in un array

Descrizione

array pg_fetch_all ( resource risultato [, int tupla] )

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

<?php 
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "E' avvenuto un errore.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "E' avvenuto un errore.\n";
    exit;
}

$arr = pg_fetch_all ($result, 0, PGSQL_NUM);

var_dump($arr);

?>

pg_fetch_array

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

pg_fetch_array -- Carica una tupla in un array

Descrizione

array pg_fetch_array ( resource result [, int tupla [, int tipo_risultato]] )

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

<?php 
$conn = pg_pconnect ("dbname=editori");
if (!$conn) {
    echo "Si è verificato un errore.\n";
    exit;
}

$risultato = pg_query ($conn, "SELECT * FROM autori");
if (!$risultato) {
    echo "Si è verificato un errore.\n";
    exit;
}

$arr = pg_fetch_array ($risultato, 0, PGSQL_NUM);
echo $arr[0] . " <- array\n";

$arr = pg_fetch_array ($risultato, 1, PGSQL_ASSOC);
echo $arr["autore"] . " <- array\n";
?>

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

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_assoc -- Fetch a row as an array

Description

array pg_fetch_assoc ( resource result [, int row] )

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

<?php 
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

$arr = pg_fetch_assoc ($result, 1, PGSQL_ASSOC);
echo $arr["author"] . " <- array\n";
?>

pg_fetch_object

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

pg_fetch_object -- Carica una tupla in un oggetto

Descrizione

object pg_fetch_object ( resource result [, int tupla [, int tipo_risultato]] )

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

<?php 
$database = "verlag";
$db_conn = pg_connect ("host=localhost port=5432 dbname=$database");
if (!$db_conn): ?>
    <H1>Failed connecting to postgres database <?php echo $database ?></H1> <?php
    exit;
endif;

$qu = pg_exec ($db_conn, "SELECT * FROM verlag ORDER BY autor");
$row = 0; // postgres needs a row counter other dbs might not 

while ($data = pg_fetch_object ($qu, $row)) {
    echo $data->autor." (";
    echo $data->jahr ."): ";
    echo $data->titel."<BR>";
    $row++;
}
?>
<PRE>
<?php
$fields[] = Array ("autor", "Author");
$fields[] = Array ("jahr",  "  Year");
$fields[] = Array ("titel", " Title");

$row= 0; // postgres needs a row counter other dbs might not
while ($data = pg_fetch_object ($qu, $row)) {
    echo "----------\n";
    reset ($fields);
    while (list (,$item) = each ($fields)):
        echo $item[1].": ".$data->$item[0]."\n";
    endwhile;
    $row++;
}
echo "----------\n"; 
?>
</PRE> 
<?php
pg_freeresult ($qu);
pg_close ($db_conn);
?>

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

(PHP 4 >= 4.2.0, PHP 5)

pg_fetch_result -- Restituisce i valori da una risorsa di risultato

Descrizione

mixed pg_fetch_result ( resource risultato, int tupla, mixed campo )

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

(PHP 3 >= 3.0.1, PHP 4, PHP 5)

pg_fetch_row -- Carica una tupla in un array

Descrizione

array pg_fetch_row ( resource result, int tupla )

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

<?php 
$conn = pg_pconnect ("dbname=editori");
if (!$conn) {
    echo "Si è verificato un errore.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM autori");
if (!$rrisultato) {
    echo "Si è verificato un errore.\n";
    exit;
}

while ($row = pg_fetch_row($risultato, $i)) {
  for ($j=0; $j < count($row); $j++) {
    echo "$row[$j]&nbsp;";
  }

  echo "<BR>";

}
 
?>

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

(PHP 4 >= 4.2.0, PHP 5)

pg_field_is_null -- Verifica se un campo è NULL

Descrizione

int pg_field_is_null ( resource risultato, int tupla, mixed campo )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_field_name -- Restituisce il nome di un campo

Descrizione

string pg_field_name ( resource risultato, int numero_campo )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_field_num -- Restituisce la posizione del campo specificato

Descrizione

int pg_field_num ( resource risultato, string nome_campo )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_field_prtlen -- Restituisce la lunghezza "stampabile" di un valore

Descrizione

int pg_field_prtlen ( resource risultato, int indice_tupla, string nome_campo )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_field_size --  Restituisce la reale dimensione di memorizzazione del campo

Descrizione

int pg_field_size ( resource risultato, int indice_campo )

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().

pg_field_type_oid

(PHP 5 >= 5.1.0RC1)

pg_field_type_oid --  Returns the type ID (OID) for the corresponding field number

Descrizione

int pg_field_type_oid ( resource result, int field_number )

pg_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.

Elenco dei parametri

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Valori restituiti

The OID of the field's base type. FALSE is returned on error.

Esempi

Esempio 1. Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Assume 'title' is a varchar type
  $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

  echo "Title field type OID: ", pg_field_type_oid($res, 0);
?>

Il precedente esempio visualizzerà:

Title field type OID: 1043

pg_field_type

(PHP 4 >= 4.2.0, PHP 5)

pg_field_type --  Restituisce il nome del tipo del campo specificato

Descrizione

string pg_field_type ( resource risultato, int numero_campo )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_free_result -- Libera la memoria allocata per i risultati

Descrizione

bool pg_free_result ( resource risultato )

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

(PHP 4 >= 4.3.0, PHP 5)

pg_get_notify -- Ping database connection

Description

array pg_get_notify ( resource connection [, int result_type] )

pg_get_notify() gets notify message sent by NOTIFY SQL command. To recieve nofigy messages, LISTEN SQL command must be issued. If there is notify message on the connection, array contains message name and backend PID is returned. If there is no message, FALSE is returned.

See also pg_get_pid()

Esempio 1. PostgreSQL NOTIFY message

<?php 
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

// Listen 'author_updated' message from other processes
pq_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify)
    print("No messages\n");
else
    print_r($notify);
?>

pg_get_pid

(PHP 4 >= 4.3.0, PHP 5)

pg_get_pid -- Ping database connection

Description

int pg_get_pid ( resource connection )

pg_get_pid() gets backend (database server process) PID. PID is useful to check if NOTIFY message is sent from other process or not.

See also pg_get_notify()

Esempio 1. PostgreSQL backend PID

<?php 
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

pg_get_result

(PHP 4 >= 4.2.0, PHP 5)

pg_get_result --  Recupera i risultati di una query asincrona

Descrizione

resource pg_get_result ( [resource connessione] )

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

(PHP 3, PHP 4, PHP 5)

pg_host --  Restituisce il nome dell'host associato alla connessione

Descrizione

string pg_host ( resource connessione )

pg_host() restituisce il nome dell'host a cui la risorsa PostgreSQL connessione è connessa.

Vedere anche pg_connect() e pg_pconnect().

pg_insert

(PHP 4 >= 4.3.0, PHP 5)

pg_insert --  Inserisce un array in una tabella.

Descrizione

bool pg_insert ( resource connessione, string nome_tabella, array array_assoc [, int opzioni] )

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.

Esempio 1. pg_insert

<?php 
    $db = pg_connect ('dbname=foo');
    // La riga seguente è sicura, dato che $_POST è convertito automaticamente
    $res = pg_insert($db, 'post_log', $_POST);
    if ($res) {
        echo "dati POST inseriti con successo\n";
    }
    else {
    echo "L'utente deve aver invitao dati sbagliati\n";
    }
?>

Nota: Questa funzione è sperimentale.

Vedere anche pg_convert()

pg_last_error

(PHP 4 >= 4.2.0, PHP 5)

pg_last_error -- Restituisce l'ultimo messaggio d'errore di una connessione

Descrizione

string pg_last_error ( [resource connessione] )

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().

pg_last_notice

(PHP 4 >= 4.0.6, PHP 5)

pg_last_notice --  Restituisce l'ultimo messaggio di notifica dal server PostgreSQL

Descrizione

string pg_last_notice ( resource connessione )

pg_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

(PHP 4 >= 4.2.0, PHP 5)

pg_last_oid -- Restituisce l'oid dell'ultimo oggetto

Descrizione

int pg_last_oid ( resource risultato )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_close -- Chiude un large object

Descrizione

bool pg_lo_close ( resource large_object )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_create -- Crea un large object

Descrizione

int pg_lo_create ( resource connessione )

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().

pg_lo_export

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_export -- Esporta un large object salvandolo su un file

Descrizione

bool pg_lo_export ( int oid, string percorso [, resource connessione] )

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().

pg_lo_import

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_import -- Importa un large object da un file

Descrizione

int pg_lo_import ( [resource connessione, string percorso] )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_open -- Apre un large object

Descrizione

resource pg_lo_open ( resource connessione, int oid, string modo )

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().

pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read_all --  Legge interamente un large object e lo manda direttamente al browser

Descrizione

int pg_lo_read_all ( resource large_object )

pg_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

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read -- Legge un large object

Descrizione

string pg_lo_read ( resource large_object, int lung )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_seek --  Ricerca la posizione di un large object

Descrizione

bool pg_lo_seek ( resource large_object, int offset [, int whence] )

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

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_tell --  Restituisce la posizione attuale in un large object

Descrizione

int pg_lo_tell ( resource large_object )

pg_lo_tell() restituisce la posizione attuale (offset dall'inizio di un large object).

Vedere anche pg_lo_seek().

pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_unlink -- Cancella un large object

Descrizione

bool pg_lo_unlink ( resource connession, int oid )

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().

pg_lo_write

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_write -- Scrive un large object

Descrizione

int pg_lo_write ( resource large_object, string dati )

pg_lo_write() scrive su un large object i dati della variabile dati e restituisce il numero di byte scritti, oppure FALSE in caso di errore. large_object è una risorsa large object ottenuta attraverso pg_lo_open().

Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.

Nota: Questa funzione si chiamava pg_lo_write().

Vedere anche pg_lo_create() e pg_lo_open().

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5)

pg_meta_data --  Ottiene la definizione di una tabella.

Descrizione

array pg_meta_data ( resource connessione, string nome_tabella )

pg_metadata() resituisce la definizione della tabella nome_tabella sotto forma di array. Se avviane un errore, restituisce FALSE

Nota: Questa funzione è sperimentale.

Vedere anche pg_convert()

pg_num_fields

(PHP 4 >= 4.2.0, PHP 5)

pg_num_fields -- Restituisce il numero di campi

Descrizione

int pg_num_fields ( resource risultato )

pg_num_fields() restituisce il numero di campi (colonne) in un risultato PostgreSQL. L'argomento è una risorsa risultato ottenuta mediante pg_query(). Restituisce -1 in caso di errore.

Nota: Questa funzione si chiamava pg_numfields().

Vedere anche pg_num_rows() e pg_affected_rows().

pg_num_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_num_rows -- Restituiscein numero di tuple

Descrizione

int pg_num_rows ( resource risultato )

pg_num_rows() restituisce il numero di tuple (righe) in un risultato PostgreSQL. risultato è una risorsa risultato ottenuta attraverso pg_query(). Restituisce -1 in caso di errore.

Nota: Utilizzare pg_affected_rows() per ottenere il numero di righe modificate da query INSERT, UPDATE and DELETE.

Nota: Questa funzione si chiamava pg_numrows().

Vedere anche pg_num_fields() e pg_affected_rows().

pg_options

(PHP 3, PHP 4, PHP 5)

pg_options -- Estrae le opzioni associate alla connessione

Descrizione

string pg_options ( resource connessione )

pg_options() restituisce una stringa contenente le opzioni specificate alla risorsa PostgreSQL connessione.

pg_parameter_status

(PHP 5)

pg_parameter_status -- Looks up a current parameter setting of the server.

Descrizione

string pg_parameter_status ( resource connection, string param_name )

string pg_parameter_status ( string param_name )

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or FALSE if the parameter is not known.

Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Attenzione

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Elenco dei parametri

connection

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().

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.

Valori restituiti

A string containing the value of the parameter, FALSE on failure or invalid param_name.

Esempi

Esempio 1. pg_parameter_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>

Il precedente esempio visualizzerà:

Server encoding: SQL_ASCII

pg_pconnect

(PHP 3, PHP 4, PHP 5)

pg_pconnect -- Open a persistent PostgreSQL connection

Descrizione

resource pg_pconnect ( string stringa_di_connessione )

pg_pconnect() apre una connessione verso un database PostgreSQL. Restituisce una risorsa di connessione che è necessaria per utilizzare le altre funzioni di PostgreSQL.

Per una descrizione del parametro stringa_di_connessione, vedere pg_connect().

Per abilitare le connessioni persistenti, la direttiva pgsql.allow_persistent php.ini deve essere impostata a"On". (che è il default). Il massimo numero di connessioni persistenti può essere definito con la direttiva pgsql.max_persistent php.ini. (il default è -1 ovvero nessun limite). Il numero totale di connessioni può essere impostato con la direttiva pgsql.max_links php.ini.

pg_close() non chiue le connessioni persistenti create con pg_pconnect().

Vedere anche pg_connect() e la sezione Connessioni Permanenti al Database per ulteriori informazioni.

pg_ping

(PHP 4 >= 4.3.0, PHP 5)

pg_ping -- Ping database connection

Description

array pg_ping ( resource connection )

pg_ping() ping database connection, try to reconnect if it is broken. It returns TRUE if connection is alive, otherwise FALSE.

See also pg_connection_status() and pg_connection_reset().

Esempio 1. PostgreSQL fetch array

<?php 
$conn = pg_pconnect ("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

if (!pg_ping($conn))
    die("Connection is broken\n");
?>

pg_port

(PHP 3, PHP 4, PHP 5)

pg_port --  Restituisce il numero di porta associato alla connessione

Descrizione

int pg_port ( resource connessione )

pg_port() restituisce il numero della porta a cui la risorsa PostgreSQL connessione è collegata.

pg_prepare

(PHP 5 >= 5.1.0RC1)

pg_prepare --  Submits a request to create a prepared statement with the given parameters, and waits for completion.

Descrizione

resource pg_prepare ( resource connection, string stmtname, string query )

resource pg_prepare ( string stmtname, string query )

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.

Elenco dei parametri

connection

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().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Valori restituiti

A query result resource on success, or FALSE on failure.

Esempi

Esempio 1. Using pg_prepare()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

pg_put_line

(PHP 4 >= 4.0.3, PHP 5)

pg_put_line -- Invia una stringa terminata da NULL al backend PostgreSQL

Descrizione

bool pg_put_line ( [resource connessione, string dati] )

pg_put_line() invia una stringa terminata da NULL al backend PostgreSQL. Ciò è utile, per esempio, per l'inserimento ad alta velocità di dati in una tabella, iniziato mediante l'invocazione di una operazione di copia. Il carattere NULL finale è aggiunto automaticamente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: L'applicazione deve explicitamente inviare i due caratteri "\." sull'ultima riga, ad indicare al backend il termine dell'invio dei dati.

Vedere anche pg_end_copy().

Esempio 1. Inserimento ad alta velocità dai dati in una tabella

<?php 
    $conn = pg_pconnect ("dbname=foo");
    pg_query($conn, "create table bar (a int4, b char(16), d float8)");
    pg_query($conn, "copy bar from stdin");
    pg_put_line($conn, "3\thello world\t4.5\n");
    pg_put_line($conn, "4\tgoodbye world\t7.11\n");
    pg_put_line($conn, "\\.\n");
    pg_end_copy($conn);
?>

pg_query_params

(PHP 5 >= 5.1.0RC1)

pg_query_params -- Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

Descrizione

resource pg_query_params ( resource connection, string query, array params )

resource pg_query_params ( string query, array params )

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

Elenco dei parametri

connection

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().

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

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.

Valori restituiti

A query result resource on success, or FALSE on failure.

Esempi

Esempio 1. Using pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets.  Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?>

Vedere anche:

pg_query()

pg_query

(PHP 4 >= 4.2.0, PHP 5)

pg_query -- Esegue una query

Descrizione

resource pg_query ( resource connessione, string query )

pg_query() restituisce un risorsa risultato della query se è stato possibile eseguire quest'ultima. Retituisce FALSE in caso di errore o se la connessione non è valida. I dettagli dell'errore si possono recuperare utilizzando la funzione pg_last_error() se la connessione è valida. pg_last_error() invia un comando SQL al database PostgreSQL specificato dalla risorsa connessione. Il parametro connessione deve essere una connessione valida restituita da pg_connect() o pg_pconnect(). Il valore di ritorno di questa funzione è una risorsa risultato che si può usare per accedere ai dati attraverso altre funzioni PostgreSQL come pg_fetch_array().

Nota: connessione è un parametro opzionale di pg_query(). Se connessione non è impostato, viene utilizzata la connessione di default, ovvero l'ultima connessione effettuata con pg_connect() o pg_pconnect().

Anche se connessione può essere omessa, ciò non è raccomandato, dal momento che questo può essere fonte di errori difficili da trovare nello script.

Nota: Questa funzione si chiamava pg_exec(). pg_exec() è ancora disponibile, per ragioni di compatibilità, ma si consiglia agli utenti di usare il nuovo nome.

Vedere anche pg_connect(), pg_pconnect(), pg_fetch_array(), pg_fetch_object(), pg_num_rows() e pg_affected_rows().

pg_result_error_field

(PHP 5 >= 5.1.0RC1)

pg_result_error_field -- Returns an individual field of an error report.

Descrizione

string pg_result_error_field ( resource result, int fieldcode )

pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode.

Because pg_query() and pg_query_params() return FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

Elenco dei parametri

result

A PostgreSQL query result resource from a previously executed statement.

fieldcode

Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.

Valori restituiti

A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.

Esempi

Esempio 1. pg_result_error_field() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }
  
  $res1 = pg_get_result($dbconn);
  echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>

Vedere anche:

pg_result_error()

pg_result_error

(PHP 4 >= 4.2.0, PHP 5)

pg_result_error --  Restituisce i messaggio di errore associato al risultato

Descrizione

string pg_result_error ( resource risultato )

pg_result_error() restituisce il messaggio di errore associato alla risorsa risultato. Quindi, l'utente ha la possibilità di ottenere un messaggio più preciso rispetto alla pg_last_error().

vedere anche pg_query(), pg_send_query(), pg_get_result(), pg_last_error() e pg_last_notice()

pg_result_seek

(PHP 4 >= 4.3.0, PHP 5)

pg_result_seek -- Set internal row offset in result resource

Description

array pg_result_seek ( resource result, int offset )

pg_result_seek() set internal row offset in reuslt resource. It returns FALSE, if there is error.

See also pg_fetch_row(), pg_fetch_assoc(), pg_fetch_array(), pg_fetch_object() and pg_fetch_result().

pg_result_status

(PHP 4 >= 4.2.0, PHP 5)

pg_result_status --  Recupera lo stato del risultato di una query

Descrizione

int pg_result_status ( resource risultato )

pg_result_status() restituisce lo stato di una risorsa risultato. I valori di ritorno posso essere PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_TO, PGSQL_COPY_FROM, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR e PGSQL_FATAL_ERROR.

Vedere anche pg_connection_status().

pg_select

(PHP 4 >= 4.3.0, PHP 5)

pg_select --  Seleziona delle tuple.

Descrizione

array pg_select ( resource connessione, string nome_tabella, array array_assoc [, int opzioni] )

pg_select() seleziona le tuple specificate da array_assoc che ha la forma campo=>valore. Se la query ha successo, restituisce un array contenente tutte le tuple e i campi che corrispondono alla condizione specificata da array_assoc. Se opzioni è specificato, pg_convert() viene applicata ad array_assoc con le opzioni date.

Esempio 1. pg_select

<?php 
    $db = pg_connect ('dbname=foo');
    // La riga seguente è sicura, dal momento che $_POST viene convertita automaticamente
    $rec = pg_select($db, 'post_log', $_POST);
    if ($rec) {
        echo "Record selezionati\n";
        var_dump($rec);
    }
    else {
        echo "L'utente ha inviato dati errati\n";
    }
?>

Nota: Questa funzione è sperimentale.

Vedere anche pg_convert()

pg_send_execute

(PHP 5 >= 5.1.0RC1)

pg_send_execute -- Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

Descrizione

bool pg_send_execute ( resource connection, string stmtname, array params )

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

Elenco dei parametri

connection

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().

stmtname

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.

params

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.

Valori restituiti

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Esempi

Esempio 1. Using pg_send_execute()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }
  
  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }
  
?>

pg_send_prepare

(PHP 5 >= 5.1.0RC1)

pg_send_prepare -- Sends a request to create a prepared statement with the given parameters, without waiting for completion.

Descrizione

bool pg_send_prepare ( resource connection, string stmtname, string query )

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to dispatch the request, and FALSE if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

Elenco dei parametri

connection

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().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Valori restituiti

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Esempi

Esempio 1. Using pg_send_prepare()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }
  
  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }
  
?>

pg_send_query_params

(PHP 5 >= 5.1.0RC1)

pg_send_query_params -- Submits a command and separate parameters to the server without waiting for the result(s).

Descrizione

bool pg_send_query_params ( resource connection, string query, array params )

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

Elenco dei parametri

connection

PostgreSQL database connection resource.

query

The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

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.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Use pg_get_result() to determine the query result.

Esempi

Esempio 1. Using pg_send_query_params()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Using parameters.  Note that it is not necessary to quote or escape
  // the parameter.
  pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));
  
  // Compare against basic pg_send_query usage
  $str = pg_escape_string('Perth');
  pg_send_query($dbconn, "select count(*) from authors where city = '${str}'");
?>

Vedere anche:

pg_send_query()

pg_send_query

(PHP 4 >= 4.2.0, PHP 5)

pg_send_query --  Invia una query in modo asincrono

Descrizione

bool pg_send_query ( resource connessione, string query )

bool pg_send_query ( string query )

pg_send_query() manda in modo asincrono una query sulla connessione. Diversamente da pg_query(), può inviare più query a PostgreSQL e recuperare i risultati uno ad uno utilizzando pg_get_result(). L'esecuzione dello script non viene interrotta mentre le query sono in esecuzione. Utilizzare pg_connection_busy() per controllare se la connessione è occupata (es. una query è in esecuzione). Le query possono essere cancellate mediante pg_cancel_query().

Anche se è possibile inviare query multiple in un sol colpo, non è possibile inviare query multiple su una connessione occupata. Se la query è inviata mentre la connessione è occupata, la funzione aspetta la fine del processamento di tutti le query in coda, quindi scarta tutti i risultati.

Vedere anche pg_query(), pg_cancel_query(), pg_get_result() e pg_connection_busy()

pg_set_client_encoding

(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)

pg_set_client_encoding --  Imposta la codifica del client

Descrizione

int pg_set_client_encoding ( [resource connessione, string codifica] )

pg_set_client_encoding() imposta la codifica del client e restituisce 0 in caso di successo, -1 in caso di errore.

codifica è la codifica del client e 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. Le codifiche disponibili dipendono dalle versionidi PostgreSQL e di libpq. Consultare il manuale di PostgreSQL per conoscere le cidifiche accettate dala propria installazione di PostgreSQL.

Nota: Questa funzione richiede PHP-4.0.3 o successiv e PostgreSQL-7.0 o successivi. Le codifiche accettate dipendono dalla versione di PostgreSQL. Consultare il manuale di PostgreSQL per ulteriori dettagli.

Questa funzione si chiamava pg_setclientencoding().

Vedere anche pg_client_encoding().

pg_set_error_verbosity

(PHP 5 >= 5.1.0RC1)

pg_set_error_verbosity --  Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

Descrizione

int pg_set_error_verbosity ( resource connection, int verbosity )

int pg_set_error_verbosity ( int verbosity )

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

Elenco dei parametri

connection

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().

verbosity

The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Valori restituiti

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Esempi

Esempio 1. pg_set_error_verbosity() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }
  
  pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?>

pg_trace

(PHP 4 >= 4.0.1, PHP 5)

pg_trace -- iAbilita il tracciamento di una connessione PostgreSQL

Descrizione

bool pg_trace ( string percorsofile [, string modo [, resource connessione]] )

pg_trace() abilita il tracciamento di una comunicazione frontend/backend PostgreSQL verso un file di debug specificato da percorsofile. Per riuscire a capire i risultati, occorre conoscere bene i dettagli del protocollo di comunicazione di PostgreSQL. Per chi non ne è a conoscenza, può sempre essere utile per tracciare gli errori nelle query mandate al server; ad esempio si può eseguire grep '^To backend' trace.log e vedere quale query è stata realmente inviata al server PostgreSQL. Per ulteriori informazioni, consultare il manuale di PostgreSQL.

percorsofile e modo sono gli stessi parametri di fopen() (mode ha come default 'w'), connession specifica la connessione da tracciare ed ha come default l'ultima aperta.

pg_trace() rRestituisce TRUE se percorsofile è stato apertoo in scrittura per il log, altrimenti FALSE.

Vedere anche:

fopen()
pg_untrace()

pg_transaction_status

(PHP 5 >= 5.1.0RC1)

pg_transaction_status -- Returns the current in-transaction status of the server.

Descrizione

int pg_transaction_status ( resource connection )

Returns the current in-transaction status of the server.

Attenzione

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

Elenco dei parametri

connection

PostgreSQL database connection resource.

Valori restituiti

The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.

Esempi

Esempio 1. pg_transaction_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_transaction_status($dbconn);
  if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
      echo 'Connection is bad';
  } else if ($stat === PGSQL_TRANSACTION_IDLE) {
      echo 'Connection is currently idle';
  } else {
      echo 'Connection is in a transaction state';
  }    
?>

pg_tty

(PHP 3, PHP 4, PHP 5)

pg_tty --  Restituisce il nome della tty associata alla connessione

Descrizione

string pg_tty ( resource connessione )

pg_tty() restituisce il noe della tty a cui viene mandato l'output del debug del server sulla risorsa connessione specificata.

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5)

pg_unescape_bytea --  Escape binary for bytea type

Description

string pg_unescape_bytea ( string data )

pg_unescape_bytea() unescapes string from bytea datatype. It returns unescaped string (binary).

Nota: When you SELECT bytea type, PostgreSQL returns octal byte value prefixed by \ (e.g. \032). Users are supposed to convert back to binary format by yourself.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea type must be casted when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need cast. Exception is when client and backend character encoding does not match, there may be multi-byte stream error. User must cast to bytea to avoid this error.

See also pg_escape_bytea() and pg_escape_string()

pg_untrace

(PHP 4 >= 4.0.1, PHP 5)

pg_untrace -- Disabilita il tracciamento di una connessione PostgreSQL

Descrizione

bool pg_untrace ( [resource connessione] )

Termina il tracciamento cominciato con pg_trace(). connessione specifica la connessione tracciata ed ha come default l'ultima connessione aperta.

Restituisce sempre TRUE.

Vedere anche pg_trace().

pg_update

(PHP 4 >= 4.3.0, PHP 5)

pg_update --  Modifica le tuple della tabella

Descrizione

mixed pg_update ( resource connessione, string nome_tabella, array dati, array condizione [, int opzioni] )

pg_update() aggiorna le tuple che corrispondono a condizione con dati. Se opzioni è specificato, pg_convert() viene applicata su dati con le opzioni date.

Esempio 1. pg_update

<?php 
    $db = pg_connect ('dbname=foo');
    $data = array('field1'=>'AA', 'field2'=>'BB');
    // La riga seguente è sicura, date che $_POST è convertito automaticamente
    $res = pg_update($db, 'post_log', $_POST, $data);
    if ($res) {
        echo "Dati aggiornati: $res\n";
    }
    else {
        echo "L'utente ha inviato dati errati\n";
    }
?>

Nota: Questa funzione è sperimentale.

Vedere anche pg_convert()

pg_version

(PHP 5)

pg_version --  Returns an array with client, protocol and server version (when available)

Descrizione

array pg_version ( [resource connection] )

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only avaliable if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

Elenco dei parametri

connection

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().

Valori restituiti

Returns an array with client, protocol and server_version keys and values (if available). Returns FALSE on error or invalid connection.

Esempi

Esempio 1. pg_version() example

<?php
  $dbconn = pg_connect("host=localhost port=5432 dbname=mary")
     or die("Could not connect");
     
  $v = pg_version($dbconn);
  
  echo $v['client'];
?>

Il precedente esempio visualizzerà:

7.4

Vedere anche:

pg_parameter_status()

CXV. PostgreSQL Functions (PDO_PGSQL)

Introduzione

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

Sommario
PDO_PGSQL DSN -- Connecting to PostgreSQL databases

PDO_PGSQL DSN

(no version information, might be only in CVS)

PDO_PGSQL DSN -- Connecting to PostgreSQL databases

Descrizione

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces:

DSN prefix

The DSN prefix is pgsql:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

user

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.

password

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.

Esempi

Esempio 1. PDO_PGSQL DSN examples

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database:
pgsql:host=localhost port=5432 dbname=testdb user=bruce password=mypass

CXVI. Funzioni per le Stampanti

Introduzione

Queste funzioni sono disponibili solo nei sistemi Windows 9.x, ME, NT4 e 2000. Sono state aggiunte in PHP 4.0.4.


Installazione

Questo modulo PECL non viene incluso nel rilascio di PHP.

Per potere utilizzare queste funzioni, gli utenti Windows dovranno abilitare php_printer.dll nel php.ini. You may obtain this unbundled PECL extension from the various PECL snaps pages (select the appropriate repository for your version of PHP): PECL for PHP 4.3.x, PECL for PHP 5.0.x or PECL Unstable.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione per il modulo stampante

NomeDefaultModificabileVariazioni
printer.default_printer""PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Sommario
printer_abort -- Cancella il file di spool dalla stampante
printer_close -- Chiude una connessione aperta verso una stampante
printer_create_brush -- Crea un nuovo pennello
printer_create_dc -- Crea un nuovo device context
printer_create_font -- Crea un nuovo font
printer_create_pen -- Crea una nuova penna
printer_delete_brush -- Cancella un pennello
printer_delete_dc -- Cancella un device context
printer_delete_font -- Cancella un font
printer_delete_pen -- Cancella una penna
printer_draw_bmp -- Disegna una bitmap
printer_draw_chord -- Traccia una corda
printer_draw_elipse -- Traccia una ellisse
printer_draw_line -- Traccia una linea
printer_draw_pie -- Traccia una grafico a torta
printer_draw_rectangle -- Traccia un rettangolo
printer_draw_roundrect -- Traccia un rettangolo con gli angoli arrotondati
printer_draw_text -- Scrive un testo
printer_end_doc -- Chiude il documento
printer_end_page -- Chiude la pagina attiva
printer_get_option -- Recupera la configurazione della stampante
printer_list -- Restituisce un elenco delle stampanti collegate al server
printer_logical_fontheight -- Restituisce l'altezza logica del font
printer_open -- Apre la connessione ad una stampante
printer_select_brush -- Seleziona un pennello
printer_select_font -- Seleziona un font
printer_select_pen -- Seleziona una penna
printer_set_option -- Configura la connessione con la stampante
printer_start_doc -- Inizia un nuovo documento
printer_start_page -- Inizia una nuova pagina
printer_write -- Scrive dei dati sulla stampante

printer_abort

(PECL)

printer_abort -- Cancella il file di spool dalla stampante

Descrizione

void printer_abort ( resource handle )

La funzione cancella lo spool di stampa dalla stampante.

Il parametro handle deve indicare un handle valido di stampante.

Esempio 1. Esempio di utilizzo di printer_abort()

<?php
$handle = printer_open();
printer_abort($handle);
printer_close($handle);
?>

printer_close

(PECL)

printer_close -- Chiude una connessione aperta verso una stampante

Descrizione

void printer_close ( resource handle )

Questa funzione chiude la connessione verso una stampante. Inoltre, la funzione printer_close() chiude il device context attivo.

Il parametro handle deve indicare un handle valido di stampante.

Esempio 1. Esempio di utilizzo di printer_close()

<?php
$handle = printer_open();
printer_close($handle);
?>

printer_create_brush

(PECL)

printer_create_brush -- Crea un nuovo pennello

Descrizione

mixed printer_create_brush ( int stile, string colore )

La funzione crea un nuovo pennello e restituisce un handle per questo. Il pennello viene usato per riempire le forme. Per un esempio vedere printer_select_brush(). Il parametro colore deve essere un colore in formato esadecimale RGB, ad esempio "000000" per il nero, stile, invece, deve essere valorizzato con una delle seguenti costanti:

  • PRINTER_BRUSH_SOLID: crea un pennello con un colore pieno.

  • PRINTER_BRUSH_DIAGONAL: crea un pennello con righe a 45 gradi dal basso a sinistra verso l'alto a destra ( / ).

  • PRINTER_BRUSH_CROSS: crea un pennello con delle croci ( + ).

  • PRINTER_BRUSH_DIAGCROSS: crea un pennello con croci a 45 gradi ( x ).

  • PRINTER_BRUSH_FDIAGONAL: crea un pennello con righe a 45 gradi dall'alto a sinistra verso il basso a destra ( \ ).

  • PRINTER_BRUSH_HORIZONTAL: crea un pennello a righe orizzontali ( - ).

  • PRINTER_BRUSH_VERTICAL: crea un pennello a righe verticali ( | ).

  • PRINTER_BRUSH_CUSTOM: crea un pennello personalizzato a partire da un file BMP. Il secondo parametro viene usato per indicare il file BMP anzichè il codice RGB del colore.

printer_create_dc

(PECL)

printer_create_dc -- Crea un nuovo device context

Descrizione

void printer_create_dc ( resource handle )

La funzione crea un nuovo device context. Il device context è utilizzato per personalizzare gli oggetti grafici del documento. Il parametro handle deve indicare un handle valido di stampante.

Esempio 1. Esempio di utilizzo di printer_create_dc()

<?php
$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* esegue qualche operazione sul device context */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* crea un'altro device context */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* ci esegue delle operazioni */

printer_delete_dc($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_create_font

(PECL)

printer_create_font -- Crea un nuovo font

Descrizione

mixed printer_create_font ( string tipo, int altezza, int larghezza, int spessore, bool corsivo, bool sottolineato, bool barrato, int orientamento )

La funzione crea un nuovo font e restituisce il relativo handle. Il font è utilizzato per scrivere testi. Per un esempio vedere printer_select_font(). Il parametro tipo è una stringa indicante il tipo di font. Altezza indica l'altezza del font e larghezza ne indica la larghezza. Il parametro spessore indica lo spessore del font (il valore normale è 400), e può essere una delle seguente costanti predefinite:

  • PRINTER_FW_THIN: imposta un font sottile (100).

  • PRINTER_FW_ULTRALIGHT: imposta un font molto leggero (200).

  • PRINTER_FW_LIGHT: imposta un font leggero (300).

  • PRINTER_FW_NORMAL: imposta un font normale (400).

  • PRINTER_FW_MEDIUM: imposta un font medio (500).

  • PRINTER_FW_BOLD: imposta il font a grassetto (700).

  • PRINTER_FW_ULTRABOLD: imposta il font ad un grassetto maggiore (800).

  • PRINTER_FW_HEAVY: imposta un font grosso (900).

Il parametro corsivo può essere TRUE o FALSE, ed indica se il font debba essere corsivo.

Il parametro sottolineato può essere TRUE o FALSE, e indica se il font debba essere sottolineato.

Il parametro barrato può essere TRUE o FALSE, e indica se il font debba essere barrato.

Il parametro orientamento specifica la rotazione. Per un esempio vedere printer_select_font().

printer_create_pen

(PECL)

printer_create_pen -- Crea una nuova penna

Descrizione

mixed printer_create_pen ( int stile, int larghezza, string colore )

La funzione crea una nuova penna e restituisce il relativo handle. Una penna viene usata per tracciare linee e curve. Per un esempio vedere printer_select_pen(). Il parametro colore deve essere un colore in formato esadecimale RGB, ad esempio "000000" per nero, larghezza specifica la larghezza della penna, mentre stile deve essere una delle seguenti costanti:

  • PRINTER_PEN_SOLID: crea una penna continua.

  • PRINTER_PEN_DASH: crea una penna tratteggiata.

  • PRINTER_PEN_DOT: crea una penna a punti.

  • PRINTER_PEN_DASHDOT: crea una penna con tratto e punto.

  • PRINTER_PEN_DASHDOTDOT: crea una penna con tratto e due punti.

  • PRINTER_PEN_INVISIBLE: crea una penna invisibile.

printer_delete_brush

(PECL)

printer_delete_brush -- Cancella un pennello

Descrizione

bool printer_delete_brush ( resource handle )

La funzione cancella il pennello selezionato. Per un esempio vedere printer_select_brush(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Il parametro handle deve essere un handle valido di un pennello.

printer_delete_dc

(PECL)

printer_delete_dc -- Cancella un device context

Descrizione

bool printer_delete_dc ( resource handle )

Questa funzione cancella il device context. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Per un esempio vedere printer_create_dc(). Il parametro handle deve essere un handle valido di stampante.

printer_delete_font

(PECL)

printer_delete_font -- Cancella un font

Descrizione

bool printer_delete_font ( resource handle )

La funzione cancella il font prescelto. Per un esempio vedere printer_select_font(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Il parametro handle deve essere un handle valido di un font.

printer_delete_pen

(PECL)

printer_delete_pen -- Cancella una penna

Descrizione

bool printer_delete_pen ( resource handle )

La funzione cancella la penna prescelta. Per un esempio vedere printer_select_pen().Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Il parametro handle deve essere un handle valido di una penna.

printer_draw_bmp

(PECL)

printer_draw_bmp -- Disegna una bitmap

Descrizione

void printer_draw_bmp ( resource handle, string nomefile, int x, int y [, int width, int height] )

La funzione disegna la bitmap nomefile alla posizione x, y. Il parametro handle deve essere un handle valido di una stampante.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. Esempio di utilizzo di printer_draw_bmp()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_chord

(PECL)

printer_draw_chord -- Traccia una corda

Descrizione

void printer_draw_chord ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad_x, int rad_y, int rad_x1, int rad_y1 )

La funzione disegna una corda. Il parametro handle deve esesre un handle valido di stampante.

rec_x indica la coordinata x dell'angolo in alto a sinistra del rettangolo perimetrale.

rec_y indica la coordinata y dell'angolo in alto a sinistra del rettangolo perimetrale.

rec_x1 indica la coordinata x dell'angolo in basso a destra del rettangolo perimetrale.

rec_y1 indica la coordinata y dell'angolo in basso a destra del rettangolo perimetrale.

rad_x indica la coordinata x del radiale indicante l'inizio della corda.

rad_y indica la coordinata y del radiale indicante l'inizio della corda.

rad_x1 indica la coordinata x del radiale indicante la fine della corda.

rad_y1 indica la coordinata y del radiale indicante la fine della corda.

Esempio 1. Esempio di utilizzo di printer_draw_chord()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);   
?>

printer_draw_elipse

(PECL)

printer_draw_elipse -- Traccia una ellisse

Descrizione

void printer_draw_elipse ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y )

La funzione disegna una ellisse. Il parametro handle deve esesre un handle valido di stampante.

ul_x indica la coordinata x in alto a sinistra dell'ellisse.

ul_y indica la coordinata y in alto a sinistra dell'ellisse.

lr_x indica la coordinata x in basso a destra dell'ellisse.

lr_y indica la coordinata y in basso a destra dell'ellisse.

Esempio 1. Esempio di utilizzo di printer_draw_elipse()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_elipse($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);   
?>

printer_draw_line

(PECL)

printer_draw_line -- Traccia una linea

Description

void printer_draw_line ( resource printer_handle, int from_x, int from_y, int to_x, int to_y )

Questa funzione disegna una linea dalla posizione from_x, from_y alla posizione to_x, to_y usando la penna selezionata. Il parametro handle deve essere un handle valido di stampante.

Esempio 1. Esempio di utilizzo di printer_draw_line()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);
printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_pie

(PECL)

printer_draw_pie -- Traccia una grafico a torta

Descrizione

void printer_draw_pie ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad1_x, int rad1_y, int rad2_x, int rad2_y )

La funzione traccia un grafico a torta. Il parametro handle deve indicare un handle valido di stampante.

rec_x indica la coordinata x dell'angolo in alto a sinistra del rettangolo perimetrale.

rec_y indica la coordinata y dell'angolo in alto a sinistra del rettangolo perimetrale.

rec_x1 indica la coordinata x dell'angolo in basso a destra del rettangolo perimetrale.

rec_y1 indica la coordinata y dell'angolo in basso a destra del rettangolo perimetrale.

rad1_x indica la coordinata x del punto finale del primo raggio.

rad1_y indica la coordinata y del punto finale del primo raggio.

rad2_x indica la coordinata x del punto finale del secondo raggio.

rad2_y indica la coordinata y del punto finale del secondo raggio.

Esempio 1. Esempio di utilizzo di printer_draw_pie()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle); 
?>

printer_draw_rectangle

(PECL)

printer_draw_rectangle -- Traccia un rettangolo

Descrizione

void printer_draw_rectangle ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y )

La funzione disegna un rettangolo.

Il parametro handle deve indicare un handle valido di stampante.

ul_x indica la coordinata x dell'angolo in alto a sinistra del rettangolo.

ul_y indica la coordinata y dell'angolo in alto a sinistra del rettangolo.

lr_x indica la coordinata x dell'angolo in basso a destra del rettangolo.

lr_y indica la coordinata y dell'angolo in basso a destra del rettangolo.

Esempio 1. Esempio di utilizzo di printer_draw_rectangle()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_roundrect

(PECL)

printer_draw_roundrect -- Traccia un rettangolo con gli angoli arrotondati

Descrizione

void printer_draw_roundrect ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y, int width, int height )

La funzione traccia un rettangolo con gli angoli arrotondati.

Il parametro handle deve indicare un handle valido di stampante.

ul_x indica la coordinata x dell'angolo in alto a sinistra del rettangolo.

ul_y indica la coordinata y dell'angolo in alto a sinistra del rettangolo.

lr_x indica la coordinata x dell'angolo in basso a destra del rettangolo.

lr_y indica la coordinata y dell'angolo in basso a destra del rettangolo.

width indica la larghezza dell'ellisse.

height indica l'altezza dell'ellisse.

Esempio 1. Esempio di utilizzo di printer_draw_roundrect()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_text

(PECL)

printer_draw_text -- Scrive un testo

Descrizione

void printer_draw_text ( resource printer_handle, string testo, int x, int y )

La funzione scrive il testo alla posizione x, y utilizzando il font selezionato. Il parametro printer_handle deve indicare un handle valido di stampante.

Esempio 1. Esempio di utilizzo di printer_draw_text()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);
$font = printer_create_font("Arial", 72, 48, 400, false, false, false ,0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_end_doc

(PECL)

printer_end_doc -- Chiude il documento

Descrizione

bool printer_end_doc ( resource handle )

Chiude il nuovo documento creato nello spooler della stampante. Ora il documento è pronto per essere stampato. Per un esempio vedere printer_start_doc(). Il parametro handle deve indicare un handle valido di stampante.

printer_end_page

(PECL)

printer_end_page -- Chiude la pagina attiva

Descrizione

bool printer_end_page ( resource handle )

La funzione chiude la pagina attiva del documento corrente. Per un esempio vedere printer_start_doc(). Il parametro handle deve indicare un handle valido di stampante.

printer_get_option

(PECL)

printer_get_option -- Recupera la configurazione della stampante

Descrizione

mixed printer_get_option ( resource handle, string opzione )

La funzione recupera il valore di configurazione per il parametro opzione. Il parametro handle deve indicare un handle valido di stampante. Vedere la funzione printer_set_option() per avere l'elenco dei parametri che sono disponibili; in aggiunta possono essere recuperate le informazioni sui parametri:

  • PRINTER_DEVICENAME restituisce il nome della device della stampante.

  • PRINTER_DRIVERVERSION restituisce la versione del driver della stampante.

Esempio 1. Esempio di utilizzo di printer_get_option()

<?php
$handle = printer_open();
echo printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);
?>

printer_list

(PECL)

printer_list -- Restituisce un elenco delle stampanti collegate al server

Descrizione

array printer_list ( int enumtype [, string nome [, int livello]] )

La funzione elenca le stampanti disponibili e le loro capacità. Il parametro livello indica il livello delle informazioni richieste. I livelli possono essere 1,2,4 o 5. Il parametro enumtype deve essere valorizzato con una delle seguenti costanti:

  • PRINTER_ENUM_LOCAL: elenca le stampanti installate localmente.

  • PRINTER_ENUM_NAME: elenca le stampanti installate su nome, che può indicare un server, un dominio, un printer server.

  • PRINTER_ENUM_SHARED: questo parametro non può essere utilizzato da solo, è necessario aggiungerlo in OR ad uno degli altri, ad esempio PRINTER_ENUM_LOCAL per rilevare le stampanti locali condivise.

  • PRINTER_ENUM_DEFAULT: (solo Win9.x) elenca la stampante di default.

  • PRINTER_ENUM_CONNECTIONS: (solo WinNT/2000) elenca le stampanti che l'utente può utilizzare.

  • PRINTER_ENUM_NETWORK: (solo WinNT/2000) elenca le stampanti presenti nel dominio del computer. Opzione valida solo se livello è valorizzato a 1.

  • PRINTER_ENUM_REMOTE: (solo WinNT/2000) elenca le stampanti di rete ed i printer server presenti nel dominio del computer. Opzione valida solo se livello è valorizzato a 1.

Esempio 1. Esempio di utilizzo di printer_list()

<?php
/* rileva le stampanti locali condivise */
var_dump(printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED) );
?>

printer_logical_fontheight

(PECL)

printer_logical_fontheight -- Restituisce l'altezza logica del font

Descrizione

int printer_logical_fontheight ( resource handle, int altezza )

La funzione calcola l'altezza logica del font per il parametro altezza. Il parametro handle deve indicare un handle valido di stampante.

Esempio 1. Esempio di utilizzo di printer_logical_fontheight()

<?php
$handle = printer_open();
echo printer_logical_fontheight($handle, 72);
printer_close($handle);
?>

printer_open

(PECL)

printer_open -- Apre la connessione ad una stampante

Descrizione

mixed printer_open ( [string NomePeriferica] )

Questa funzione tenta di aprire una connessione con la stampante NomePeriferica, e restituisce un handle se ha successo oppure FALSE se fallisce.

Se non vengono passati parametri, la funzione tenta di aprire una connessione con la stampante di default (se non viene specificata in php.ini come printer.default_printer, il PHP tenta di determinarla).

Inoltre printer_open() attiva un device context.

Esempio 1. Esempio di utilizzo di printer_open()

<?php
$handle = printer_open("HP Deskjet 930c");
$handle = printer_open();
?>

printer_select_brush

(PECL)

printer_select_brush -- Seleziona un pennello

Descrizione

void printer_select_brush ( resource printer_handle, resource brush_handle )

La funzione seleziona un pennello come oggetto attivo per il disegno nel device context corrente. Un pennello viene utilizzato per riempire le figure. Se si disegna un rettangolo il pennello viene utilizzato per disegnarne la forma, mentre si utilizza la penna per tracciarne i contorni. Se non si seleziona alcun pennello prima di disegnare delle figure, queste non saranno riempite. Il parametro printer_handle deve indicare un handle valido di stampante. Il parametro brush_handle deve indicare un handle valido di pennello.

Esempio 1. Esempio di utilizzo di printer_select_brush()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1, 1, 500, 500);
printer_delete_brush($brush);
$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1, 501, 500, 1001);
printer_delete_brush($brush);
printer_delete_pen($pen);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_select_font

(PECL)

printer_select_font -- Seleziona un font

Descrizione

void printer_select_font ( resource printer_handle, resource font_handle )

La funzione seleziona un font con cui scrivere testi. Il parametro printer_handle deve indicare un handle valido di stampante. Il parametro font_handle deve indicare un handle valido di font.

Esempio 1. Esempio di utilizzo di printer_select_font()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_select_pen

(PECL)

printer_select_pen -- Seleziona una penna

Descrizione

void printer_select_pen ( resource printer_handle, resource pen_handle )

La funzione seleziona una penna come oggetto attivo di disegno per il device context corrente. Si utilizza una per penna per tracciare linee e curve. Ad esempio se si deve tracciare un linea singola si usa una penna. Se si disegna un rettangolo, si utilizza la penna per tracciare i bordi, mentre con il pennello si riempie l'interno. Se non si seleziona una penna prima di tracciare delle figure, queste non avranno i bordi. Il parametro printer_handle deve indicare un handle valido di stampante. Il parametro pen_handle deve indicare un handle valido di penna.

Esempio 1. Esempio di utilizzo di printer_select_pen()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_set_option

(PECL)

printer_set_option -- Configura la connessione con la stampante

Descrizione

bool printer_set_option ( resource handle, int opzione, mixed valore )

La funzione valorizza le seguenti opzioni per la connessione corrente. Il parametro handle deve indicare un handle valido di stampante. Per il parametro opzione si può utilizzare una delle seguenti costanti:

  • PRINTER_COPIES: indica quante copie si debbano stampare, valore deve essere un intero.

  • PRINTER_MODE: specifica il tipo di dati (text, raw or emf), valore deve essere una stringa.

  • PRINTER_TITLE: specifica il nome del documento, valore deve essere una stringa.

  • PRINTER_ORIENTATION: specifica l'orientamento del foglio, valore può essere o PRINTER_ORIENTATION_PORTRAIT o PRINTER_ORIENTATION_LANDSCAPE

  • PRINTER_RESOLUTION_Y: specifica la risoluzione y in DPI, valore deve essere un intero.

  • PRINTER_RESOLUTION_X: specifica la risoluzione x in DPI, valore deve essere un intero.

  • PRINTER_PAPER_FORMAT: specifica il formato predefinito della carta, impostare valore a PRINTER_FORMAT_CUSTOM se si vuole impostare un formato personalizzato con PRINTER_PAPER_WIDTH e PRINTER_PAPER_LENGTH. Il parametro valore può essere una delle seguenti costanti.

    • PRINTER_FORMAT_CUSTOM: specifica un formato personalizzato.

    • PRINTER_FORMAT_LETTER: specifica il formato letter (8 1/2- per 11-pollici).

    • PRINTER_FORMAT_LETTER: specifica il formato legal (8 1/2- per 14-pollici).

    • PRINTER_FORMAT_A3: specifica il formato A3 (297- per 420-millimetri).

    • PRINTER_FORMAT_A4: specifica il formato A4 (210- per 297-millimetri).

    • PRINTER_FORMAT_A5: specifica il formato A5 (148- per 210-millimetri).

    • PRINTER_FORMAT_B4: specifica il formato B4 (250- per 354-millimetri).

    • PRINTER_FORMAT_B5: specifica il formato B5 (182- per 257-millimetri).

    • PRINTER_FORMAT_FOLIO: specifica il formato FOLIO (8 1/2- per 13-pollici).

  • PRINTER_PAPER_LENGTH: se PRINTER_PAPER_FORMAT è impostato a PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifica la lunghezza personalizzata in mm, valore deve essere un intero.

  • PRINTER_PAPER_WIDTH: se PRINTER_PAPER_FORMAT è impostato a PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifica la larghezza personalizzata in mm, valore deve essere un intero.

  • PRINTER_SCALE: specifica il fattore per il quale l'output della stampante deve essere dimensionato. La dimensione dalle pagine viene modificata dalla dimensione fisica di un fattore pari a scala/100. Ad esempio se simposta scala a 50, l'output sarà la metà della dimensione originale. Valore deve essere un intero.

  • PRINTER_BACKGROUND_COLOR: specifica il colore di background per il device context corrente, valore deve essere una stringa contenente il colore in formato RGB esadecimale, ad esempio "005533".

  • PRINTER_TEXT_COLOR: specifica il colore del testo per il device context corrente, valore deve essere una stringa contenente il colore in formato RGB esadecimale, ad esempio "005533".

  • PRINTER_TEXT_ALIGN: specifica l'allineamento del testo per il device context corrente, valore può essere la combinazione tramite OR delle seguenti costanti:

    • PRINTER_TA_BASELINE: il testo sarà allineato alla linea base.

    • PRINTER_TA_BOTTOM: il testo sarà allineato in basso.

    • PRINTER_TA_TOP: il testo sarà allineato in alto.

    • PRINTER_TA_CENTER: il testo sarà centrato.

    • PRINTER_TA_LEFT: il testo sarà allineato a sinistra.

    • PRINTER_TA_RIGHT: il testo sarà allineato a destra.

Esempio 1. Esempio di utilizzo di printer_set_option()

<?php
$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);
?>

printer_start_doc

(PECL)

printer_start_doc -- Inizia un nuovo documento

Descrizione

bool printer_start_doc ( resource handle [, string documento] )

La funzione crea un nuovo documento nello spooler della stampante. Il documento può contenere diverse pagine, la funzione è utilizzata per inserire un job di stampa nello spooler. Il parametro handle deve essere un handle valido di una stampante. Il parametro opzionale documento può esesre usato per indicare un nome alternativo al documento.

Esempio 1. Esempio di utilizzo di printer_start_doc()

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_start_page

(PECL)

printer_start_page -- Inizia una nuova pagina

Descrizione

bool printer_start_page ( resource handle )

La funzione crea una nuova pagina nel documento attivo. Per un esempio vedere printer_start_doc(). Il parametro handle deve essere un handle valido di stampante.

printer_write

(PECL)

printer_write -- Scrive dei dati sulla stampante

Descrizione

bool printer_write ( resource handle, string contenuto )

La funzione scrive contenuto direttamente alla stampante. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Il parametro handle deve essere un handle valido di una stampante.

Esempio 1. Esempio di utilizzo di printer_write()

<?php
$handle = printer_open();
printer_write($handle, "Testo da scrivere");
printer_close($handle);
?>

CXVII. Funzioni per l'esecuzione di programmi

Introduzione

Queste funzioni permettono l'esecuzione di comandi sul sistema stesso, e rendono sicuri tali comandi.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Vedere anche:

Queste funzioni sono anche strettamente correlate al operatore backtick. Inoltre, in modalità sicura occorre tenere conto anche della direttiva safe_mode_exec_dir.

Sommario
escapeshellarg -- estrae una stringa da usare come un argomento della shell
escapeshellcmd -- Elude i metacaratteri della shell
exec -- Esegue un programma esterno
passthru -- Esegue un programma esterno e mostra l'output non elaborato
proc_close -- Close a process opened by proc_open() and return the exit code of that process.
proc_get_status -- Get information about a process opened by proc_open()
proc_nice -- Change the priority of the current process
proc_open --  Execute a command and open file pointers for input/output
proc_terminate -- kills a process opened by proc_open
shell_exec -- Esegue un comando attraverso la shell e restituisce l'output completo come stringa
system -- Esegue un programma esterno e mostra l'output

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5)

escapeshellarg -- estrae una stringa da usare come un argomento della shell

Descrizione

string escapeshellarg ( string arg )

escapeshellarg() aggiunge le virgolette singole attorno ad una stringa ed elude ogni virgoletta semplice per permetterti di passare una stringa direttamente ad una funzione della shell a che questa venga trattata come un singolo argomento. Questa funzione dovrebbe essere usata per eludere argomenti individuali per funzioni della shell che giungano dall'input del utente. Le funzioni della shell includono exec(), system() e l'operatore backtick. Un utilizzo standard sarebbe:

<?php
system('ls '.escapeshellarg($dir));

Vedere anche escapeshellcmd(), exec(), popen(), system() e l'operatore backtick.

escapeshellcmd

(PHP 3, PHP 4, PHP 5)

escapeshellcmd -- Elude i metacaratteri della shell

Descrizione

string escapeshellcmd ( string command )

escapeshellcmd() elude ogni carattere di una stringa che potrebbe essere usata per indurre un comando shell ad eseguire comandi arbitrari. Questa funzione dovrebbe essere usata per assicurarsi che ogni dato che giunga dall'input dell'utente venga neutralizzato prima di essere passato a funzioni come exec() o system() o all'operatore backtick . Un modello d'utilizzo potrebbe essere:

<?php
$e = escapeshellcmd($userinput);

// qui non ci preoccupiamo se $e contiene spazi
system("echo $e");
$f = escapeshellcmd($filename);
// e qui lo facciamo, usando le virgolette
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); 
?>

Vedere anche escapeshellarg(), exec(), popen(), system() e l'operatore backtick.

exec

(PHP 3, PHP 4, PHP 5)

exec -- Esegue un programma esterno

Descrizione

string exec ( string command [, array &output [, int &return_var]] )

exec() esegue il comando passato da command, la funzione non invia nessun output. Restituisce semplicemente l'ultima linea dal risultato del comando. Se si ha bisogno di eseguire un comando ed avere tutti i dati passati direttamente indietro senza alcuna interferenza, usare la funzione passthru().

Se l'argomento output è presente, allora tale vettore specificato verrà riempito con ogni linea del output del comando. I fine riga, come \nnon sono inclusi in questo array. Notare che se il vettore contiene già degli elementi, exec() li aggiungerà in coda al vettore. Se non si vuole che la funzione aggiunga elementi, eseguire un unset() sul vettore prima di passarlo ad exec().

Se viene passato l'argomento return_var assieme all'argomento output, allora lo stato del comando eseguito verrà scritto in questa variabile.

Esempio 1. Un exec() example

<?php
 // restituisce la username del proprietario del processo php/httpd attivo
 // (su um sistema con l'eseguibile "whoami" nel path)
 echo exec('whoami');
 ?>

Avvertimento

Se si permette di passare a questa funzione i dati provenineti dagli input utente, si dovrebbe utilizzare la funzione escapeshellarg() oppure escapeshellcmd() in modo da essere sicuri che gli utenti non possano compromettere il sistema eseguendo comandi arbitrari.

Nota: Se si vuole avviare un programma tramite questa funzione e lasciarlo girare in background, occorre essere certi che l output del programma sia rediretto su un file o qualche altro flusso di output altrimenti il PHP sarà sospenderà fino a quando il programma non termina.

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 system(), passthru(), popen(), escapeshellcmd() pcntl_exec() e l'operatore backtick.

passthru

(PHP 3, PHP 4, PHP 5)

passthru -- Esegue un programma esterno e mostra l'output non elaborato

Descrizione

void passthru ( string command [, int &return_var] )

La funzione passthru() è simile alla funzione exec() inquanto esegue command. Se il parametro return_var è specificato, lo stato ritornato dal comando Unix verrà posto lì. Questa funzione deve essere usata al posto di exec() o di system() quando l'output del comando Unix consiste in dati binari da passare direttamente al browser. Un suo uso frequente consiste nel eseguire, ad esempio, le utility pbmplus che possono restituire un flusso diretto all'immagine. Impostado il tipo di contenuto a image/gif e successivamente chiamando un programma pbmplus per generare una gif puoi realizzare uno script PHP che genera direttamente immagini.

Avvertimento

Se si permette di passare a questa funzione i dati provenineti dagli input utente, si dovrebbe utilizzare la funzione escapeshellarg() oppure escapeshellcmd() in modo da essere sicuri che gli utenti non possano compromettere il sistema eseguendo comandi arbitrari.

Nota: Se si vuole avviare un programma tramite questa funzione e lasciarlo girare in background, occorre essere certi che l output del programma sia rediretto su un file o qualche altro flusso di output altrimenti il PHP sarà sospenderà fino a quando il programma non termina.

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 exec(), system(), popen(), escapeshellcmd(), e l'operatore backtick.

proc_close

(PHP 4 >= 4.3.0, PHP 5)

proc_close -- Close a process opened by proc_open() and return the exit code of that process.

Descrizione

int proc_close ( resource process )

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns its exit code. If you have open pipes to that process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.

Elenco dei parametri

process

The proc_open() resource that will be closed.

proc_get_status

(PHP 5)

proc_get_status -- Get information about a process opened by proc_open()

Descrizione

array proc_get_status ( resource process )

proc_get_status() fetches data about a process opened using proc_open().

Elenco dei parametri

process

The proc_open() resource that will be evaluated.

Valori restituiti

An array of collected information on success, and FALSE on failure. The returned array contains the following elements:

elementtypedescription
commandstring The command string that was passed to proc_open()
pidintprocess id
runningbool TRUE if the process is still running, FALSE if it has terminated
signaledbool TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.
stoppedbool TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.
exitcodeint the exit code returned by the process (which is only meaningful if running is FALSE)
termsigint the number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE)
stopsigint the number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE)

Vedere anche:

proc_open()

proc_nice

(PHP 5)

proc_nice -- Change the priority of the current process

Descrizione

bool proc_nice ( int increment )

proc_nice() changes the priority of the current process by the amount specified in increment. A positive increment will lower the priority of the current process, whereas a negative increment will raise the priority.

proc_nice() is not related to proc_open() and its associated functions in any way.

Elenco dei parametri

increment

The increment value of the priority change.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.

Note

Availability: proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. This means that proc_nice() is not available on Windows.

proc_open

(PHP 4 >= 4.3.0, PHP 5)

proc_open --  Execute a command and open file pointers for input/output

Descrizione

resource proc_open ( string cmd, array descriptorspec, array &pipes [, string cwd [, array env [, array other_options]]] )

proc_open() is similar to popen() but provides a much greater degree of control over the program execution.

PHP 5 introduces pty support for systems with Unix98 ptys. This allows your script to interact with applications that expect to be talking to a terminal. A pty works like a pipe, but is bi-directional, so there is no need to specify a read/write mode. The example below shows how to use a pty; note that you don't have to have all descriptors talking to a pty. Also note that only one pty is created, even though pty is specified 3 times. In a future version of PHP, it might be possible to do more than just read and write to the pty.

Elenco dei parametri

cmd

The command to execute

descriptorspec

An indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. 0 is stdin, 1 is stdout, while 2 is stderr.

The currently supported pipe types are file, pipe and pty.

The file descriptor numbers are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.

pipes

Will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created.

cwd

The initial working dir for the command. This must be an absolute directory path, or NULL if you want to use the default value (the working dir of the current PHP process)

env

An array with the environment variables for the command that will be run, or NULL to use the same environment as the current PHP process

other_options

Allows you to specify additional options. Currently only suppress_errors is supported, which suppresses errors generated by this function when it's set to TRUE

Valori restituiti

Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.

Log delle modifiche

VersioneDescrizione
5.0.0. Added the cwd, env and other_options parameters. Added support for Unix98 ptys.

Esempi

Esempio 1. A proc_open() example

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Esempio 2. ptys usage

<?php
// Create a pseudo terminal for the child process
$descriptorspec = array(
   0 => array("pty"),
   1 => array("pty"),
   2 => array("pty")
);
$process = proc_open("cvs -d:pserver:cvsread@cvs.php.net:/repository login", $descriptorspec, $pipes);
if (is_resource($process)) {
   // work with it here
}
?>

Note

Nota: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Nota: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

proc_terminate

(PHP 5)

proc_terminate -- kills a process opened by proc_open

Descrizione

int proc_terminate ( resource process [, int signal] )

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

The optional signal is only useful on POSIX operating systems; you may specify a signal to send to the process using the kill(2) system call. The default is SIGTERM.

proc_terminate() allows you terminate the process and continue with other tasks. You may poll the process (to see if it has stopped yet) by using the proc_get_status() function.

shell_exec

(PHP 4, PHP 5)

shell_exec -- Esegue un comando attraverso la shell e restituisce l'output completo come stringa

Descrizione

string shell_exec ( string cmd )

Questa funzione è identica all'operatore backtick.

Esempio 1. Un shell_exec() esempio

<?php
  	$output = shell_exec('ls -lart');
  	echo "<pre>$output</pre>";
  	?>

Nota: Questa funzione è disabilitata nella modalitàsafe-mode

Vedere anche exec() e escapeshellcmd().

system

(PHP 3, PHP 4, PHP 5)

system -- Esegue un programma esterno e mostra l'output

Descrizione

string system ( string command [, int &return_var] )

system() è semplicemente come la versione C della funzione che esegue il command dato e restituisce in uscita il risultato. Se viene fornita una variabile come secondo argomento, allora il codice di stato ritornato dal comando eseguito verrà scritto in tale variabile.

Avvertimento

Se si permette di passare a questa funzione i dati provenineti dagli input utente, si dovrebbe utilizzare la funzione escapeshellarg() oppure escapeshellcmd() in modo da essere sicuri che gli utenti non possano compromettere il sistema eseguendo comandi arbitrari.

Nota: Se si vuole avviare un programma tramite questa funzione e lasciarlo girare in background, occorre essere certi che l output del programma sia rediretto su un file o qualche altro flusso di output altrimenti il PHP sarà sospenderà fino a quando il programma non termina.

La chiamata a system() tenta anche di ripulire automaticamente il buffer di output del web server dopo ogni linea di output se PHP gira come un modulo server.

Restituisce l'ultima linea del output del comando se ha successo e FALSE se fallisce.

Se devi eseguire un comando ottenendo tutti i dati restituiti dal comando direttamente senza alcuna interferenza, usa la funzione passthru().

Esempio 1. system() example

<?php
  	echo '<pre>';
  	 
  	// Mette in output tutti i risultati della shellcommand "ls", e restituisce
  	// l'ultima  linea di output nella $last_line. Memorizza il valore restituito
  	// del comando da shell in $retval.
  	$last_line = system('ls', $retval);
  	 
  	// Stampa informazioni aggiuntive
  	echo '
  	</pre>
  	<hr />L'ultima linea dell'output: ' . $last_line . '
  	<hr />Restituisce il valore: ' . $retval;
  	?>

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 exec(), passthru(), popen(), escapeshellcmd(), pcntl_exec(), e l'operatore backtick.

CXVIII. PostScript document creation

Introduzione

This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.

Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.


Requisiti

You need at least PHP 4.3.0 and pslib >= 0.1.12. The ps library (pslib) is available at http://pslib.sourceforge.net/.


Installazione

A short installation note: just type
$ pear install ps
in your console.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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 ps extension.

Tabella 1. Contants for line caps

NameMeaning
ps_LINECAP_BUTT 
ps_LINECAP_ROUND 
ps_LINECAP_SQUARED 

Tabella 2. Contants for line joins

NameMeaning
ps_LINEJOIN_MITER 
ps_LINEJOIN_ROUND 
ps_LINEJOIN_BEVEL 


Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail steinm@php.net. Any help is very welcome.

Sommario
ps_add_bookmark -- Add bookmark to current page
ps_add_launchlink -- Adds link which launches file
ps_add_locallink -- Adds link to a page in the same document
ps_add_note -- Adds note to current page
ps_add_pdflink -- Adds link to a page in a second pdf document
ps_add_weblink -- Adds link to a web location
ps_arc -- Draws an arc counterclockwise
ps_arcn -- Draws an arc clockwise
ps_begin_page -- Start a new page
ps_begin_pattern -- Start a new pattern
ps_begin_template -- Start a new template
ps_circle -- Draws a circle
ps_clip -- Clips drawing to current path
ps_close_image -- Closes image and frees memory
ps_close -- Closes a PostScript document
ps_closepath_stroke -- Closes and strokes path
ps_closepath -- Closes path
ps_continue_text -- Continue text in next line
ps_curveto -- Draws a curve
ps_delete -- Deletes all resources of a PostScript document
ps_end_page -- End a page
ps_end_pattern -- End a pattern
ps_end_template -- End a template
ps_fill_stroke -- Fills and strokes the current path
ps_fill -- Fills the current path
ps_findfont -- Loads a font
ps_get_buffer -- Fetches the full buffer containig the generated PS data
ps_get_parameter -- Gets certain parameters
ps_get_value -- Gets certain values
ps_hyphenate -- Hyphenates a word
ps_lineto -- Draws a line
ps_makespotcolor -- Create spot color
ps_moveto -- Sets current point
ps_new -- Creates a new PostScript document object
ps_open_file -- Opens a file for output
ps_open_image_file -- Opens image from file
ps_open_image -- Reads an image for later placement
ps_place_image -- Places image on the page
ps_rect -- Draws a rectangle
ps_restore -- Restore previously save context
ps_rotate -- Sets rotation factor
ps_save -- Save current context
ps_scale -- Sets scaling factor
ps_set_border_color -- Sets color of border for annotations
ps_set_border_dash -- Sets length of dashes for border of annotations
ps_set_border_style -- Sets border style of annotations
ps_set_info -- Sets information fields of document
ps_set_parameter -- Sets certain parameters
ps_set_text_pos -- Sets position for text output
ps_set_value -- Sets certain values
ps_setcolor -- Sets current color
ps_setdash -- Sets appearance of a dashed line
ps_setflat -- Sets flatness
ps_setfont -- Sets font to use for following output
ps_setgray -- Sets gray value
ps_setlinecap -- Sets appearance of line ends
ps_setlinejoin -- Sets how contected lines are joined
ps_setlinewidth -- Sets width of a line
ps_setmiterlimit -- Sets the miter limit
ps_setpolydash -- Sets appearance of a dashed line
ps_shading_pattern -- Creates a pattern based on a shading
ps_shading -- Creates a shading for later use
ps_shfill -- Fills an area with a shading
ps_show_boxed -- Output text in a box
ps_show_xy -- Output text at given position
ps_show -- Output text
ps_string_geometry -- Gets geometry of a string
ps_stringwidth -- Gets width of a string
ps_stroke -- Draws the current path
ps_symbol_name -- Gets name of a glyph
ps_symbol_width -- Gets width of a glyph
ps_symbol -- Output a glyph
ps_translate -- Sets translation

ps_add_bookmark

(PECL)

ps_add_bookmark -- Add bookmark to current page

Descrizione

int ps_add_bookmark ( resource psdoc, string text [, int parent [, int open]] )

Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.

The bookmark has no meaning if the document is printed or viewed but it will be used if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Elenco dei parametri

psdoc

text

parent

The parameter parent is another bookmark which is used as the parent of the new bookmark.

open

If open is unequal to zero the bookmark will be shown open by the pdf viewer.

Valori restituiti

The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent.

Returns the identifier of the bookmark or zero in case of an error. The identifier is a positive number.

ps_add_launchlink

(PECL)

ps_add_launchlink -- Adds link which launches file

Descrizione

bool ps_add_launchlink ( resource psdoc, float llx, float lly, float urx, float ury, string filename )

Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_add_locallink

(PECL)

ps_add_locallink -- Adds link to a page in the same document

Descrizione

bool ps_add_locallink ( resource psdoc, float llx, float lly, float urx, float ury, int page, string dest )

Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.

The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Elenco dei parametri

psdoc

llx

lly

urx

ury

page

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_add_note

(PECL)

ps_add_note -- Adds note to current page

Descrizione

bool ps_add_note ( resource psdoc, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_add_pdflink()

ps_add_pdflink

(PECL)

ps_add_pdflink -- Adds link to a page in a second pdf document

Descrizione

bool ps_add_pdflink ( resource psdoc, float llx, float lly, float urx, float ury, string filename, int page, string dest )

Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.

The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Elenco dei parametri

psdoc

llx

lly

urx

ury

filename

page

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_add_weblink

(PECL)

ps_add_weblink -- Adds link to a web location

Descrizione

bool ps_add_weblink ( resource psdoc, float llx, float lly, float urx, float ury, string url )

Places a hyperlink at the given position pointing to a web page. The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_arc

(PECL)

ps_arc -- Draws an arc counterclockwise

Descrizione

bool ps_arc ( resource psdoc, float x, float y, float radius, float alpha, float beta )

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn counterclockwise. The subpath added to the current path starts on the arc at angle alpha and ends on the arc at angle beta.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_arcn()

ps_arcn

(no version information, might be only in CVS)

ps_arcn -- Draws an arc clockwise

Descrizione

bool ps_arcn ( resource psdoc, float x, float y, float radius, float alpha, float beta )

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn clockwise. The subpath added to the current path starts on the arc at angle beta and ends on the arc at angle alpha.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_arc()

ps_begin_page

(PECL)

ps_begin_page -- Start a new page

Descrizione

bool ps_begin_page ( resource psdoc, float width, float height )

Starts a new page. Although the parameters width and height imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.

Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.

If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. If ps_findfont() was called before the header has been output already, the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field BoundingBox and possibly Orientation before any ps_findfont() or ps_begin_page() calls.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_begin_pattern

(PECL)

ps_begin_pattern -- Start a new pattern

Descrizione

bool ps_begin_pattern ( resource psdoc, float width, float height, float xstep, float ystep, int painttype )

Starts a new pattern.

Valori restituiti

The identifier of the pattern or FALSE in case of an error.

ps_begin_template

(PECL)

ps_begin_template -- Start a new template

Descrizione

bool ps_begin_template ( resource psdoc, float width, float height )

Starts a new template.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_end_template()

ps_circle

(PECL)

ps_circle -- Draws a circle

Descrizione

bool ps_circle ( resource psdoc, float x, float y, float radius )

Draws a circle with its middle point at (x, y). The circle starts and ends at position (x+radius, y). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (x+radius, y) then there will be a gap in the path.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_arc()
ps_arcn()

ps_clip

(PECL)

ps_clip -- Clips drawing to current path

Descrizione

bool ps_clip ( resource psdoc )

Takes the current path and uses it to define the border of a clipping area.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_closepath()

ps_close_image

(PECL)

ps_close_image -- Closes image and frees memory

Descrizione

void ps_close_image ( resource psdoc, int imageid )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Returns NULL on success or FALSE on failure.

ps_close

(PECL)

ps_close -- Closes a PostScript document

Descrizione

bool ps_close ( resource psdoc )

Closes the PostScript document.

This function outputs a last line into the PostScript document, which is a PostScript comment containing the number of pages. It also writes the bookmark tree.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_closepath_stroke

(PECL)

ps_closepath_stroke -- Closes and strokes path

Descrizione

bool ps_closepath_stroke ( resource psdoc )

Connects the last point with first point of a path and draws the resulting closed line.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_closepath()

ps_closepath

(PECL)

ps_closepath -- Closes path

Descrizione

bool ps_closepath ( resource psdoc )

Connects the last point with first point of a path.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_continue_text

(PECL)

ps_continue_text -- Continue text in next line

Descrizione

bool ps_continue_text ( resource psdoc, string text )

Output a text one line below the last outputted line. The line spacing is taken from the value "leading" which must be set with ps_set_value() in points. The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_show()

ps_curveto

(PECL)

ps_curveto -- Draws a curve

Descrizione

bool ps_curveto ( resource psdoc, float x1, float y1, float x2, float y2, float x3, float y3 )

Draws a curve described by the three given points.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_lineto()

ps_delete

(PECL)

ps_delete -- Deletes all resources of a PostScript document

Descrizione

bool ps_delete ( resource psdoc )

Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a last line containing the PostScript comment with the number of pages in the document. Without this comment, a PostScript viewer may not show the number of pages properly.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_close()

ps_end_page

(PECL)

ps_end_page -- End a page

Descrizione

bool ps_end_page ( resource psdoc )

Ends a page which was started with ps_begin_page().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_begin_page()

ps_end_pattern

(PECL)

ps_end_pattern -- End a pattern

Descrizione

bool ps_end_pattern ( resource psdoc )

Ends a pattern which was started with ps_begin_pattern().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_begin_pattern()

ps_end_template

(PECL)

ps_end_template -- End a template

Descrizione

bool ps_end_template ( resource psdoc )

Ends a template which was started with ps_begin_template().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_begin_template()

ps_fill_stroke

(PECL)

ps_fill_stroke -- Fills and strokes the current path

Descrizione

bool ps_fill_stroke ( resource psdoc )

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_fill()
ps_stroke()

ps_fill

(PECL)

ps_fill -- Fills the current path

Descrizione

bool ps_fill ( resource psdoc )

Fills the path constructed with previously called drawing functions like ps_lineto().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_findfont

(PECL)

ps_findfont -- Loads a font

Descrizione

int ps_findfont ( resource psdoc, string fontname, string encoding [, bool embed] )

Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.

Elenco dei parametri

psdoc

fontname

encoding

ps_findfont() will try to load the file passed in the parameter encoding. Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.

encoding can be NULL or the empty string if the default encoding (TeXBase1) shall be used.

If the encoding is set to builtin then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.

embed

Valori restituiti

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

ps_get_buffer

(PECL)

ps_get_buffer -- Fetches the full buffer containig the generated PS data

Descrizione

string ps_get_buffer ( resource psdoc )

Not yet implemented

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Vedere anche:

ps_open_file()

ps_get_parameter

(PECL)

ps_get_parameter -- Gets certain parameters

Descrizione

string ps_get_parameter ( resource psdoc, string name [, float modifier] )

Gets several parameters which were set by ps_set_parameter(). Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().

Valori restituiti

Returns the value of the parameter or FALSE.

Vedere anche:

ps_set_parameter()

ps_get_value

(PECL)

ps_get_value -- Gets certain values

Descrizione

float ps_get_value ( resource psdoc, string name [, float modifier] )

Gets several values which were set by ps_set_value(). Parameters are by definition float values.

Elenco dei parametri

psdoc

name

modifier

The parameter modifier specifies the resource for which the value is to be retrieved. This can be the id of a font or an image. It must be 0.0 if not used.

Valori restituiti

Returns the value of the parameter or FALSE.

Vedere anche:

ps_set_value()

ps_hyphenate

(PECL)

ps_hyphenate -- Hyphenates a word

Descrizione

array ps_hyphenate ( resource psdoc, string text )

Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars and the parameter hyphendict. hyphendict must be set before calling this function.

This function requires the locale category LC_CTYPE to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale.

Elenco dei parametri

psdoc

text

text should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in text after which a hyphenation can take place.

Vedere anche:

ps_show_boxed()
locale(1)

ps_lineto

(PECL)

ps_lineto -- Draws a line

Descrizione

bool ps_lineto ( resource psdoc, float x, float y )

Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_moveto()

ps_makespotcolor

(PECL)

ps_makespotcolor -- Create spot color

Descrizione

int ps_makespotcolor ( resource psdoc, string name [, float reserved] )

Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor().

Valori restituiti

The id of the new spot color or 0 in case of an error.

Vedere anche:

ps_setcolor()

ps_moveto

(PECL)

ps_moveto -- Sets current point

Descrizione

bool ps_moveto ( resource psdoc, float x, float y )

Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_lineto()

ps_new

(PECL)

ps_new -- Creates a new PostScript document object

Descrizione

resource ps_new ( void )

Creates a new document instance. It does not create the file on disk or in memory. It just sets up everything.

Valori restituiti

Resource of PostScript document or FALSE on failure.

Vedere anche:

ps_delete()

ps_open_file

(PECL)

ps_open_file -- Opens a file for output

Descrizione

bool ps_open_file ( resource psdoc [, string filename] )

Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.

Elenco dei parametri

psdoc

filename

If filename is not passed the document will be created in memory and all output will go straight to the browser.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_close()

ps_open_image_file

(PECL)

ps_open_image_file -- Opens image from file

Descrizione

int ps_open_image_file ( resource psdoc, string type, string filename [, string stringparam [, int intparam]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

ps_open_image

(PECL)

ps_open_image -- Reads an image for later placement

Descrizione

int ps_open_image ( resource psdoc, string type, string source, string data, int lenght, int width, int height, int components, int bpc, string params )

Reads an image which is already available in memory. The parameter source is currently not evaluated and assumed to be memory.

Valori restituiti

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

ps_place_image

(PECL)

ps_place_image -- Places image on the page

Descrizione

bool ps_place_image ( resource psdoc, int imageid, float x, float y, float scale )

Places a formerly loaded image on the page. The image can be scaled.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_rect

(PECL)

ps_rect -- Draws a rectangle

Descrizione

bool ps_rect ( resource psdoc, float x, float y, float width, float height )

Draws a rectangle with its lower left corner at (x, y). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_arc()
ps_cirle()
ps_lineto()

ps_restore

(PECL)

ps_restore -- Restore previously save context

Descrizione

bool ps_restore ( resource psdoc )

Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_save()

ps_rotate

(PECL)

ps_rotate -- Sets rotation factor

Descrizione

bool ps_rotate ( resource psdoc, float rot )

Sets the rotation of the coordinate system.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_save

(PECL)

ps_save -- Save current context

Descrizione

bool ps_save ( resource psdoc )

Saves the current graphics context, containing colors, translation and rotation settings and some more. A save context can be restored with ps_restore().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_restore()

ps_scale

(PECL)

ps_scale -- Sets scaling factor

Descrizione

bool ps_scale ( resource psdoc, float x, float y )

Sets horizontal and vertical scaling of the coordinate system.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_set_border_color

(PECL)

ps_set_border_color -- Sets color of border for annotations

Descrizione

bool ps_set_border_color ( resource psdoc, float red, float green, float blue )

Annotations like the starting points of links are surrounded by a rectangle. This function sets the color of the border line.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_set_border_dash

(PECL)

ps_set_border_dash -- Sets length of dashes for border of annotations

Descrizione

bool ps_set_border_dash ( resource psdoc, float black, float white )

Annotations like the starting points of links are surrounded by a rectangle. This function sets the black and white portion of a dashed border line.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_set_border_style

(PECL)

ps_set_border_style -- Sets border style of annotations

Descrizione

bool ps_set_border_style ( resource psdoc, string style, float width )

Annotations like the starting points of links are surrounded by a rectangle. This function sets the appearance and width of the border line.

Elenco dei parametri

psdoc

style

style can be solid or dashed.

width

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_set_info

(PECL)

ps_set_info -- Sets information fields of document

Descrizione

bool ps_set_info ( resource p, string key, string val )

Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. The values which can be set are Keywords, Subject, Title, Creator, Author, BoundingBox, and Orientation. Be aware that some of them has a meaning to PostScript viewers.

The BoundingBox is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_set_parameter

(PECL)

ps_set_parameter -- Sets certain parameters

Descrizione

bool ps_set_parameter ( resource psdoc, string name, string value )

Sets several parameters which are used by many functions. Parameters are by definition string values.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_get_parameters()
ps_set_value()

ps_set_text_pos

(PECL)

ps_set_text_pos -- Sets position for text output

Descrizione

bool ps_set_text_pos ( resource psdoc, float x, float y )

Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing textx respectively texty as the value name.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_set_value

(PECL)

ps_set_value -- Sets certain values

Descrizione

bool ps_set_value ( resource psdoc, string name, float value )

Sets several values which are used by many functions. Parameters are by definition float values.

Elenco dei parametri

The name can be one of the following:

textrendering

The way how text is shown.

textx

The x coordinate for text output.

texty

The y coordinate for text output.

wordspacing

The distance between words relative to the width of a space.

leading

The distance between lines in pixels.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setcolor

(PECL)

ps_setcolor -- Sets current color

Descrizione

bool ps_setcolor ( resource psdoc, string type, string colorspace, float c1, float c2, float c3, float c4 )

Sets the color for drawing, filling, or both.

Elenco dei parametri

psdoc

type

The parameter type can be both, fill, or fillstroke.

colorspace

The colorspace should be one of gray, rgb, cmyk, spot, pattern. Depending on the colorspace either only the first, the first three or all parameters will be used.

c1

c2

c3

c4

Bugs

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setdash

(PECL)

ps_setdash -- Sets appearance of a dashed line

Descrizione

bool ps_setdash ( resource psdoc, float on, float off )

Sets the length of the black and white portions of a dashed line.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_setpolydash()

ps_setflat

(PECL)

ps_setflat -- Sets flatness

Descrizione

bool ps_setflat ( resource psdoc, float value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

psdoc

value

The value must be between 0.2 and 1.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setfont

(PECL)

ps_setfont -- Sets font to use for following output

Descrizione

bool ps_setfont ( resource psdoc, int fontid, float size )

Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font before results in an error.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_findfont()

ps_setgray

(no version information, might be only in CVS)

ps_setgray -- Sets gray value

Descrizione

bool ps_setgray ( resource psdoc, float gray )

Sets the gray value for all following drawing operations.

Elenco dei parametri

psdoc

gray

The value must be between 0 (white) and 1 (black).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_setcolor()

ps_setlinecap

(PECL)

ps_setlinecap -- Sets appearance of line ends

Descrizione

bool ps_setlinecap ( resource psdoc, int type )

Sets how line ends look like.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setlinejoin

(PECL)

ps_setlinejoin -- Sets how contected lines are joined

Descrizione

bool ps_setlinejoin ( resource psdoc, int type )

Sets how lines are joined.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setlinewidth

(PECL)

ps_setlinewidth -- Sets width of a line

Descrizione

bool ps_setlinewidth ( resource psdoc, float width )

Sets the line width for all following drawing operations.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setmiterlimit

(PECL)

ps_setmiterlimit -- Sets the miter limit

Descrizione

bool ps_setmiterlimit ( resource psdoc, float value )

If two lines join in a small angle and the line join is set to miter, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_setpolydash

(PECL)

ps_setpolydash -- Sets appearance of a dashed line

Descrizione

bool ps_setpolydash ( resource psdoc, float arr )

Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.

Elenco dei parametri

psdoc

arr

arr is a list of length elements alternately for the black and white portion.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_setdash()

ps_shading_pattern

(PECL)

ps_shading_pattern -- Creates a pattern based on a shading

Descrizione

int ps_shading_pattern ( resource psdoc, int shadingid, string optlist )

Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.

Valori restituiti

The identifier of the pattern or FALSE in case of an error.

ps_shading

(PECL)

ps_shading -- Creates a shading for later use

Descrizione

int ps_shading ( resource psdoc, string type, float x0, float y0, float x1, float y1, float c1, float c2, float c3, float c4, string optlist )

Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().

The color of the shading can be in any color space except for pattern.

Elenco dei parametri

psdoc

type

The type of shading can be either radial or axial. Each shading starts with the current fill color and ends with the given color values passed in the parameters c1 to c4 (see ps_setcolor() for their meaning).

x0, x1, y0, y1

The coordinates x0, y0, x1, y1 are the start and end point of the shading.

c1, c2, c3, c4

See ps_setcolor() for their meaning.

optlist

If the shading is of type radial the optlist must also contain the parameters r0 and r1 with the radius of the start and end circle.

Valori restituiti

Returns the identifier of the pattern or FALSE in case of an error.

ps_shfill

(PECL)

ps_shfill -- Fills an area with a shading

Descrizione

bool ps_shfill ( resource psdoc, int shadingid )

Fills an area with a shading, which has to be created before with ps_shading().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_show_boxed

(PECL)

ps_show_boxed -- Output text in a box

Descrizione

int ps_show_boxed ( resource psdoc, string text, float left, float bottom, float width, float height, string hmode [, string feature] )

Outputs a text in a given box. The lower left corner of the box is at (left, bottom). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.

The text will be hyphenated if the parameter "hyphenation" is set to "true" and the parameter "hyphendict" contains a valid filename for a hyphenation file. The line spacing is taken from the value "leading". Paragraphs can be separated by an empty line just like in TeX. If the value "parindent" is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter "numindentlines". In order to prevent indenting of the first m paragraphs set the value "parindentskip" to a positive number.

Used parameters

The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output the following parameters and values are evaluated.

leading (value)

Distance between baselines of two consecutive lines.

linebreak (parameter)

Set to "true" if you want a carriage return to start a new line instead of treating it as a space. Defaults to "false".

parbreak (parameter)

Set to "true" if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to "true".

hyphenation (parameter)

Set to "true" in order to turn hyphenation on. This requires a dictionary to be set with the parameter "hyphendict". Defaults to "false".

hyphendict (parameter)

Filename of the dictionary used for hyphenation pattern (see below).

hyphenminchar (value)

The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.

parindent (value)

Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value "numindentlines".

parskip (value)

Set the amount of extra space in pixel between paragraphs. Defaults to 0 which will result in a normal line distance.

numindentlines (value)

Number of lines from the start of the paragraph which will be indented. Defaults to 1.

parindentskip (value)

Number of paragraphs in the box whose first lines will not be indented. This defaults to 0. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to 1.

linenumbermode (parameter)

Set how lines are to be numbered. Possible values are "box" for numbering lines in the whole box or "paragraph" to number lines within each paragraph.

linenumberspace (value)

The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to 20.

linenumbersep (value)

The space between the column with line numbers and the line itself. Defaults to 5.

Hyphenation

Text is hyphenated if the parameter hyphenation is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:

/usr/share/apps/koffice/hyphdicts/
/usr/lib/scribus/dicts/
/usr/lib/openoffice/share/dict/ooo/

Currently scribus appears to have the most complete hyphenation dictionaries.

Elenco dei parametri

psdoc

text

left

bottom

width

height

hmode

The parameter hmode can be "justify", "fulljustify", "right", "left", or "center". The difference of "justify" and "fulljustify" just affects the last line of the box. In fulljustify mode the last line will be left and right justified unless this is also the last line of paragraph. In justify mode it will always be left justified.

feature

Valori restituiti

Number of characters that could not be written.

Vedere anche:

ps_continue_text()

ps_show_xy

(PECL)

ps_show_xy -- Output text at given position

Descrizione

bool ps_show_xy ( resource psdoc, string text, float x, float y )

Output a text at the given text position.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_show

(PECL)

ps_show -- Output text

Descrizione

bool ps_show ( resource psdoc, string text )

Output a text at the current text position. The function will issue an error if no font was set before with ps_setfont().

ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().

charspacing (value)

Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.

kerning (parameter)

Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.

ligatures (parameter)

Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.

underline (parameter)

Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.

overline (parameter)

Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.

strikeout (parameter)

Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_string_geometry

(PECL)

ps_string_geometry -- Gets geometry of a string

Descrizione

array ps_string_geometry ( resource psdoc, string text [, int fontid [, float size]] )

This function is similar to ps_stringwidth() but returns an array of dimensions.

Valori restituiti

An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.

ps_stringwidth

(PECL)

ps_stringwidth -- Gets width of a string

Descrizione

float ps_stringwidth ( resource psdoc, string text [, int fontid [, float size]] )

Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.

Valori restituiti

Width of a string in points.

Vedere anche:

ps_string_geometry()

ps_stroke

(PECL)

ps_stroke -- Draws the current path

Descrizione

bool ps_stroke ( resource psdoc )

Draws the path constructed with previously called drawing functions like ps_lineto().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_symbol_name

(PECL)

ps_symbol_name -- Gets name of a glyph

Descrizione

string ps_symbol_name ( resource psdoc, int ord [, int fontid] )

This function needs an Adobe font metrics file to know which glyphs are available.

Elenco dei parametri

psdoc

ord

The parameter ord is the position of the glyph in the font encoding vector.

fontid

Valori restituiti

The name of a glyph in the given font.

ps_symbol_width

(PECL)

ps_symbol_width -- Gets width of a glyph

Descrizione

float ps_symbol_width ( resource psdoc, int ord [, int fontid [, float size]] )

Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.

Elenco dei parametri

psdoc

ord

The parameter ord is the position of the glyph in the font encoding vector.

fontid

Its description

size

Valori restituiti

The width of a glyph in points.

ps_symbol

(PECL)

ps_symbol -- Output a glyph

Descrizione

bool ps_symbol ( resource psdoc, int ord )

Output the glyph at position ord in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ps_translate

(PECL)

ps_translate -- Sets translation

Descrizione

bool ps_translate ( resource psdoc, float x, float y )

Sets a new initial point of the coordinate system.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

ps_scale()
ps_rotate()

CXIX. Pspell Functions

Introduzione

These functions allow you to check the spelling of a word and offer suggestions.


Requisiti

To compile PHP with pspell support, you need the aspell library, available from http://aspell.sourceforge.net/.


Installazione

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Note to Win32 Users: win32 support is available only in PHP 4.3.3 and later versions. Also, you must have aspell 0.50 or newer installed. In order to enable this module under Windows, you must copy aspell-15.dll from the bin folder of your aspell installation to a folder where PHP will be able to find it. C:\PHP or the SYSTEM32 folder of your windows machine (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32) are good choices.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

PSPELL_FAST (integer)

PSPELL_NORMAL (integer)

PSPELL_BAD_SPELLERS (integer)

PSPELL_RUN_TOGETHER (integer)

Sommario
pspell_add_to_personal -- Add the word to a personal wordlist
pspell_add_to_session -- Add the word to the wordlist in the current session
pspell_check -- Check a word
pspell_clear_session -- Clear the current session
pspell_config_create -- Create a config used to open a dictionary
pspell_config_data_dir --  location of language data files
pspell_config_dict_dir --  Location of the main word list
pspell_config_ignore -- Ignore words less than N characters long
pspell_config_mode -- Change the mode number of suggestions returned
pspell_config_personal -- Set a file that contains personal wordlist
pspell_config_repl -- Set a file that contains replacement pairs
pspell_config_runtogether -- Consider run-together words as valid compounds
pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist
pspell_new_config -- Load a new dictionary with settings based on a given config
pspell_new_personal -- Load a new dictionary with personal wordlist
pspell_new -- Load a new dictionary
pspell_save_wordlist -- Save the personal wordlist to a file
pspell_store_replacement -- Store a replacement pair for a word
pspell_suggest -- Suggest spellings of a word

pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_personal -- Add the word to a personal wordlist

Description

bool pspell_add_to_personal ( int dictionary_link, string word )

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Esempio 1. pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_session -- Add the word to the wordlist in the current session

Description

bool pspell_add_to_session ( int dictionary_link, string word )

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

pspell_check

(PHP 4 >= 4.0.2, PHP 5)

pspell_check -- Check a word

Description

bool pspell_check ( int dictionary_link, string word )

pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.

Esempio 1. pspell_check()

<?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?>

pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_clear_session -- Clear the current session

Description

bool pspell_clear_session ( int dictionary_link )

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

Esempio 1. pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_clear_session($pspell_link);
pspell_save_wordlist($pspell_link);    //"Vlad" will not be saved
?>

pspell_config_create

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_create -- Create a config used to open a dictionary

Description

int pspell_config_create ( string language [, string spelling [, string jargon [, string encoding]]] )

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Esempio 1. pspell_config_create()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal($pspell_config, "en");
?>

pspell_config_data_dir

(PHP 5)

pspell_config_data_dir --  location of language data files

Description

bool pspell_config_data_dir ( int conf, string directory )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

pspell_config_dict_dir

(PHP 5)

pspell_config_dict_dir --  Location of the main word list

Description

bool pspell_config_dict_dir ( int conf, string directory )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_ignore -- Ignore words less than N characters long

Description

bool pspell_config_ignore ( int dictionary_link, int n )

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spell checker. Words less than n characters will be skipped.

Esempio 1. pspell_config_ignore()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd");    //will not result in an error
?>

pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_mode -- Change the mode number of suggestions returned

Description

bool pspell_config_mode ( int dictionary_link, int mode )

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Esempio 1. pspell_config_mode()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_personal -- Set a file that contains personal wordlist

Description

bool pspell_config_personal ( int dictionary_link, string file )

pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Esempio 1. pspell_config_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_repl -- Set a file that contains replacement pairs

Description

bool pspell_config_repl ( int dictionary_link, string file )

pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Esempio 1. pspell_config_repl()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_runtogether -- Consider run-together words as valid compounds

Description

bool pspell_config_runtogether ( int dictionary_link, bool flag )

pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Esempio 1. pspell_config_runtogether()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist

Description

bool pspell_config_save_repl ( int dictionary_link, bool flag )

pspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new_config

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_config -- Load a new dictionary with settings based on a given config

Description

int pspell_new_config ( int config )

pspell_new_config() opens up a new dictionary with settings specified in a config, created with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().

The config parameter is the one returned by pspell_config_create() when the config was created.

Esempio 1. pspell_new_config()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
?>

pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_personal -- Load a new dictionary with personal wordlist

Description

int pspell_new_personal ( string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]] )

pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

The personal parameter specifies the file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Esempio 1. pspell_new_personal()

<?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws", 
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>

pspell_new

(PHP 4 >= 4.0.2, PHP 5)

pspell_new -- Load a new dictionary

Description

int pspell_new ( string language [, string spelling [, string jargon [, string encoding [, int mode]]]] )

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

For more information and examples, check out inline manual pspell website:http://aspell.net/.

Esempio 1. pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "", 
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5)

pspell_save_wordlist -- Save the personal wordlist to a file

Description

bool pspell_save_wordlist ( int dictionary_link )

pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Esempio 1. pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5)

pspell_store_replacement -- Store a replacement pair for a word

Description

bool pspell_store_replacement ( int dictionary_link, string misspelled, string correct )

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Esempio 1. pspell_store_replacement()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);

pspell_store_replacement($pspell_link, $misspelled, $correct);
pspell_save_wordlist($pspell_link);
?>

pspell_suggest

(PHP 4 >= 4.0.2, PHP 5)

pspell_suggest -- Suggest spellings of a word

Description

array pspell_suggest ( int dictionary_link, string word )

pspell_suggest() returns an array of possible spellings for the given word.

Esempio 1. pspell_suggest() example

<?php
$pspell_link = pspell_new("en");

if (!pspell_check($pspell_link, "testt")) {
    $suggestions = pspell_suggest($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />"; 
    }
}
?>

CXX. Funzioni qtdom

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 non è disponibile su piattaforme Windows.

Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.


Requisiti

E' richiesta la libreria Qt-library >=2.2.0


Installazione

Per utilizzare questo modulo, configurare il PHP con --with-qtdom.

Sommario
qdom_error -- Restituisce la stringa d'errore dell'ultima operazione QDOM o FALSE se non ci sono stati errori
qdom_tree -- Crea un tree di una stringa XML

qdom_error

(PHP 4 >= 4.0.5, PECL)

qdom_error -- Restituisce la stringa d'errore dell'ultima operazione QDOM o FALSE se non ci sono stati errori

Descrizione

string qdom_error ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

qdom_tree

(PHP 4 >= 4.0.4, PECL)

qdom_tree -- Crea un tree di una stringa XML

Descrizione

QDomDocument qdom_tree ( string 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CXXI. Radius

Introduzione

This package is based on the libradius of FreeBSD. This PECL adds full support for Radius Authentication (RFC 2865) and Radius Accounting (RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.

Nota: An exact description for libradius can be found here. A detailed description of the configuration file can be found here.


Installazione

Howto install the package?

  • untar the package (usually into php4/ext)

  • rename radius-x.x to radius

  • run ./buildconf in php4

  • run ./configure --enable-radius

  • make; make install

or if you would like to have it as .so:

  • untar the package

  • run phpize in the radius-x.x directory

  • run ./configure in the radius-x.x directory

  • make; make install

For windows I recommend to use the php_radius.dll from http://snaps.php.net/. You may obtain this unbundled PECL extension from the various PECL snaps pages (select the appropriate repository for your version of PHP): PECL for PHP 4.3.x, PECL for PHP 5.0.x or PECL Unstable.


Costanti predefinite

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.

RADIUS_ACCESS_REQUEST ()

Authentication Request

RADIUS_ACCESS_ACCEPT ()

Access accepted

RADIUS_ACCESS_REJECT ()

Access rejected

RADIUS_ACCOUNTING_REQUEST ()

Accounting request

RADIUS_ACCOUNTING_RESPONSE ()

Accounting response

RADIUS_ACCESS_CHALLENGE ()

Accsess challenge

RADIUS_USER_NAME (string)

Username

RADIUS_USER_PASSWORD (string)

Password

RADIUS_CHAP_PASSWORD (string)

Chap Password: chappass = md5(ident + plaintextpass + challenge)

RADIUS_NAS_IP_ADDRESS (string)

NAS IP-Adress

RADIUS_NAS_PORT (int)

NAS Port

RADIUS_SERVICE_TYPE (int)

Type of Service, one of:

RADIUS_LOGIN
RADIUS_FRAMED
RADIUS_CALLBACK_LOGIN
RADIUS_CALLBACK_FRAMED
RADIUS_OUTBOUND
RADIUS_ADMINISTRATIVE
RADIUS_NAS_PROMPT
RADIUS_AUTHENTICATE_ONLY
RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

Framed Protocol, one of:

RADIUS_PPP
RADIUS_SLIP
RADIUS_ARAP
RADIUS_GANDALF
RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (string)

IP-Address

RADIUS_FRAMED_IP_NETMASK (string)

Netmask

RADIUS_FRAMED_ROUTING (int)

Routing

RADIUS_FILTER_ID (string)

Filter ID

RADIUS_FRAMED_MTU (int)

MTU

RADIUS_FRAMED_COMPRESSION (int)

Compression, one of:

RADIUS_COMP_NONE
RADIUS_COMP_VJ
RADIUS_COMP_IPXHDR

RADIUS_LOGIN_IP_HOST (string)

Login IP Host

RADIUS_LOGIN_SERVICE (int)

Login Service

RADIUS_LOGIN_TCP_PORT (int)

Login TCP Port

RADIUS_REPLY_MESSAGE (string)

Reply Message

RADIUS_CALLBACK_NUMBER (string)

Callback Number

RADIUS_CALLBACK_ID (string)

Callback ID

RADIUS_FRAMED_ROUTE (string)

Framed Route

RADIUS_FRAMED_IPX_NETWORK (string)

Framed IPX Network

RADIUS_STATE (string)

State

RADIUS_CLASS (int)

Class

RADIUS_VENDOR_SPECIFIC (int)

Vendor specific attribute

RADIUS_SESSION_TIMEOUT (int)

Session timeout

RADIUS_IDLE_TIMEOUT (int)

Idle timeout

RADIUS_TERMINATION_ACTION (int)

Termination action

RADIUS_CALLED_STATION_ID (int)

Called Station Id

RADIUS_CALLING_STATION_ID (string)

Calling Station Id

RADIUS_NAS_IDENTIFIER (int)

NAS ID

RADIUS_PROXY_STATE (int)

Proxy State

RADIUS_LOGIN_LAT_SERVICE (int)

Login LAT Service

RADIUS_LOGIN_LAT_NODE (int)

Login LAT Node

RADIUS_LOGIN_LAT_GROUP (int)

Login LAT Group

RADIUS_FRAMED_APPLETALK_LINK (int)

Framed Appletalk Link

RADIUS_FRAMED_APPLETALK_NETWORK (int)

Framed Appletalk Network

RADIUS_FRAMED_APPLETALK_ZONE (int)

Framed Appletalk Zone

RADIUS_CHAP_CHALLENGE (string)

Challenge

RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

RADIUS_ASYNC
RADIUS_SYNC
RADIUS_ISDN_SYNC
RADIUS_ISDN_ASYNC_V120
RADIUS_ISDN_ASYNC_V110
RADIUS_VIRTUAL
RADIUS_PIAFS
RADIUS_HDLC_CLEAR_CHANNEL
RADIUS_X_25
RADIUS_X_75
RADIUS_G_3_FAX
RADIUS_SDSL
RADIUS_ADSL_CAP
RADIUS_ADSL_DMT
RADIUS_IDSL
RADIUS_ETHERNET
RADIUS_XDSL
RADIUS_CABLE
RADIUS_WIRELESS_OTHER
RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)

Port Limit

RADIUS_LOGIN_LAT_PORT (int)

Login LAT Port

RADIUS_CONNECT_INFO (string)

Connect info

RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

RADIUS_START
RADIUS_STOP
RADIUS_ACCOUNTING_ON
RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)

Accounting delay time

RADIUS_ACCT_INPUT_OCTETS (int)

Accounting input bytes

RADIUS_ACCT_OUTPUT_OCTETS (int)

Accounting output bytes

RADIUS_ACCT_SESSION_ID (int)

Accounting session ID

RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

RADIUS_AUTH_RADIUS
RADIUS_AUTH_LOCAL
RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)

Accounting session time

RADIUS_ACCT_INPUT_PACKETS (int)

Accounting input packets

RADIUS_ACCT_OUTPUT_PACKETS (int)

Accounting output packets

RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

RADIUS_TERM_USER_REQUEST
RADIUS_TERM_LOST_CARRIER
RADIUS_TERM_LOST_SERVICE
RADIUS_TERM_IDLE_TIMEOUT
RADIUS_TERM_SESSION_TIMEOUT
RADIUS_TERM_ADMIN_RESET
RADIUS_TERM_ADMIN_REBOOT
RADIUS_TERM_PORT_ERROR
RADIUS_TERM_NAS_ERROR
RADIUS_TERM_NAS_REQUEST
RADIUS_TERM_NAS_REBOOT
RADIUS_TERM_PORT_UNNEEDED
RADIUS_TERM_PORT_PREEMPTED
RADIUS_TERM_PORT_SUSPENDED
RADIUS_TERM_SERVICE_UNAVAILABLE
RADIUS_TERM_CALLBACK
RADIUS_TERM_USER_ERROR
RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)

Accounting multi session ID

RADIUS_ACCT_LINK_COUNT (int)

Accounting link count

RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (RFC 2548), one of:

RADIUS_MICROSOFT_MS_CHAP_RESPONSE
RADIUS_MICROSOFT_MS_CHAP_ERROR
RADIUS_MICROSOFT_MS_CHAP_PW_1
RADIUS_MICROSOFT_MS_CHAP_PW_2
RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
RADIUS_MICROSOFT_MS_RAS_VENDOR
RADIUS_MICROSOFT_MS_CHAP_DOMAIN
RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
RADIUS_MICROSOFT_MS_BAP_USAGE
RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
RADIUS_MICROSOFT_MS_RAS_VERSION
RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
RADIUS_MICROSOFT_MS_FILTER
RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
RADIUS_MICROSOFT_MS_CHAP2_PW
RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
RADIUS_MICROSOFT_MS_ARAP_CHALLENGE


Quickstart

Howto start?

  • get a radius resource

  • configure the library

  • create the request

  • put attributes

  • send the request

  • receive attributes

  • close the radius resource (optional)

Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.


Contact Information

If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at mbretter@php.net. Binaries for Windows can be downloaded from here.

Sommario
radius_acct_open -- Creates a Radius handle for accounting
radius_add_server -- Adds a server
radius_auth_open -- Creates a Radius handle for authentication
radius_close -- Frees all ressources
radius_config -- Causes the library to read the given configuration file
radius_create_request -- Create accounting or authentication request
radius_cvt_addr -- Converts raw data to IP-Address
radius_cvt_int -- Converts raw data to integer
radius_cvt_string -- Converts raw data to string
radius_demangle_mppe_key -- Derives mppe-keys from mangled data
radius_demangle -- Demangles data
radius_get_attr -- Extracts an attribute
radius_get_vendor_attr -- Extracts a vendor specific attribute
radius_put_addr -- Attaches an IP-Address attribute
radius_put_attr -- Attaches a binary attribute
radius_put_int -- Attaches an integer attribute
radius_put_string -- Attaches a string attribute
radius_put_vendor_addr -- Attaches a vendor specific IP-Address attribute
radius_put_vendor_attr -- Attaches a vendor specific binary attribute
radius_put_vendor_int -- Attaches a vendor specific integer attribute
radius_put_vendor_string -- Attaches a vendor specific string attribute
radius_request_authenticator -- Returns the request authenticator
radius_send_request -- Sends the request and waites for a reply
radius_server_secret -- Returns the shared secret
radius_strerror -- Returns an error message

radius_acct_open

(PECL)

radius_acct_open -- Creates a Radius handle for accounting

Descrizione

resource radius_acct_open ( void )

Valori restituiti

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Esempi

Esempio 1. radius_acct_open() example

<?php
$res = radius_acct_open ()
    or die ("Could not create handle");
print("Handle successfully created");
?>

radius_add_server

(PECL)

radius_add_server -- Adds a server

Descrizione

bool radius_add_server ( resource radius_handle, string hostname, int port, string secret, int timeout, int max_tries )

radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.

Elenco dei parametri

radius_handle

hostname

The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

port

The port specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp or radacct/udp service in the network services database, and uses the port found there. If no entry is found, the library uses the standard Radius ports, 1812 for authentication and 1813 for accounting.

secret

The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.

timeout

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

max_tries

The maximum number of repeated requests to make before giving up is passed into the max_tries.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. radius_add_server() example

<?php
if (!radius_add_server($res, 'radius.example.com', 1812, 'testing123', 3, 3)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br>";
    exit;
}
?>

Vedere anche:

radius_config()

radius_auth_open

(PECL)

radius_auth_open -- Creates a Radius handle for authentication

Descrizione

resource radius_auth_open ( void )

Valori restituiti

Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.

Esempi

Esempio 1. radius_auth_open() example

<?php
$radh = radius_auth_open()
    or die ("Could not create handle");
echo "Handle successfully created";
?>

radius_close

(PECL)

radius_close -- Frees all ressources

Descrizione

bool radius_close ( resource radius_handle )

It is not needed to call this function because php frees all resources at the end of each request.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

radius_config

(PECL)

radius_config -- Causes the library to read the given configuration file

Descrizione

bool radius_config ( resource radius_handle, string file )

Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in radius.conf.

Elenco dei parametri

radius_handle

file

The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

radius_add_server()

radius_create_request

(PECL)

radius_create_request -- Create accounting or authentication request

Descrizione

bool radius_create_request ( resource radius_handle, int type )

A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().

Nota: Attention: You must call this function, before you can put any attribute!

Elenco dei parametri

radius_handle

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

type

Its description

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. radius_create_request() example

<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Vedere anche:

radius_send_request()

radius_cvt_addr

(PECL)

radius_cvt_addr -- Converts raw data to IP-Address

Descrizione

string radius_cvt_addr ( string data )

Esempi

Esempio 1. radius_cvt_addr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    
    switch ($attr) {

    case RADIUS_FRAMED_IP_ADDRESS:
        $ip = radius_cvt_addr($data);
        echo "IP: $ip<br>\n";
        break;

    case RADIUS_FRAMED_IP_NETMASK:
        $mask = radius_cvt_addr($data);
        echo "MASK: $mask<br>\n";
        break;
    }
}
?>

radius_cvt_int

(PECL)

radius_cvt_int -- Converts raw data to integer

Descrizione

int radius_cvt_int ( string data )

Esempi

Esempio 1. radius_cvt_int() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    
    switch ($attr) {

    case RADIUS_FRAMED_MTU:
        $mtu = radius_cvt_int($data);
        echo "MTU: $mtu<br>\n";
        break;
    }
}
?>

radius_cvt_string

(PECL)

radius_cvt_string -- Converts raw data to string

Descrizione

string radius_cvt_string ( string data )

Esempi

Esempio 1. radius_cvt_string() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    
    switch ($attr) {

    case RADIUS_FILTER_ID:
        $id = radius_cvt_string($data);
        echo "Filter ID: $id<br>\n";
        break;
    }
}
?>

radius_demangle_mppe_key

(PECL)

radius_demangle_mppe_key -- Derives mppe-keys from mangled data

Descrizione

string radius_demangle_mppe_key ( resource radius_handle, string mangled )

When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.

Valori restituiti

Returns the demangled string, or FALSE on error.

radius_demangle

(PECL)

radius_demangle -- Demangles data

Descrizione

string radius_demangle ( resource radius_handle, string mangled )

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

Valori restituiti

Returns the demangled string, or FALSE on error.

radius_get_attr

(PECL)

radius_get_attr -- Extracts an attribute

Descrizione

mixed radius_get_attr ( resource radius_handle )

Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.

Valori restituiti

Returns an associative array containing the attribute-type and the data, or error number <= 0.

Esempi

Esempio 1. radius_get_attr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
}
?>

radius_get_vendor_attr

(PECL)

radius_get_vendor_attr -- Extracts a vendor specific attribute

Descrizione

array radius_get_vendor_attr ( string data )

If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.

Valori restituiti

Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.

Esempi

Esempio 1. radius_get_vendor_attr() example

<?php
while ($resa = radius_get_attr($res)) {

    if (!is_array($resa)) {
        printf ("Error getting attribute: %s\n",  radius_strerror($res));
        exit;
    }

    $attr = $resa['attr'];
    $data = $resa['data'];
    printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
    if ($attr == RADIUS_VENDOR_SPECIFIC) {

        $resv = radius_get_vendor_attr($data);
        if (is_array($resv)) {
            $vendor = $resv['vendor'];
            $attrv = $resv['attr'];
            $datav = $resv['data'];    
            printf("Got Vendor Attr:%d %d Bytes %s\n", $attrv, strlen($datav), bin2hex($datav));
        }
        
    }
}
?>

radius_put_addr

(PECL)

radius_put_addr -- Attaches an IP-Address attribute

Descrizione

bool radius_put_addr ( resource radius_handle, int type, string addr )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

radius_put_attr

(PECL)

radius_put_attr -- Attaches a binary attribute

Descrizione

bool radius_put_attr ( resource radius_handle, int type, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. radius_put_attr() example

<?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

radius_put_int

(PECL)

radius_put_int -- Attaches an integer attribute

Descrizione

bool radius_put_int ( resource radius_handle, int type, int value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. radius_put_int() example

<?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
   echo 'RadiusError:' . radius_strerror($res). "\n<br />";
   exit;
}
?>

radius_put_string

(PECL)

radius_put_string -- Attaches a string attribute

Descrizione

bool radius_put_string ( resource radius_handle, int type, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. radius_put_string() example

<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

radius_put_vendor_addr

(PECL)

radius_put_vendor_addr -- Attaches a vendor specific IP-Address attribute

Descrizione

bool radius_put_vendor_addr ( resource radius_handle, int vendor, int type, string addr )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

radius_put_vendor_attr

(PECL)

radius_put_vendor_attr -- Attaches a vendor specific binary attribute

Descrizione

bool radius_put_vendor_attr ( resource radius_handle, int vendor, int type, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. radius_put_vendor_attr() example

<?php
if (!radius_put_vendor_attr($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

radius_put_vendor_int

(PECL)

radius_put_vendor_int -- Attaches a vendor specific integer attribute

Descrizione

bool radius_put_vendor_int ( resource radius_handle, int vendor, int type, int value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

radius_put_vendor_string

(PECL)

radius_put_vendor_string -- Attaches a vendor specific string attribute

Descrizione

bool radius_put_vendor_string ( resource radius_handle, int vendor, int type, string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

radius_request_authenticator

(PECL)

radius_request_authenticator -- Returns the request authenticator

Descrizione

string radius_request_authenticator ( resource radius_handle )

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

Valori restituiti

Returns the request authenticator as string, or FALSE on error.

Vedere anche:

radius_demangle()

radius_send_request

(PECL)

radius_send_request -- Sends the request and waites for a reply

Descrizione

int radius_send_request ( resource radius_handle )

After the Radius request has been constructed, it is sent by radius_send_request().

The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.

Valori restituiti

If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns FALSE.

radius_server_secret

(PECL)

radius_server_secret -- Returns the shared secret

Descrizione

string radius_server_secret ( resource radius_handle )

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

Valori restituiti

Returns the server's shared secret as string, or FALSE on error.

radius_strerror

(PECL)

radius_strerror -- Returns an error message

Descrizione

string radius_strerror ( resource radius_handle )

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

Valori restituiti

Returns error messages as string from failed radius functions.

CXXII. Rar Functions

Introduzione

Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by UnRar library and is directly prohibited by it's license.

More information about Rar and UnRar can be found at http://www.rarlabs.com/.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Installazione

Rar is currently available through PECL http://pecl.php.net/package/rar.

Also you can use the pear installer to install the Rar extension, using the following command: pear -v install rar.

You can always download the tar.gz package and install Rar by hand:

Esempio 1. Rar installation

gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install

Windows users can download the extension dll php_rar.dll here: http://snaps.php.net/win32/PECL_STABLE/.


Tipi di risorse

There is one resource used in Rar extension: a file descriptor returned by rar_open().


Costanti predefinite

RAR_HOST_MSDOS (integer)

RAR_HOST_OS2 (integer)

RAR_HOST_WIN32 (integer)

RAR_HOST_UNIX (integer)

RAR_HOST_BEOS (integer)


Esempi

Esempio 2. Rar extension overview example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entries = rar_list($rar_file);

foreach ($entries as $entry) {
    echo 'Filename: ' . $entry->getName() . "\n";
    echo 'Packed size: ' . $entry->getPackedSize() . "\n";
    echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";

    $entry->extract('/dir/extract/to/');
}

rar_close($rar_file);

?>

This example opens a Rar file archive and extracts each entry to the specified directory.

Sommario
rar_close -- Close Rar archive and free all resources
rar_entry_get -- Get entry object from the Rar archive
Rar::extract -- Extract entry from the archive
Rar::getAttr -- Get attributes of the entry
Rar::getCrc -- Get CRC of the entry
Rar::getFileTime -- Get entry last modification time
Rar::getHostOs -- Get entry host OS
Rar::getMethod -- Get pack method of the entry
Rar::getName -- Get name of the entry
Rar::getPackedSize -- Get packed size of the entry
Rar::getUnpackedSize -- Get unpacked size of the entry
Rar::getVersion -- Get version of the archiver used to add the entry
rar_list -- Get entries list from the Rar archive
rar_open -- Open Rar archive

rar_close

(no version information, might be only in CVS)

rar_close -- Close Rar archive and free all resources

Description

bool rar_close ( resource rar_file )

Close Rar archive and free all allocated resources.

rar_close() returns FALSE on error.

rar_entry_get

(no version information, might be only in CVS)

rar_entry_get -- Get entry object from the Rar archive

Description

RarEntry rar_entry_get ( resource rar_file, string entry_name )

Get entry object from the Rar archive.

Esempio 1. Rar::() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

print_r($entry);

?>

rar_get_entry() returns entry object or FALSE on error.

Rar::extract

(no version information, might be only in CVS)

Rar::extract -- Extract entry from the archive

Description

bool Rar::extract ( string dir [, string filepath] )

Rar::extract() extracts entry's data to the dir. It will create new file in the specified dir with the name identical to the entry's name. If parameter filepath is specified instead dir, Rar::extract() will extract entry's data to the specified file.

Esempio 1. Rar::extract() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

$entry->extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Rar::getAttr

(no version information, might be only in CVS)

Rar::getAttr -- Get attributes of the entry

Description

int Rar::getAttr ( void )

Rar::getAttr() returns attributes of the archive entry.

Esempio 1. Rar::getAttr() example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry");

$host_os = $entry->getHostOs();
$attr = $entry->getAttr();

switch($host_os) {
    case RAR_HOST_MSDOS:
    case RAR_HOST_OS2:
    case RAR_HOST_WIN32:
    case RAR_HOST_MACOS:
        printf("%c%c%c%c%c%c\n",
                ($attr & 0x08) ? 'V' : '.',
                ($attr & 0x10) ? 'D' : '.',
                ($attr & 0x01) ? 'R' : '.',
                ($attr & 0x02) ? 'H' : '.',
                ($attr & 0x04) ? 'S' : '.',
                ($attr & 0x20) ? 'A' : '.');
        break;
    case RAR_HOST_UNIX:
    case RAR_HOST_BEOS:
        switch ($attr & 0xF000)
        {
            case 0x4000:
                printf("d");
                break;
            case 0xA000:
                printf("l");
                break;
            default:
                printf("-");
                break;
        }
        printf("%c%c%c%c%c%c%c%c%c\n",
                ($attr & 0x0100) ? 'r' : '-',
                ($attr & 0x0080) ? 'w' : '-',
                ($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),
                ($attr & 0x0020) ? 'r' : '-',
                ($attr & 0x0010) ? 'w' : '-',
                ($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),
                ($attr & 0x0004) ? 'r' : '-',
                ($attr & 0x0002) ? 'w' : '-',
                ($attr & 0x0001) ? 'x' : '-');
        break;
}

rar_close($rar_file);

?>

Rar::getAttr() returns FALSE on error.

See also Rar::getHostOs().

Rar::getCrc

(no version information, might be only in CVS)

Rar::getCrc -- Get CRC of the entry

Description

int Rar::getCrc ( void )

Rar::getCrc() returns CRC of the archive entry.

Esempio 1. Rar::getCrc() example

<?php

?>

Rar::getCrc() returns FALSE on error.

Rar::getFileTime

(no version information, might be only in CVS)

Rar::getFileTime -- Get entry last modification time

Description

string Rar::getFileTime ( void )

Rar::getFileTime() returns entry last modification time as string in format YYYY-MM-DD HH:II:SS.

Esempio 1. Rar::() example

<?php

?>

Rar::getFileTime() returns FALSE on error.

Rar::getHostOs

(no version information, might be only in CVS)

Rar::getHostOs -- Get entry host OS

Description

int Rar::getHostOs ( void )

Rar::getHostOs() return code of the host OS of the archive entry.

Esempio 1. Rar::getHostOs() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
    case RAR_HOST_MSDOS:
        echo "MS-DOS\n";
        break;
    case RAR_HOST_OS2:
        echo "OS2\n";
        break;
    case RAR_HOST_WIN32:
        echo "Win32\n";
        break;
    case RAR_HOST_MACOS:
        echo "MacOS\n";
        break;
    case RAR_HOST_UNIX:
        echo "Unix/Linux\n";
        break;
    case RAR_HOST_BEOS:
        echo "BeOS\n";
        break;
}

?>

Rar::getHostOs() returns FALSE on error.

Rar::getMethod

(no version information, might be only in CVS)

Rar::getMethod -- Get pack method of the entry

Description

int Rar::getMethod ( void )

Rar::getMethod() returns number of the method used when adding current archive entry.

Esempio 1. Rar::getMethod() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Method number: " . $entry->getMethod();

?>

Rar::getMethod() returns FALSE on error.

Rar::getName

(no version information, might be only in CVS)

Rar::getName -- Get name of the entry

Description

string Rar::getName ( void )

Rar::getName() returns full name of the archive entry.

Esempio 1. Rar::getName() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Entry name: " . $entry->getName();

?>

Rar::getName() returns FALSE on error.

Rar::getPackedSize

(no version information, might be only in CVS)

Rar::getPackedSize -- Get packed size of the entry

Description

int Rar::getPackedSize ( void )

Get packed size of the archive entry.

Esempio 1. Rar::() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Packed size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

Rar::getPackedSize() returns FALSE on error.

Rar::getUnpackedSize

(no version information, might be only in CVS)

Rar::getUnpackedSize -- Get unpacked size of the entry

Description

int Rar::getUnpackedSize ( void )

Get unpacked size of the archive entry.

Esempio 1. Rar::getUnpackedSize() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Unpacked size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

Rar::getUnpackedSize() returns FALSE on error.

Rar::getVersion

(no version information, might be only in CVS)

Rar::getVersion -- Get version of the archiver used to add the entry

Description

int Rar::getVersion ( void )

Get version of the archiver used to add the archive entry.

Esempio 1. Rar::getVersion() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Rar (WinRAR) version used: " . $entry->getVersion();

?>

Rar::getVersion() returns FALSE on error.

rar_list

(no version information, might be only in CVS)

rar_list -- Get entries list from the Rar archive

Description

array rar_list ( resource rar_file )

Get entries list from the Rar archive.

Esempio 1. Rar::() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entries_list = rar_list($rar_file);

print_r($entries_list);

?>

rar_list() returns array of entries or FALSE on error.

rar_open

(no version information, might be only in CVS)

rar_open -- Open Rar archive

Description

resource rar_open ( string filename [, string password] )

Open specified Rar archive and return Rar file resource.

rar_open() returns Rar file resource or FALSE on error.

CXXIII. GNU Readline

Introduzione

The readline() functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts used from a command line.

Nota: Questo modulo non è disponibile su piattaforme Windows.


Requisiti

To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.

You can also use these functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensed and available for download from http://sourceforge.net/projects/libedit/.


Installazione

To use these functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR]. In order you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR].


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
readline_add_history -- Adds a line to the history
readline_callback_handler_install -- Initializes the readline callback interface and terminal, prints the prompt and returns immediately
readline_callback_handler_remove -- Removes a previously installed callback handler and restores terminal settings
readline_callback_read_char -- Reads a character and informs the readline callback interface when a line is received
readline_clear_history -- Clears the history
readline_completion_function -- Registers a completion function
readline_info -- Gets/sets various internal readline variables
readline_list_history -- Lists the history
readline_on_new_line --  Inform readline that the cursor has moved to a new line
readline_read_history -- Reads the history
readline_redisplay --  Ask readline to redraw the display
readline_write_history -- Writes the history
readline -- Reads a line

readline_add_history

(PHP 4, PHP 5)

readline_add_history -- Adds a line to the history

Description

bool readline_add_history ( string line )

This function adds a line to the command line history.

readline_callback_handler_install

(PHP 5 >= 5.1.0RC1)

readline_callback_handler_install -- Initializes the readline callback interface and terminal, prints the prompt and returns immediately

Descrizione

bool readline_callback_handler_install ( string prompt, callback callback )

Sets up a readline callback interface then prints prompt and immediately returns. The callback function takes one parameter; the user input returned. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.

The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Readline Callback Interface Example

<?php
function rl_callback($ret)
{
    global $c, $prompting;

    echo "You entered: $ret\n";
    $c++;

    if ($c > 10) {
        $prompting = false;
        readline_callback_handler_remove();
    } else {
        readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
    }
}

$c = 1;
$prompting = true;

readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');

while ($prompting) {
    $n = stream_select($r = array(STDIN), $w = null, $e = null, null);
    if ($n && in_array(STDIN, $r)) {
        // read a character, will call the callback when a newline is entered
        readline_callback_read_char();
    }
}

echo "Prompting disabled. All done.\n";
?>

readline_callback_handler_remove

(PHP 5 >= 5.1.0RC1)

readline_callback_handler_remove -- Removes a previously installed callback handler and restores terminal settings

Descrizione

bool readline_callback_handler_remove ( void )

Removes a previously installed callback handler and restores terminal settings.

Esempi

See readline_callback_handler_install() for an example of how to use the readline callback interface.

Valori restituiti

Returns TRUE if a previously installed callback handler was removed, or FALSE if one could not be found.

readline_callback_read_char

(PHP 5 >= 5.1.0RC1)

readline_callback_read_char -- Reads a character and informs the readline callback interface when a line is received

Descrizione

void readline_callback_read_char ( void )

Reads a character of user input. When a line is received, this function informs the readline callback interface installed using readline_callback_handler_install() that a line is ready for input.

Esempi

See readline_callback_handler_install() for an example of how to use the readline callback interface.

readline_clear_history

(PHP 4, PHP 5)

readline_clear_history -- Clears the history

Description

bool readline_clear_history ( void )

This function clears the entire command line history.

readline_completion_function

(PHP 4, PHP 5)

readline_completion_function -- Registers a completion function

Description

bool readline_completion_function ( callback function )

This function registers a completion function. You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

readline_info

(PHP 4, PHP 5)

readline_info -- Gets/sets various internal readline variables

Description

mixed readline_info ( [string varname [, string newvalue]] )

If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one parameter, the value of that setting is returned. If called with two parameters, the setting will be changed to the given value.

readline_list_history

(PHP 4, PHP 5)

readline_list_history -- Lists the history

Description

array readline_list_history ( void )

This function returns an array of the entire command line history. The elements are indexed by integers starting at zero.

readline_on_new_line

(PHP 5 >= 5.1.0RC1)

readline_on_new_line --  Inform readline that the cursor has moved to a new line

Description

void readline_on_new_line ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

readline_read_history

(PHP 4, PHP 5)

readline_read_history -- Reads the history

Description

bool readline_read_history ( [string filename] )

This function reads a command history from a file.

readline_redisplay

(PHP 5 >= 5.1.0RC1)

readline_redisplay --  Ask readline to redraw the display

Description

void readline_redisplay ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

readline_write_history

(PHP 4, PHP 5)

readline_write_history -- Writes the history

Description

bool readline_write_history ( [string filename] )

This function writes the command history to a file.

readline

(PHP 4, PHP 5)

readline -- Reads a line

Description

string readline ( string prompt )

This function returns a single string from the user. You may specify a string with which to prompt the user. The line returned has the ending newline removed. You must add this line to the history yourself using readline_add_history().

Esempio 1. readline()

<?php
//get 3 commands from user
for ($i=0; $i < 3; $i++) {
        $line = readline("Command: ");
        readline_add_history($line);
}

//dump history
print_r(readline_list_history());

//dump variables
print_r(readline_info());
?>

CXXIV. GNU Recode Functions

Introduzione

This module contains an interface to the GNU Recode library. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most RFC 1345 character sets are supported.

Nota: Questo modulo non è disponibile su piattaforme Windows.


Requisiti

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from http://directory.fsf.org/All_GNU_Packages/recode.html.

Avvertimento

The Recode library version 3.6 adds weird characters behind converted strings under certain circumstances. Thus it's safer to use Recode v3.5 or one of the available alternatives like the iconv or mbstring extension.


Installazione

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Avvertimento

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proved to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own hash_lookup() function and both mysql and recode have their own hash_insert function.

Avvertimento

Il modulo IMAP non può essere utilizzato in congiunzione con i moduli recode, YAZ oppure Cyrus. Poichè questi moduli condividono i medesimi simboli interni.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
recode_file --  Recode from file to file according to recode request
recode_string -- Recode a string according to a recode request
recode -- Alias di recode_string()

recode_file

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

recode_file --  Recode from file to file according to recode request

Description

bool recode_file ( string request, resource input, resource output )

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request. Returns FALSE, if unable to comply, TRUE otherwise.

This function does not currently process filehandles referencing remote files (URLs). Both filehandles must refer to local files.

Esempio 1. Basic recode_file() example

<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>

recode_string

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

recode_string -- Recode a string according to a recode request

Description

string recode_string ( string request, string string )

Recode the string string according to the recode request request. Returns the recoded string or FALSE, if unable to perform the recode request.

A simple recode request may be "lat1..iso646-de". See also the GNU Recode documentation of your installation for detailed instructions about recode requests.

Esempio 1. Basic recode_string() example:

<?php
echo recode_string("us..flat", "The following character has a diacritical mark: &aacute;");
?>

recode

(PHP 4, PHP 5)

recode -- Alias di recode_string()

Descrizione

This function is an alias of: recode_string().

CXXV. RPM Header Reading Funzioni

Introduzione

This module allows you to read the meta information stored in the headers of a RedHat Package Manager (RPM) file.


Requisiti

The RPMReader extension requires PHP 5.


Installazione

RPMReader is not bundled with PHP. It is a PECL extension and can be located here: http://pecl.php.net/package/rpmreader.

To enable extname support, configure PHP with --with-rpmreader


Tipi di risorse

There is one resource type used by the RPMReader module. The resource is a file pointer which identifies the RPM file with which to work.


Costanti predefinite

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 list of constants are used to obtain information using the rpm_get_tag() function. These constants represent the tag number to be retrieved from the RPM file's header section. Descriptions are given below as to what data the tag number constants reference.

RPMREADER_MINIMUM (integer)

The minimum valid value of any RPM tag number.

RPMREADER_NAME (integer)

The name of the RPM package.

RPMREADER_VERSION (integer)

The version of the RPM package.

RPMREADER_RELEASE (integer)

The release of the RPM package.

RPMREADER_EPOCH (integer)

RPMREADER_SERIAL (integer)

RPMREADER_SUMMARY (integer)

The summary text of the RPM package.

RPMREADER_DESCRIPTION (integer)

The full description text of the RPM package.

RPMREADER_BUILDTIME (integer)

The date and time when the RPM package was built.

RPMREADER_BUILDHOST (integer)

The name of the host on which the RPM package was built.

RPMREADER_INSTALLTIME (integer)

RPMREADER_SIZE (integer)

The size of the RPM package.

RPMREADER_DISTRIBUTION (integer)

RPMREADER_VENDOR (integer)

RPMREADER_GIF (integer)

RPMREADER_XPM (integer)

RPMREADER_LICENSE (integer)

RPMREADER_COPYRIGHT (integer)

RPMREADER_PACKAGER (integer)

RPMREADER_GROUP (integer)

RPMREADER_SOURCE (integer)

RPMREADER_PATCH (integer)

RPMREADER_URL (integer)

RPMREADER_OS (integer)

RPMREADER_ARCH (integer)

RPMREADER_PREIN (integer)

RPMREADER_POSTIN (integer)

RPMREADER_PREUN (integer)

RPMREADER_POSTUN (integer)

RPMREADER_OLDFILENAMES (integer)

The list of files in an RPM package (deprecated format). The correct way is now to use a combination of 3 tags (RPMREADER_BASENAMES, RPMREADER_DIRINDEXES, RPMREADER_DIRNAMES) in what RPM now calls "CompressedFileNames". This tag is still used in older RPM files that did not use the "CompressedFileNames" method and is maintained for backward compatibility.

RPMREADER_FILESIZES (integer)

RPMREADER_FILESTATES (integer)

RPMREADER_FILEMODES (integer)

RPMREADER_FILERDEVS (integer)

RPMREADER_FILEMTIMES (integer)

RPMREADER_FILEMD5S (integer)

RPMREADER_FILELINKTOS (integer)

RPMREADER_FILEFLAGS (integer)

RPMREADER_FILEUSERNAME (integer)

RPMREADER_FILEGROUPNAME (integer)

RPMREADER_ICON (integer)

RPMREADER_SOURCERPM (integer)

RPMREADER_FILEVERIFYFLAGS (integer)

RPMREADER_ARCHIVESIZE (integer)

RPMREADER_PROVIDENAME (integer)

RPMREADER_PROVIDES (integer)

RPMREADER_REQUIREFLAGS (integer)

RPMREADER_REQUIRENAME (integer)

RPMREADER_REQUIREVERSION (integer)

RPMREADER_CONFLICTFLAGS (integer)

RPMREADER_CONFLICTNAME (integer)

RPMREADER_CONFLICTVERSION (integer)

RPMREADER_EXCLUDEARCH (integer)

RPMREADER_EXCLUDEOS (integer)

RPMREADER_EXCLUSIVEARCH (integer)

RPMREADER_EXCLUSIVEOS (integer)

RPMREADER_RPMVERSION (integer)

RPMREADER_TRIGGERSCRIPTS (integer)

RPMREADER_TRIGGERNAME (integer)

RPMREADER_TRIGGERVERSION (integer)

RPMREADER_TRIGGERFLAGS (integer)

RPMREADER_TRIGGERINDEX (integer)

RPMREADER_VERIFYSCRIPT (integer)

RPMREADER_CHANGELOGTIME (integer)

The list of dates from changelog entries.

RPMREADER_CHANGELOGNAME (integer)

The list of changelog entry names.

RPMREADER_CHANGELOGTEXT (integer)

The list of the text from changelog entries.

RPMREADER_PREINPROG (integer)

RPMREADER_POSTINPROG (integer)

RPMREADER_PREUNPROG (integer)

RPMREADER_POSTUNPROG (integer)

RPMREADER_BUILDARCHS (integer)

RPMREADER_OBSOLETENAME (integer)

RPMREADER_OBSOLETES (integer)

RPMREADER_VERIFYSCRIPTPROG (integer)

RPMREADER_TRIGGERSCRIPTPROG (integer)

RPMREADER_COOKIE (integer)

RPMREADER_FILEDEVICES (integer)

RPMREADER_FILEINODES (integer)

RPMREADER_FILELANGS (integer)

RPMREADER_PREFIXES (integer)

RPMREADER_INSTPREFIXES (integer)

RPMREADER_PROVIDEFLAGS (integer)

RPMREADER_PROVIDEVERSION (integer)

RPMREADER_OBSOLETEFLAGS (integer)

RPMREADER_OBSOLETEVERSION (integer)

RPMREADER_DIRINDEXES (integer)

The list of indices that relate directory names to files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.

RPMREADER_BASENAMES (integer)

The list of the names of files in the RPM package without path information. This tag is used in conjunction with RPMREADER_DIRINDEXES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.

RPMREADER_DIRNAMES (integer)

The list of directory names used by files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRINDEXES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.

RPMREADER_OPTFLAGS (integer)

RPMREADER_DISTURL (integer)

RPMREADER_PAYLOADFORMAT (integer)

RPMREADER_PAYLOADCOMPRESSOR (integer)

RPMREADER_PAYLOADFLAGS (integer)

RPMREADER_INSTALLCOLOR (integer)

RPMREADER_INSTALLTID (integer)

RPMREADER_REMOVETID (integer)

RPMREADER_RHNPLATFORM (integer)

RPMREADER_PLATFORM (integer)

RPMREADER_PATCHESNAME (integer)

RPMREADER_PATCHESFLAGS (integer)

RPMREADER_PATCHESVERSION (integer)

RPMREADER_CACHECTIME (integer)

RPMREADER_CACHEPKGPATH (integer)

RPMREADER_CACHEPKGSIZE (integer)

RPMREADER_CACHEPKGMTIME (integer)

RPMREADER_FILECOLORS (integer)

RPMREADER_FILECLASS (integer)

RPMREADER_CLASSDICT (integer)

RPMREADER_FILEDEPENDSX (integer)

RPMREADER_FILEDEPENDSN (integer)

RPMREADER_DEPENDSDICT (integer)

RPMREADER_SOURCEPKGID (integer)

RPMREADER_FILECONTEXTS (integer)

RPMREADER_FSCONTEXTS (integer)

RPMREADER_RECONTEXTS (integer)

RPMREADER_POLICIES (integer)

RPMREADER_MAXIMUM (integer)

The maximum valid value of any RPM tag number.


Esempi

This example will open an RPM file and read the name, version, and release from the RPM file, echo the results, and close the RPM file.

Esempio 1. Basic RPMReader Example

<?php

$filename = "/path/to/file.rpm";

// open file
$rpmr = rpm_open($filename);

// get "Name" tag
$name = rpm_get_tag($rpmr, RPMREADER_NAME);

// get "Version" tag
$ver = rpm_get_tag($rpmr, RPMREADER_VERSION);

// get "Release" tag
$rel = rpm_get_tag($rpmr, RPMREADER_RELEASE);

echo "$name-$ver-$rel<br>\n";

// close file
rpm_close($rpmr);

?>
Sommario
rpm_close -- Closes an RPM file
rpm_get_tag -- Retrieves a header tag from an RPM file
rpm_is_valid -- Tests a filename for validity as an RPM file
rpm_open -- Opens an RPM file

rpm_close

(no version information, might be only in CVS)

rpm_close -- Closes an RPM file

Descrizione

boolean rpm_close ( resource rpmr )

rpm_close() will close an RPM file pointer.

Elenco dei parametri

rpmr

A file pointer resource successfully opened by rpm_open().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. rpm_close() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

Vedere anche:

rpm_open()

rpm_get_tag

(no version information, might be only in CVS)

rpm_get_tag -- Retrieves a header tag from an RPM file

Descrizione

mixed rpm_get_tag ( resource rpmr, int tagnum )

rpm_get_tag() will retrieve a given tag from the RPM file's header and return it.

Elenco dei parametri

rpmr

A file pointer resource successfully opened by rpm_open().

tagnum

The tag number to retrieve from the RPM header. This value can be specified using the list of constants defined by this module.

Valori restituiti

The return value can be of various types depending on the tagnum supplied to the function.

Esempi

Esempio 1. rpm_get_tag() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

$name = rpm_get_tag($rpmr, RPMREADER_NAME);
echo "$name<br>\n";

rpm_close($rpmr);

?>

Vedere anche:

rpm_open()
rpm_close()

rpm_is_valid

(no version information, might be only in CVS)

rpm_is_valid -- Tests a filename for validity as an RPM file

Descrizione

boolean rpm_is_valid ( string filename )

rpm_is_valid() will test an RPM file for validity as an RPM file. This is not the same as rpm_open() as it only checks the file for validity but does not return a file pointer to be used by further functions.

Elenco dei parametri

filename

The filename of the RPM file you wish to check for validity.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. rpm_is_valid() example

<?php

$file = "/path/to/file.rpm";

if (rpm_is_valid($file)) {
    echo "File is recognized as an RPM file.<br>\n";
}
else {
    echo "File is not recognized as an RPM file.<br>\n";
}

?>

rpm_open

(no version information, might be only in CVS)

rpm_open -- Opens an RPM file

Descrizione

resource rpm_open ( string filename )

rpm_open() will open an RPM file and will determine if the file is a valid RPM file.

Elenco dei parametri

filename

The filename of the RPM file you wish to open.

Valori restituiti

If the open succeeds, then rpm_open() will return a file pointer resource to the newly opened file. On error, the function will return FALSE.

Esempi

Esempio 1. rpm_open() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

Vedere anche:

rpm_close()

CXXVI. runkit Functions

Introduzione

The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.

Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/runkit.

This package is meant as a feature added replacement for the classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.


Requisiti

Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.

Custom Superglobals are only available in PHP 4.2.0 or later.

Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Runkit Configuration Options

NameDefaultChangeableChangelog
runkit.superglobal PHP_INI_PERDIR 
runkit.internal_override PHP_INI_SYSTEM 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

runkit.superglobal string

Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

Esempio 1. Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini

<?php
function show_values() {
  echo "Foo is $_FOO\n";
  echo "Bar is $_BAR\n";
  echo "Baz is $_BAZ\n";
}

$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';

/* Displays foo and bar, but not baz */
show_values();
?>


Costanti predefinite

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.

RUNKIT_IMPORT_FUNCTIONS (integer)

runkit_import() flag indicating that normal functions should be imported from the specified file.

RUNKIT_IMPORT_CLASS_METHODS (integer)

runkit_import() flag indicating that class methods should be imported from the specified file.

RUNKIT_IMPORT_CLASS_CONSTS (integer)

runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.

RUNKIT_IMPORT_CLASS_PROPS (integer)

runkit_import() flag indicating that class standard properties should be imported from the specified file.

RUNKIT_IMPORT_CLASSES (integer)

runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.

RUNKIT_IMPORT_OVERRIDE (integer)

runkit_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.

RUNKIT_ACC_PUBLIC (integer)

PHP5 specific flag to runkit_method_add()

RUNKIT_ACC_PROTECTED (integer)

PHP5 specific flag to runkit_method_add()

RUNKIT_ACC_PRIVATE (integer)

PHP5 specific flag to runkit_method_add()

CLASSKIT_ACC_PUBLIC (integer)

PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.

CLASSKIT_ACC_PROTECTED (integer)

PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.

CLASSKIT_ACC_PRIVATE (integer)

PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.

CLASSKIT_AGGREGATE_OVERRIDE (integer)

PHP5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.

RUNKIT_VERSION (string)

Defined to the current version of the runkit package.

CLASSKIT_VERSION (string)

Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.

Sommario
Runkit_Sandbox --  Runkit Sandbox Class -- PHP Virtual Machine
Runkit_Sandbox_Parent --  Runkit Anti-Sandbox Class
runkit_class_adopt --  Convert a base class to an inherited class, add ancestral methods when appropriate
runkit_class_emancipate --  Convert an inherited class to a base class, removes any method whose scope is ancestral
runkit_constant_add --  Similar to define(), but allows defining in class definitions as well
runkit_constant_redefine --  Redefine an already defined constant
runkit_constant_remove --  Remove/Delete an already defined constant
runkit_function_add --  Add a new function, similar to create_function()
runkit_function_copy --  Copy a function to a new function name
runkit_function_redefine --  Replace a function definition with a new implementation
runkit_function_remove --  Remove a function definition
runkit_function_rename --  Change a function's name
runkit_import --  Process a PHP file importing function and class definitions, overwriting where appropriate
runkit_lint_file --  Check the PHP syntax of the specified file
runkit_lint --  Check the PHP syntax of the specified php code
runkit_method_add -- Dynamically adds a new method to a given class
runkit_method_copy -- Copies a method from class to another
runkit_method_redefine -- Dynamically changes the code of the given method
runkit_method_remove -- Dynamically removes the given method
runkit_method_rename -- Dynamically changes the name of the given method
runkit_sandbox_output_handler --  Specify a function to capture and/or process output from a runkit sandbox
runkit_superglobals --  Return numerically indexed array of registered superglobals

Runkit_Sandbox

(no version information, might be only in CVS)

Runkit_Sandbox --  Runkit Sandbox Class -- PHP Virtual Machine

Descrizione

Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.

Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Constructor

void Runkit_Sandbox::__construct ( [array options] )

options is an associative array containing any combination of the special ini options listed below.

safe_mode

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.

safe_mode_gid

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.

safe_mode_include_dir

If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.

open_basedir

open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.

allow_url_fopen

Like safe_mode, this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE

disable_functions

Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.

disable_classes

Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.

runkit.superglobal

Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.

runkit.internal_override

Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.

Esempio 1. Instantiating a restricted sandbox

<?php
$options = array(
  'safe_mode'=>true,
  'open_basedir'=>'/var/www/users/jdoe/',
  'allow_url_fopen'=>'false',
  'disable_functions'=>'exec,shell_exec,passthru,system',
  'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>

Accessing Variables

All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.

Esempio 2. Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();

$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>

Il precedente esempio visualizzerà:

bar
barbaz
bool(false)

Calling PHP Functions

Any function defined within the sandbox may be called as a method on the sandbox object. This also includes a few pseudo-function language constructs: eval(), include(), include_once(), require(), require_once(), echo(), print(), die(), and exit().

Esempio 3. Calling sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

echo $sandbox->str_replace('a','f','abc');
?>

Il precedente esempio visualizzerà:

fbc

When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.

Esempio 4. Passing arguments to sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>

Il precedente esempio visualizzerà:

bar
baz

Changing Sandbox Settings

As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.

Tabella 1. Sandbox Settings / Status Indicators

SettingTypePurposeDefault
activeBoolean (Read Only) TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. TRUE (Initial)
output_handlerCallback When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. None
parent_accessBoolean May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. FALSE
parent_readBoolean May the sandbox read variables in its parent's context? FALSE
parent_writeBoolean May the sandbox modify variables in its parent's context? FALSE
parent_evalBoolean May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS FALSE
parent_includeBoolean May the sandbox include php code files in its parent's context? DANGEROUS FALSE
parent_echoBoolean May the sandbox echo data in its parent's context effectively bypassing its own output_handler? FALSE
parent_callBoolean May the sandbox call functions in its parent's context? FALSE
parent_dieBoolean May the sandbox kill its own parent? (And thus itself) FALSE
parent_scopeInteger What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceeding calling scope, 3 == The scope before that, etc..., etc... 0 (Global)

Runkit_Sandbox_Parent

(no version information, might be only in CVS)

Runkit_Sandbox_Parent --  Runkit Anti-Sandbox Class

Descrizione

void Runkit_Sandbox_Parent::__construct ( void )

Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.

Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.

Esempio 1. Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;

Accessing the Parent's Variables

Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.

Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.

Esempio 2. Accessing parental variables

<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test = "Global";

$php->eval('$PARENT = new Runkit_Sandbox_Parent;');

$php['parent_scope'] = 0;
one();

$php['parent_scope'] = 1;
one();

$php['parent_scope'] = 2;
one();

$php['parent_scope'] = 3;
one();

$php['parent_scope'] = 4;
one();

$php['parent_scope'] = 5;
one();

function one() {
    $test = "one()";
    two();
}

function two() {
    $test = "two()";
    three();
}

function three() {
    $test = "three()";
    $GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>

Il precedente esempio visualizzerà:

string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"

Calling the Parent's Functions

Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print() and echo() are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include(), include_once(), require(), and require_once() are enabled through parent_include.

runkit_class_adopt

(PECL)

runkit_class_adopt --  Convert a base class to an inherited class, add ancestral methods when appropriate

Descrizione

bool runkit_class_adopt ( string classname, string parentname )

Elenco dei parametri

classname

Name of class to be adopted

parentname

Parent class which child class is extending

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A runkit_class_adopt() example

<?php
class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>

Il precedente esempio visualizzerà:

Parent Function Output

runkit_class_emancipate

(PECL)

runkit_class_emancipate --  Convert an inherited class to a base class, removes any method whose scope is ancestral

Descrizione

bool runkit_class_emancipate ( string classname )

Elenco dei parametri

classname

Name of class to emancipate

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A runkit_class_emancipate() example

<?php
class myParent {
  function parentFunc () {
    echo "Parent Function Output\n";
  }
}
class myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>

Il precedente esempio visualizzerà:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

Vedere anche:

runkit_class_adopt()

runkit_constant_add

(PECL)

runkit_constant_add --  Similar to define(), but allows defining in class definitions as well

Descrizione

bool runkit_constant_add ( string constname, mixed value )

Elenco dei parametri

constname

Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.

value

NULL, Bool, Long, Double, String, or Resource value to store in the new constant.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

runkit_constant_redefine

(PECL)

runkit_constant_redefine --  Redefine an already defined constant

Descrizione

bool runkit_constant_redefine ( string constname, mixed newvalue )

Elenco dei parametri

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

runkit_constant_remove

(PECL)

runkit_constant_remove --  Remove/Delete an already defined constant

Descrizione

bool runkit_constant_remove ( string constname )

Elenco dei parametri

constname

Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

runkit_function_add

(PECL)

runkit_function_add --  Add a new function, similar to create_function()

Descrizione

bool runkit_function_add ( string funcname, string arglist, string code )

Elenco dei parametri

funcname

Name of function to be created

arglist

Comma separated argument list

code

Code making up the function

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A runkit_function_add() example

<?php
create_function('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>

Il precedente esempio visualizzerà:

The value of a is 1
The value of b is 2

runkit_function_copy

(PECL)

runkit_function_copy --  Copy a function to a new function name

Descrizione

bool runkit_function_copy ( string funcname, string targetname )

Elenco dei parametri

funcname

Name of existing function

targetname

Name of new function to copy definition to

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A runkit_function_copy() example

<?php
function original() {
  echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

Il precedente esempio visualizzerà:

In a function
In a function

runkit_function_redefine

(PECL)

runkit_function_redefine --  Replace a function definition with a new implementation

Descrizione

bool runkit_function_redefine ( string funcname, string arglist, string code )

Elenco dei parametri

funcname

Name of function to redefine

arglist

New list of arguments to be accepted by function

code

New code implementation

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A runkit_function_redefine() example

<?php
function testme() {
  echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

Il precedente esempio visualizzerà:

Original Testme Implementation
New Testme Implementation

runkit_function_remove

(PECL)

runkit_function_remove --  Remove a function definition

Descrizione

bool runkit_function_remove ( string funcname )

Elenco dei parametri

funcname

Name of function to be deleted

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

runkit_function_rename

(PECL)

runkit_function_rename --  Change a function's name

Descrizione

bool runkit_function_rename ( string funcname, string newname )

Elenco dei parametri

funcname

Current function name

newname

New function name

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

runkit_import

(PECL)

runkit_import --  Process a PHP file importing function and class definitions, overwriting where appropriate

Descrizione

bool runkit_import ( string filename [, int flags] )

Similar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags, any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.

Elenco dei parametri

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT_IMPORT_* family of constants.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

runkit_lint_file

(PECL)

runkit_lint_file --  Check the PHP syntax of the specified file

Descrizione

bool runkit_lint_file ( string filename )

The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.

Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Elenco dei parametri

filename

File containing PHP Code to be lint checked

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

runkit_lint()

runkit_lint

(PECL)

runkit_lint --  Check the PHP syntax of the specified php code

Descrizione

bool runkit_lint ( string code )

The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the commandline except runkit_lint() accepts actual code rather than a filename.

Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Elenco dei parametri

code

PHP Code to be lint checked

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

runkit_lint_file()

runkit_method_add

(PECL)

runkit_method_add -- Dynamically adds a new method to a given class

Descrizione

bool runkit_method_add ( string classname, string methodname, string args, string code [, int flags] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Elenco dei parametri

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. runkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
runkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    RUNKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

Il precedente esempio visualizzerà:

16

runkit_method_copy

(PECL)

runkit_method_copy -- Copies a method from class to another

Descrizione

bool runkit_method_copy ( string dClass, string dMethod, string sClass [, string sMethod] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Elenco dei parametri

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. runkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

Il precedente esempio visualizzerà:

foo!

runkit_method_redefine

(PECL)

runkit_method_redefine -- Dynamically changes the code of the given method

Descrizione

bool runkit_method_redefine ( string classname, string methodname, string args, string code [, int flags] )

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.

Elenco dei parametri

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE

Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. runkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

Il precedente esempio visualizzerà:

Before: foo!
After: bar!

runkit_method_remove

(PECL)

runkit_method_remove -- Dynamically removes the given method

Descrizione

bool runkit_method_remove ( string classname, string methodname )

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.

Elenco dei parametri

classname

The class in which to remove the method

methodname

The name of the method to remove

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. runkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
    
    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
runkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

Il precedente esempio visualizzerà:

bar

runkit_method_rename

(PECL)

runkit_method_rename -- Dynamically changes the name of the given method

Descrizione

bool runkit_method_rename ( string classname, string methodname, string newname )

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.

Elenco dei parametri

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. runkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
runkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

Il precedente esempio visualizzerà:

foo!

runkit_sandbox_output_handler

(PECL)

runkit_sandbox_output_handler --  Specify a function to capture and/or process output from a runkit sandbox

Descrizione

mixed runkit_sandbox_output_handler ( object sandbox [, mixed callback] )

Ordinarily, anything output (such as with echo() or print()) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.

Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Deprecated: As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.

Elenco dei parametri

sandbox

Object instance of Runkit_Sandbox class on which to set output handling.

callback

Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.

Valori restituiti

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

Esempi

Esempio 1. Feeding output to a variable

<?php
function capture_output($str) {
  $GLOBALS['sandbox_output'] .= $str;

  return '';
}

$sandbox_output = '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);

echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>

Il precedente esempio visualizzerà:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.

runkit_superglobals

(PECL)

runkit_superglobals --  Return numerically indexed array of registered superglobals

Descrizione

array runkit_superglobals ( void )

Valori restituiti

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

Vedere anche:

Variable Scope

CXXVII. Satellite CORBA client extension [deprecated]

Introduzione

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 non è disponibile su piattaforme Windows.

Satellite is deprecated. It is suggested that you use Universe (http://universe-phpext.sourceforge.net/) and not Satellite.

The Satellite extension is used for accessing CORBA objects. You will need to set the idl_directory= entry in php.ini to a path where you store all IDL files you use.

See the Satellite README file for details about installing Satellite.

Sommario
OrbitEnum -- Use CORBA enums
OrbitObject -- Access CORBA objects
OrbitStruct -- Use CORBA structs
satellite_caught_exception -- See if an exception was caught from the previous function
satellite_exception_id -- Get the repository id for the latest exception.
satellite_exception_value -- Get the exception struct for the latest exception
satellite_get_repository_id -- NOT IMPLEMENTED
satellite_load_idl -- Instruct the type manager to load an IDL file
satellite_object_to_string -- Convert an object to its string representation

OrbitEnum

(no version information, might be only in CVS)

OrbitEnum -- Use CORBA enums

Descrizione

new OrbitEnum ( string id )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 class represents the enumeration identified with the id parameter.

Elenco dei parametri

id

Can be either the name of the enumeration (e.g "MyEnum"), or the full repository id (e.g. "IDL:MyEnum:1.0").

Esempi

Esempio 1. Sample IDL file

enum MyEnum {
    a,b,c,d,e
};

Esempio 2. PHP code for accessing MyEnum

<?php
$enum = new OrbitEnum ("MyEnum");

echo $enum->a;	/* write 0 */
echo $enum->c;	/* write 2 */
echo $enum->e;	/* write 4 */
?>

OrbitObject

(no version information, might be only in CVS)

OrbitObject -- Access CORBA objects

Descrizione

new OrbitObject ( string ior )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 class provides access to a CORBA object.

Elenco dei parametri

ior

Should be a string containing the IOR (Interoperable Object Reference) that identifies the remote object.

Esempi

Esempio 1. Sample IDL file

interface MyInterface {
    void SetInfo (string info);
    string GetInfo();

    attribute int value;
}

Esempio 2. PHP code for accessing MyInterface

<?php
$obj = new OrbitObject ($ior);

$obj->SetInfo ("A 2GooD object");

echo $obj->GetInfo();

$obj->value = 42;

echo $obj->value;
?>

OrbitStruct

(no version information, might be only in CVS)

OrbitStruct -- Use CORBA structs

Descrizione

new OrbitStruct ( string id )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 class represents the structure identified with the id parameter.

Elenco dei parametri

id

Can be either the name of the struct (e.g "MyStruct"), or the full repository id (e.g. "IDL:MyStruct:1.0").

Esempi

Esempio 1. Sample IDL file

struct MyStruct {
    short shortvalue;
    string stringvalue;
};

interface SomeInterface {
  void SetValues (MyStruct values);
  MyStruct GetValues();
}

Esempio 2. PHP code for accessing MyStruct

<?php
$obj = new OrbitObject ($ior);

$initial_values = new OrbitStruct ("IDL:MyStruct:1.0");
$initial_values->shortvalue = 42;
$initial_values->stringvalue = "HGTTG";

$obj->SetValues ($initial_values);

$values = $obj->GetValues();

echo $values->shortvalue;
echo $values->stringvalue;
?>

satellite_caught_exception

(4.0.3 - 4.1.2 only, PECL)

satellite_caught_exception -- See if an exception was caught from the previous function

Descrizione

bool satellite_caught_exception ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Valori restituiti

This function returns TRUE if an exception has been caught, FALSE otherwise.

Esempi

Esempio 1. Sample IDL file

/* ++?????++ Out of Cheese Error. Redo From Start. */
exception OutOfCheeseError {
    int parameter;
}

interface AnotherInterface {
    void AskWhy() raises (OutOfCheeseError);
}

Esempio 2. PHP code for handling CORBA exceptions

<?php
$obj = new OrbitObject ($ior);

$obj->AskWhy();

if (satellite_caught_exception()) {
    if ("IDL:OutOfCheeseError:1.0" == satellite_exception_id()) {
        $exception = satellite_exception_value();
        echo $exception->parameter;
    }
}
?>

satellite_exception_id

(4.0.3 - 4.1.2 only, PECL)

satellite_exception_id -- Get the repository id for the latest exception.

Descrizione

string satellite_exception_id ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

For example usage see satellite_caught_exception().

Valori restituiti

Return a repository id string. (E.g. "IDL:MyException:1.0".)

satellite_exception_value

(4.0.3 - 4.1.2 only, PECL)

satellite_exception_value -- Get the exception struct for the latest exception

Descrizione

OrbitStruct satellite_exception_value ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Return an exception struct. For example usage see satellite_caught_exception().

satellite_get_repository_id

(4.0.3 - 4.1.2 only, PECL)

satellite_get_repository_id -- NOT IMPLEMENTED

Descrizione

int satellite_get_repository_id ( object obj )

Not implemented.

satellite_load_idl

(4.0.3 - 4.1.2 only, PECL)

satellite_load_idl -- Instruct the type manager to load an IDL file

Descrizione

bool satellite_load_idl ( string file )

Load an IDL file into Satellite.

satellite_object_to_string

(4.1.0 - 4.1.2 only, PECL)

satellite_object_to_string -- Convert an object to its string representation

Descrizione

string satellite_object_to_string ( object obj )

Convert an object to its string representation (IOR).

CXXVIII. SDO Functions

Introduzione

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.

Service Data Objects (SDOs) enable PHP applications to work with data from different sources (like a database query, an XML file, and a spreadsheet) using a single interface.

Each different kind of data source requires a Data Access Service (DAS) to provide access to the data in the data source. In your PHP application, you use a DAS to create an SDO instance that represents some data in the data source. You can then set and get values in the SDO instance using the standard SDO interface. Finally, you use a DAS to write the modified data back to a data source (typically the same one).

See the list of Data Access Services for details on those currently available. In addition to the provided DASs, SDO also provides interfaces to enable others to be implemented (see the section on SDO Data Access Services Interface for more details).

This extension is derived from concepts taken from the Service Data Objects specification


The Structure of a Service Data Object

A Service Data Object instance is made up of a tree of data objects. The tree is defined by containment references between the data objects. For example, a Company data object might consist of a number of Department data objects and therefore the Company would have a containment reference to the Departments. Deleting a data object which has a containment reference to another data object will delete the referenced data object. For example, deleting the Company data object will also delete the Departments.

An SDO may also have non-containment references between data objects in the tree. For example, one Employee data object might reference another Employee to identify a career mentor. Deleting a data object which has a non-containment reference to another data object does not delete the referenced data object.

As well as data objects referencing each other, they can also have primitive properties. For example, the Company data object might have a property called "name" of type string, for holding the name of the company (for example, "Acme").


Requisiti

The SDO extension requires PHP 5.1 or higher.

SDO XML Data Access Service, which is built as part of this extension, requires libxml2 (Tested with libxml2 2.6.19) which can be downloaded from http://www.xmlsoft.org/.


Installazione

There are several options, depending on whether you are installing on Windows or Linux, and depending on whether you are installing a released version (a .tgz file from the PECL site) or the latest from CVS. The Relational DAS also needs special attention as it is written in PHP.

The instructions are likely to change as PHP 5.1 progresses in status from beta to stable release. The instructions here were correct on 6th October 2005, when PHP 5.1.0RC1 was the current release candidate for PHP, and 0.5.2 was the current beta release of SDO.

The options are summarised in the following table:

latest/ReleaseWindowsLinux
latest CVS

  • The latest DLLs for the SDO core and the XML DAS can be downloaded from php_sdo and php_sdo_das_xml respectively.

  • Check out the Relational DAS from CVS to somewhere on the PHP include_path .

  • Check out the SDO core and the XML DAS from CVS and build according to the instructions below for building on Linux.

  • Check out the Relational DAS from CVS to somewhere on the PHP include_path .

Release

  • There is currently no way provided for building the release version of the SDO core and XML DAS on a user's machine. You will only be able to pick up the latest DLLs from the snaps site (see previous row of this table).

  • The Relational DAS can be downloaded and installed with the command:

    pear install -B <package name and level>

    Substitute the desired package name and level, for example sdo-0.5.2, in the command above.

  • You can download and install all three SDO components - the SDO core, the XML DAS and the Relational DAS - with the command:

    pear install <package name and level>

    Substitute the desired package name and level, for example sdo-0.5.2, in the command above.

    This command will build the SDO and XML shared libraries as well as installing the PHP files that make the Relational DAS.

Regardless of which platform or which level of the code you have installed you will need add the two extension libraries to your php.ini file. On Windows, add:
extension=php_sdo.dll
extension=php_sdo_das_xml.dll
On Linux, add:
extension=sdo.so
extension=sdo_das_xml.so
You may also need to update your extension_dir in php.ini to point to the location of these libraries.

The Relational DAS is written in PHP. You may need to update your include_path in php.ini to point to the directory that contains sdo/DAS/Relational .

Building SDO on Linux

This section describes how to build the SDO core and XML DAS on Linux. Currently you would only need to know how to do this if you wish to build a recent version that you have checked out of CVS.

  1. Change to the main extension directory: cd < wherever your sdo code is >

  2. Run phpize, which will set up the environment to compile both SDO and the XML Data Access Service.

  3. Next, run ./configure; make; make install. Please note, you may need to login as root to install the extension.

  4. Make sure that these modules are loaded by PHP, by adding extension=sdo.so and extension=sdo_das_xml.so to your php.ini file in the same order.


Data Access Services

The table below lists the currently provided SDO Data Access Services:

DAS NameDescription
SDO_DAS_XML An XML Data Access Service supporting reading/writing SDOs as XML documents or via a Web URL to supporting things like RSS feeds.
SDO_DAS_Relational A PDO-based Data Access Service supporting reading/writing SDO to relational data sources. Implements an optimistic concurrency policy for updates.


Limitations

Implementation Limitations

The following are limitations in the current SDO implementation:

  1. There is no support for multi-byte character sets.

SDO Limitations

The following SDO 2.0 concepts are not supported in the current PHP implementation. It is not necessarily the case that these will all be added over time. Their inclusion will depend on community requirements.

  1. Abstract types and type derivation.

  2. Open types.

  3. Bi-directional relationships.

  4. Type and property alias names.

  5. Read-only properties.

  6. Model introspection.

  7. XMLHelper/XSDHelper (the XML DAS provide a lot of this functionality)

  8. TypeHelper (the SDO_DAS_DataFactory provides this functionality)


Esempi

The examples below assume an SDO created with the schema and instance information shown below, using the XML Data Access Service.

The schema describes a company data object. The company contains department data objects, and each department contains employee data objects. Each data object has a number of primitive properties to describe things like name, serial number, etc. Finally, the company data object also has a non-containment reference to one of the employee data objects to identify them as the 'employeeOfTheMonth'.

<xsd:schema  
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:sdo="commonj.sdo"
  xmlns:sdoxml="commonj.sdo/xml"
  xmlns:company="companyNS"
  targetNamespace="companyNS">
  <xsd:element name="company" type="company:CompanyType"/>
  <xsd:complexType name="CompanyType">
    <xsd:sequence>
      <xsd:element name="departments" type="company:DepartmentType" maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="employeeOfTheMonth" type="xsd:IDREF" 
sdoxml:propertyType="company:EmployeeType"/> </xsd:complexType>
  <xsd:complexType name="DepartmentType">
    <xsd:sequence>
      <xsd:element name="employees" type="company:EmployeeType"  maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="location" type="xsd:string"/>
    <xsd:attribute name="number" type="xsd:int"/>
  </xsd:complexType>
  <xsd:complexType name="EmployeeType">
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="SN" type="xsd:ID"/>
    <xsd:attribute name="manager" type="xsd:boolean"/>
  </xsd:complexType>
</xsd:schema>

The instance document below describes a single company, called 'MegaCorp', which contains a single department, called 'Advanced Technologies'. The Advanced Technologies department contains three employees. The company employeeOfTheMonth is referencing the second employee, 'Jane Doe'.

<?xml version="1.0" encoding="UTF-8" ?> 
<company xmlns="companyNS" name="MegaCorp" employeeOfTheMonth="#/departments.0/employees.1">
  <departments name="Advanced Technologies" location="NY" number="123">
    <employees name="John Jones" SN="E0001"/>
    <employees name="Jane Doe" SN="E0003"/>
    <employees name="Al Smith" SN="E0004" manager="true"/>
  </departments>
</company>


Setting and Getting Property Values

The following examples assume $company is a data object created from the schema and instance document shown above.

Esempio 1. Access via Property names

Data object properties can be accessed using the object property access syntax. The following gets the list of departments (containing a single department), and sets the company name to 'Acme'.

<?php
  $departments = $company->departments;
  $company->name = 'Acme';
?>

Esempio 2. Access via Property index

Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema). We can see from the schema listing above that the departments element is the first company property defined and the company name attribute is the second company property (the SDO interface makes no distinction between XML attributes and elements). The following gets the list of departments (containing a single department), and sets the company name to 'Acme'.

<?php
  $departments = $company[0];
  $company[1] = 'Acme';
?>

Esempio 3. Data Object Iteration

We can iterate over the properties of a data object using foreach. The following iterates over the company properties; name, departments and employeeOfTheMonth.

<?php
  foreach ($company as $name => $value) {
    ...
  }
?>

For the first iteration, $name will be 'name' and $value will be 'Acme'. For the second iteration, $name will be 'departments' and $value will be an SDO_List (because departments is a many-valued property (stated maxOccurs="unbouded" in the schema)) containing a single data object of type DepartmentType. For the third iteration, $name will be 'employeeOfTheMonth' and $value will be a data object of type EmployeeType.

Esempio 4. Many-valued Property Iteration

Many-valued properties can also be iterated over using foreach. The following iterates over the company's departments.

<?php
  foreach ($company->departments as $department) {
    ...
  }
?>

Each iteration will assign the next department in the list to the variable $department.

Esempio 5. Many-valued Element Access

We can access individual elements of many-valued properties using array syntax. The following accesses the first department in the company.

<?php
  $ad_tech_dept = $company->departments[0];
?>

Esempio 6. Nested Property Access

We can use nested property access to navigate the data object instance structure. The following gets and sets the name of the first department.

<?php
  $dept_name = $company->departments[0]->name;
  $company->departments[0]->name = 'Emerging Technologies';
?>

Esempio 7. Simple XPath support

We can access properties using XPath-like (an augmented sub-set of XPath) expressions, the simplest form of which is the property name. The following sets the company name and gets the employeeOfTheMonth.

<?php
  $company['name'] = 'UltraCorp';
  $eotm = $company['employeeOfTheMonth'];
?>

Esempio 8. Simple XPath support

We can use chained array access calls to navigate the data object instance structure. The following gets and sets the name of the first department.

<?php
  $dept_name = $company['departments'][0]['name'];
  $company['departments'][0]['name'] = 'Emerging Technologies';
?>

Esempio 9. XPath Navigation

We can use XPath expressions to navigate the data object instance structure. Two forms of indexing into many-valued properties are supported. The first is the standard XPath array syntax with the indexing starting at one, the second is an SDO extension to XPath with an index starting at zero. The following both get the second employee from the first department.

<?php
  $jane_doe = $company["departments[1]/employees[2]"];
  $jane_doe = $company["departments.0/employees.1"];
?>

Esempio 10. XPath Querying

We can use XPath to query and identify parts of a data object based on instance data. The following retrieves the manager from the 'Advanced Technologies' department.

<?php
  $ad_tech_mgr = $company["departments[name=\"Advanced Technologies\"]/employees[manager=\"true\"]"]; 
?>

Esempio 11. Creating child data object

A data object can be a factory for its child data objects. A child data object is automatically part of the data graph. The following add a new employee to the 'Advanced Technologies' department.

<?php
  $ad_tech_dept = $company["departments[name=\"Advanced Technologoies\"]"];
  $new_hire = $ad_tech_dept->createDataObject('employees');
  $new_hire->name = 'John Johnson';
  $new_hire->SN = 'E0005';
  $new_hire->manager = false;
?>

Esempio 12. Unset referenced data object

We can use the isset() and unset() functions to test and remove items from the data object.

The following removes the 'employeeOfTheMonth' from the company. If this were a containment reference then the employee would be removed from the company (probably not a good idea to sack your best employee each month!), but since this is a non-containment reference, the employee being referenced will remain in the department in the company, but will no longer be accessible via the employeeOfTheMonth property.

<?php
  if (isset($company->employeeOfTheMonth)) {
    unset($company->employeeOfTheMonth);
  }
?>


Working with Sequenced Data Objects

Sequenced data objects are SDOs which can track property ordering across the properties of a data object. They can also contain unstructured text elements (text element which do not belong to any of the SDO's properties). Sequenced data objects are useful for working with XML documents which allow unstructured text (i.e. mixed=true) or if the elements can be interleaved ( <A/><B/><A/>). This can occur for example when the schema defines maxOccurs>1 on a element which is a complexType with a choice order indicator.

The examples below assume an SDO created with the following schema and instance information, using the XML Data Access Service.

The schema below describes the format of a letter. The letter can optionally contain three properties; date, firstName, and lastName. The schema states mixed="true" which means that unstructured text can be interspersed between the three properties.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

The following is an instance letter document. It contains the three letter properties; date, firstName and lastName, and has unstructured text elements for the address and letter body.

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

When loaded, the letter data object will have the sequence and property indices shown in the table below:

Sequence IndexProperty Index:NameValue
00:dateMarch 1, 2005
1-Mutual of Omaha
2-Wild Kingdom, USA
3-Dear
41:firstNameCasy
52:lastNameCrocodile
6-Please buy more shark repellent.
7-Your premium is past due.

To ensure sequence indices are maintained, sequenced data objects should be manipulated through the SDO_Sequence interface. This allows the data object's instance data to be manipulated in terms of the sequence index as opposed to the property index (shown in the table above). The following examples assume the letter instance has been loaded into a data object referenced by the variable $letter.

Esempio 13. Getting the SDO_Sequence interface

We obtain a data object's sequence using the getSequence() method. The follow gets the sequence for the letter data object.

<?php
  $letter_seq = $letter->getSequence();
?>

All subsequent examples assume that the $letter_seq variable has been assigned the sequence for the letter data object.

Esempio 14. Get/set sequence values

We can get and set individual values (including unstructured text) using the sequence index. The following sets the firstName to 'Snappy' and gets the last sequence values (the unstructured text, 'Your premium is past due.').

<?php
  $letter_seq[4] = 'Snappy';
  $text = $letter_seq[count($letter_seq) - 1];
?>

Esempio 15. Sequence iteration

We can iterate through the individual sequence values using foreach. The following runs through the individual values in sequence order.

<?php
  foreach ($letter->getSequence() as $value) {
    ...
  }
?>

Esempio 16. Sequence versus Data Object

Setting values through the data object interface may result in the value not being part of the sequence. A value set through the data object will only be accessible through the sequence if the property was already part of the sequence. The following example sets the lastName through the data object and gets it through the sequence. This is fine because lastName already exists in the sequence. If it had not previously been set, then lastName would be set to 'Smith', but would not be part of the sequence.

<?php
  $letter[2] = 'Smith';
  $last_name = $letter_seq[5];
?>

Esempio 17. Adding to a sequence

We can add new values to a sequence using the SDO_Sequence::insert() method. The following examples assume that the 'firstName' and 'lastName' properties are initially unset.

<?php
  // Append a firstName value to the sequence
  // value: 'Smith'
  // sequence index: NULL (append)
  // propertyIdentifier: 1 (firtName property index)
  $letters_seq->insert('Smith', NULL, 1);

  // Append a lastName value to the sequence
  // value: 'Jones'
  // sequence index: NULL (append)
  // property identifier: 'lastName' (lastName property name)
  $letters_seq->insert('Jones', NULL, 'lastName');

  // Append unstructured text
  // value: 'Cancel Subscription.'
  // sequence index: absent (append)
  // propertyIdentifier: absent (unstructured text)
  $letters_seq->insert('Cancel Subscription.');

  // Insert new unstructured text.  Subsequent sequence values
  // are shifted up.                                       
  // value: 'Care of:'
  // sequence index: 1 (insert as second element)
  // propertyIdentifier: absent (unstructured text)
  $letters_seq->insert('Care of:', 1);
?>

Esempio 18. Removing from a sequence

We can use the isset() and unset() functions to test and remove items from the sequence (Note: unset() currently leaves the values in the data object, but this behaviour is likely to change to also remove the data from the data object). A sequence behaves like a contiguous list; therefore, removing items from the middle will shift entries at higher indices down. The following example tests to see if the first sequence element is set and unsets it if is.

<?php
  if (isset($letter_seq[0]) {
    unset($letter_seq[0]);
  }
?>


Classi predefinite

SDO consists of two sets of interfaces. The first set covers those interfaces for use by SDO client applications. These are identified by the package prefix 'SDO_'. The second set is those for use by Data Access Service implementations and are identified by the package prefix 'SDO_DAS_'. The majority of SDO users will not need to use or understand the 'SDO_DAS_' interfaces.


SDO Application Programmer Interface

SDO_DataObject

The main interface through which data objects are manipulated. In addition to the methods below, SDO_DataObject extends the ArrayAccess, SDO_PropertyAccess (defines __get() / __set() methods for property access overloading), Iterator, and Countable interfaces.


Metodi


SDO_Sequence

The interface through which sequenced data objects can be accessed to preserve ordering across a data object's properties and to allow unstructured text. SDO_Sequence preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down. In addition to the methods below, SDO_Sequence extends the ArrayAccess, Iterator and Countable interface.


Metodi

  • getPropertyIndex - get the property index for a given sequence index

  • getPropertyName - get the property name for a given sequence index

  • move - move an element from one property index to another

  • insert - insert a new value into the sequence


SDO_List

The interface through which many-valued properties are manipulated. In addition to the method defined below, SDO_List extends ArrayAccess, Iterator and Countable. SDO_List preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down.


Metodi

  • insert - insert a new value into the list


SDO_DataFactory

The interface through which data objects can be created. A Data Access Service is responsible for populating the model (i.e. configuring the data factory with the type and structure information for the data objects it can create.) for the factory and can then optionally return an instance of, or implement, the SDO_DataFactory interface.


Metodi

  • create - create a new data object


SDO Data Access Service Developer Interfaces

SDO_DAS_DataObject

The interface through which a Data Access Service can access a data object's SDO_DAS_ChangeSummary . The change summary is used by the Data Access Service to check for conflicts when applying changes back to a data source.


Metodi


SDO_DAS_ChangeSummary

The interface through which the change history of a data object is accessed. The change summary holds information for any modifications on a data object which occurred since logging was activated. In the case of deletions and modifications, the old values are also held in the change summary.

If logging is no longer active then the change summary only holds changes made up to the point when logging was deactivated. Reactivating logging clears the change summary. This is useful when a set of changes have been written out by a DAS and the data object is to be reused.


Metodi


SDO_DAS_Setting

The interface through which the old value for a property is accessed. A list of settings is returned by the change summary method getOldValues() .


Metodi

  • getPropertyIndex - get the property index for the changed property

  • getPropertyName - get the property name for the changed property

  • getValue - get the old value for the changed property

  • getListIndex - get the list index for the old value if it was part of a many-valued property

  • isSet - test to see if the property was set prior to being modified


SDO_DAS_DataFactory

The interface for constructing the model for an SDO_DataObject. The SDO_DAS_DataFactory is an abstract class providing a static method which returns a concrete data factory implementation. The implementation is used by Data Access Services to create an SDO model from their model. For example, a Relational Data Access Service might create and populate an SDO_DAS_DataFactory model based on a schema for a relational database.


Metodi


Costanti predefinite

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.

SDO_DAS_ChangeSummary::NONE=0 (integer)

Represents a change type of 'none'.

SDO_DAS_ChangeSummary::MODIFICATION=1 (integer)

Represents a change type of 'modification'.

SDO_DAS_ChangeSummary::ADDITION=2 (integer)

Represents a change type of 'addition'.

SDO_DAS_ChangeSummary::DELETION=3 (integer)

Represents a change type of 'deletion'.

Sommario
SDO_DAS_ChangeSummary::beginLogging --  Begin change logging.
SDO_DAS_ChangeSummary::endLogging --  End change logging.
SDO_DAS_ChangeSummary::getChangeType --  Get the type of change made to an SDO_DataObject.
SDO_DAS_ChangeSummary::getChangedDataObjects --  Get the changed data objects from a change summary.
SDO_DAS_ChangeSummary::getOldContainer --  Get the old container for a deleted SDO_DataObject.
SDO_DAS_ChangeSummary::getOldValues --  Get the old values for a given changed SDO_DataObject.
SDO_DAS_ChangeSummary::isLogging --  Test to see whether change logging is switched on.
SDO_DAS_DataFactory::addPropertyToType --  Adds a property to a type.
SDO_DAS_DataFactory::addType --  Add a new type to a model.
SDO_DAS_DataFactory::getDataFactory --  Get a data factory instance.
SDO_DAS_DataObject::getChangeSummary --  Get a data object's change summary.
SDO_DAS_Setting::getListIndex --  Get the list index for a changed many-valued property.
SDO_DAS_Setting::getPropertyIndex --  Get the property index for a changed property.
SDO_DAS_Setting::getPropertyName --  Get the property name for a changed property.
SDO_DAS_Setting::getValue --  Get the old value for the changed property.
SDO_DAS_Setting::isSet --  Test whether a property was set prior to being modified.
SDO_DataFactory::create --  Create an SDO_DataObject.
SDO_DataObject::clear --  Clear an SDO_DataObject's properties.
SDO_DataObject::createDataObject --  Create a child SDO_DataObject.
SDO_DataObject::getContainer --  Get a data object's container.
SDO_DataObject::getContainmentPropertyName --  Get the container's property name.
SDO_DataObject::getSequence --  Get the sequence for a data object.
SDO_DataObject::getType --  Get the type of a data object.
SDO_List::insert --  Insert into a list.
SDO_Sequence::getPropertyIndex --  Return the property index for the specified sequence index.
SDO_Sequence::getPropertyName --  Return the property name for the specified sequence index.
SDO_Sequence::insert --  Insert into a sequence.
SDO_Sequence::move --  Move an item to another sequence position.

SDO_DAS_ChangeSummary::beginLogging

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::beginLogging --  Begin change logging.

Descrizione

void SDO_DAS_ChangeSummary::beginLogging ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Begin logging changes made to the SDO_DataObject.

Elenco dei parametri

None.

Valori restituiti

None.

SDO_DAS_ChangeSummary::endLogging

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::endLogging --  End change logging.

Descrizione

void SDO_DAS_ChangeSummary::endLogging ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

End logging changes made to an SDO_DataObject.

Elenco dei parametri

None.

Valori restituiti

None.

SDO_DAS_ChangeSummary::getChangeType

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getChangeType --  Get the type of change made to an SDO_DataObject.

Descrizione

int SDO_DAS_ChangeSummary::getChangeType ( SDO_DataObject dataObject )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get the type of change which has been made to the supplied SDO_DataObject.

Elenco dei parametri

dataObject

The SDO_DataObject which has been changed.

Valori restituiti

The type of change which has been made. The change type is expressed as an enumeration and will be one of the following four values:

  • SDO_DAS_ChangeSummary::NONE

  • SDO_DAS_ChangeSummary::MODIFICATION

  • SDO_DAS_ChangeSummary::ADDITION

  • SDO_DAS_ChangeSummary::DELETION

SDO_DAS_ChangeSummary::getChangedDataObjects

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getChangedDataObjects --  Get the changed data objects from a change summary.

Descrizione

SDO_List SDO_DAS_ChangeSummary::getChangedDataObjects ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get an SDO_List of the SDO_DataObjects which have been changed. These data objects can then be used to identify the types of change made to each, along with the old values.

Elenco dei parametri

None.

Valori restituiti

Returns an SDO_List of SDO_DataObjects.

SDO_DAS_ChangeSummary::getOldContainer

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getOldContainer --  Get the old container for a deleted SDO_DataObject.

Descrizione

SDO_DataObject SDO_DAS_ChangeSummary::getOldContainer ( SDO_DataObject dataObject )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get the old container (SDO_DataObject) for a deleted SDO_DataObject.

Elenco dei parametri

dataObject

The SDO_DataObject which has been deleted and whose container we wish to identify.

Valori restituiti

The old containing data object of the deleted SDO_DataObject.

SDO_DAS_ChangeSummary::getOldValues

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::getOldValues --  Get the old values for a given changed SDO_DataObject.

Descrizione

SDO_List SDO_DAS_ChangeSummary::getOldValues ( SDO_DataObject dataObject )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get a list of the old values for a given changed SDO_DataObject. Returns a list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject.

Elenco dei parametri

dataObject

The data object which has been changed.

Valori restituiti

A list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject

SDO_DAS_ChangeSummary::isLogging

(no version information, might be only in CVS)

SDO_DAS_ChangeSummary::isLogging --  Test to see whether change logging is switched on.

Descrizione

bool SDO_DAS_ChangeSummary::isLogging ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Test to see whether change logging is switched on.

Elenco dei parametri

None.

Valori restituiti

Returns TRUE if change logging is on, otherwise returns FALSE.

SDO_DAS_DataFactory::addPropertyToType

(no version information, might be only in CVS)

SDO_DAS_DataFactory::addPropertyToType --  Adds a property to a type.

Descrizione

void SDO_DAS_DataFactory::addPropertyToType ( string parentNamespaceURI, string parentTypeName, string propertyName, string propertyNamespaceURI, string propertyTypeName [, array options] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Adds a property to a type. The type must already be known to the SDO_DAS_DataFactory (i.e. have been added using addType()). The property becomes a property of the type. This is how the graph model for the structure of an SDO_DataObject is built.

Elenco dei parametri

parentNamespaceURI

The namespace URI for the parent type.

parentTypeName

The type name for the parent type.

propertyName

The name by which the property will be known in the parent type.

propertyNamespaceURI

The namespace URI for the type of the property.

propertyTypeName

The type name for the type of the property

options

This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:

many

A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').

readOnly

A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false').

containment

A flag to say whether the property is contained by the parent. A value of 'true' means the property is contained by the parent. A value of 'false' results in a non-containment reference (default is 'true'). This flag is only interpreted when adding properties which are data object types, otherwise it is ignored.

default

A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).

Valori restituiti

None.

Log delle modifiche

VersioneDescrizione
0.5.2Optional parameters many, readOnly, and containment deprecated in favour of the options array.

Esempi

Esempio 1. A SDO_DAS_DataFactory::addPropertyToType() example

The following adds an 'addressline' property to a Person type. The person type is identified by its namespace, 'PersonNS', and type name, 'PersonType'. The type of the 'addressline' property is a many-valued SDO data type (primitive) with namespace 'commonj.sdo' and type name 'String'.

<?php
  $df->addPropertyToType('PersonNS', 'PersonType',
    'addressline', 'commonj.sdo', 'String', array('many'=>true));
?>

SDO_DAS_DataFactory::addType

(no version information, might be only in CVS)

SDO_DAS_DataFactory::addType --  Add a new type to a model.

Descrizione

void SDO_DAS_DataFactory::addType ( string namespaceURI, string typeName )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Add a new type to the SDO_DAS_DataFactory, defined by its namespace and type name. The type becomes part of the model of data objects that the data factory can create.

Elenco dei parametri

namespaceURI

The namespace of the type.

typeName

The name of the type.

Valori restituiti

No values returned.

Esempi

Esempio 1. A SDO_DAS_DataFactory::addType() example

The following adds a new data object type of 'CompanyType' where that type belongs to the namespace 'CompanyNS'.

<?php
  $df->addType('CompanyNS', 'CompanyType');
?>

SDO_DAS_DataFactory::getDataFactory

(no version information, might be only in CVS)

SDO_DAS_DataFactory::getDataFactory --  Get a data factory instance.

Descrizione

SDO_DAS_DataFactory SDO_DAS_DataFactory::getDataFactory ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Static method to get an instance of an SDO_DAS_DataFactory. This instance is initially only configured with the basic SDO types. A Data Access Service is responsible for populating the data factory model and then allowing PHP applications to create SDOs based on the model through the SDO_DataFactory interface. PHP applications should always obtain a data factory from a configured Data Access Service, not through this interface.

Elenco dei parametri

None.

Valori restituiti

Returns an SDO_DAS_DataFactory.

SDO_DAS_DataObject::getChangeSummary

(no version information, might be only in CVS)

SDO_DAS_DataObject::getChangeSummary --  Get a data object's change summary.

Descrizione

SDO_DAS_ChangeSummary SDO_DAS_DataObject::getChangeSummary ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Elenco dei parametri

None.

Valori restituiti

Returns the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

SDO_DAS_Setting::getListIndex

(no version information, might be only in CVS)

SDO_DAS_Setting::getListIndex --  Get the list index for a changed many-valued property.

Descrizione

int SDO_DAS_Setting::getListIndex ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get the list index for a modification made to an element of a many-valued property. For example, if we modified the third element of a many-valued property we could obtain an SDO_DAS_Setting from the change summary corresponding to that modification. A call to getListIndex() on that setting would return the value 2 (lists are indexed from zero).

Elenco dei parametri

None.

Valori restituiti

The list index for the element of the many-valued property which has been changed.

SDO_DAS_Setting::getPropertyIndex

(no version information, might be only in CVS)

SDO_DAS_Setting::getPropertyIndex --  Get the property index for a changed property.

Descrizione

int SDO_DAS_Setting::getPropertyIndex ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the property index for the changed property. This index identifies the property which was modified in data object.

Elenco dei parametri

None.

Valori restituiti

The property index for a changed property.

SDO_DAS_Setting::getPropertyName

(no version information, might be only in CVS)

SDO_DAS_Setting::getPropertyName --  Get the property name for a changed property.

Descrizione

string SDO_DAS_Setting::getPropertyName ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the property name for the changed property. This name identifies the property which was modified in data object.

Elenco dei parametri

None.

Valori restituiti

The property name for a changed property.

SDO_DAS_Setting::getValue

(no version information, might be only in CVS)

SDO_DAS_Setting::getValue --  Get the old value for the changed property.

Descrizione

mixed SDO_DAS_Setting::getValue ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the old value for the changed property. This can be used by a Data Access Service when writing updates to a data source. The DAS uses the old value to detect conflicts by comparing it with the current value in the data source. If they do not match, then the data source has been updated since the data object was originally populated, and therefore writing any new updates risks compromising the integrity of the data.

Elenco dei parametri

None.

Valori restituiti

Returns the old value of the changed property.

SDO_DAS_Setting::isSet

(no version information, might be only in CVS)

SDO_DAS_Setting::isSet --  Test whether a property was set prior to being modified.

Descrizione

bool SDO_DAS_Setting::isSet ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Test whether a property was set prior to being modified. If it was set prior to being modified then the SDO_DAS_Setting will also contain the old value.

Elenco dei parametri

None.

Valori restituiti

Returns TRUE if the property was set prior to being modified, otherwise returns FALSE.

SDO_DataFactory::create

(no version information, might be only in CVS)

SDO_DataFactory::create --  Create an SDO_DataObject.

Descrizione

void SDO_DataFactory::create ( string namespaceURI, string typeName )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Create a new SDO_DataObject given the data object's namespace URI and type name.

Elenco dei parametri

namespaceURI

The namespace of the type.

typeName

The name of the type.

Valori restituiti

Returns the newly created SDO_DataObject.

Eccezioni

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type known to this data factory.

SDO_DataObject::clear

(no version information, might be only in CVS)

SDO_DataObject::clear --  Clear an SDO_DataObject's properties.

Descrizione

void SDO_DataObject::clear ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.

Elenco dei parametri

None.

Valori restituiti

No return values.

SDO_DataObject::createDataObject

(no version information, might be only in CVS)

SDO_DataObject::createDataObject --  Create a child SDO_DataObject.

Descrizione

SDO_DataObject SDO_DataObject::createDataObject ( mixed identifier )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Create a child SDO_DataObject of the default type for the property identified. The data object is automatically inserted into the tree and a reference to it is returned.

Elenco dei parametri

identifier

Identifies the property for the data object type to be created. Can be either a property name (string), or property index (int).

Valori restituiti

Returns the newly created SDO_DataObject.

Eccezioni

SDO_PropertyNotFoundException

Thrown if the identifier does not correspond to a property of the data object.

SDO_DataObject::getContainer

(no version information, might be only in CVS)

SDO_DataObject::getContainer --  Get a data object's container.

Descrizione

SDO_DataObject SDO_DataObject::getContainer ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get the data object which contains this data object.

Elenco dei parametri

None.

Valori restituiti

Returns the SDO_DataObject which contains this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).

SDO_DataObject::getContainmentPropertyName

(no version information, might be only in CVS)

SDO_DataObject::getContainmentPropertyName --  Get the container's property name.

Descrizione

string SDO_DataObject::getContainmentPropertyName ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Get the property name used to refer to this data object by its containing data object.

Elenco dei parametri

None.

Valori restituiti

Returns the name of the container's property which references this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).

SDO_DataObject::getSequence

(no version information, might be only in CVS)

SDO_DataObject::getSequence --  Get the sequence for a data object.

Descrizione

SDO_Sequence SDO_DataObject::getSequence ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Return the SDO_Sequence for this SDO_DataObject. Accessing the SDO_DataObject through the SDO_Sequence interface acts on the same SDO_DataObject instance data, but preserves ordering across properties.

Elenco dei parametri

None.

Valori restituiti

The SDO_Sequence for this SDO_DataObject, or returns NULL if the SDO_DataObject is not of a type which can have a sequence.

SDO_DataObject::getType

(no version information, might be only in CVS)

SDO_DataObject::getType --  Get the type of a data object.

Descrizione

array SDO_DataObject::getType ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Return an array containing the type information for an SDO_DataObject. The first element contains the namespace URI string and the second contains the type name string.

Elenco dei parametri

None.

Valori restituiti

An array containing the namespace URI string and the type name string for the data object.

Esempi

Esempio 1. A SDO_DataObject::getType() example

For example, if the SDO_DataObject were of type 'CompanyType' from the namespace 'CompanyNS', then getType() would return the equivalent to array('CompanyNS', 'CompanyType'):

<?php
  $do_type = $company_do->getType();
  echo "Namespace: $do_type[0], Type Name: $do_type[1]";
?>

Il precedente esempio visualizzerà:

Namespace: CompanyNS, Type Name: CompanyType

SDO_List::insert

(no version information, might be only in CVS)

SDO_List::insert --  Insert into a list.

Descrizione

void SDO_List::insert ( mixed value [, int index] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Insert a new element at a specified position in the list. All subsequent list items are moved up.

Elenco dei parametri

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

index

The position at which to insert the new element. If this argument is not specified then the new value will be appended.

Valori restituiti

None.

Eccezioni

SDO_IndexOutOfBoundsException

Thrown if the list index is less than zero or greater than the size of the list.

SDO_InvalidConversionException

Thrown if the type of the new value does not match the type for the list (e.g. the type of the many-valued property that the list represents).

SDO_Sequence::getPropertyIndex

(no version information, might be only in CVS)

SDO_Sequence::getPropertyIndex --  Return the property index for the specified sequence index.

Descrizione

int SDO_Sequence::getPropertyIndex ( int sequenceIndex )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Return the property index for the specified sequence index. If the sequence item is unstructured text rather than a data object property, then a value of -1 is returned.

Elenco dei parametri

sequenceIndex

The sequence index for which we wish to determine the associated data object property index.

Valori restituiti

The corresponding property index. A value of -1 means the element does not belong to a property and must therefore be unstructured text.

Eccezioni

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_Sequence::getPropertyName

(no version information, might be only in CVS)

SDO_Sequence::getPropertyName --  Return the property name for the specified sequence index.

Descrizione

string SDO_Sequence::getPropertyName ( int sequenceIndex )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Return the property name for the specified sequence index. If the sequence item is unstructured text rather than a data object property, then a value of NULL is returned.

Elenco dei parametri

sequenceIndex

The sequence index for which we wish to determine the associated data object property name.

Valori restituiti

The corresponding property name. A value of NULL means the element does not belong to a property and must therefore be unstructured text.

Eccezioni

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_Sequence::insert

(no version information, might be only in CVS)

SDO_Sequence::insert --  Insert into a sequence.

Descrizione

void SDO_Sequence::insert ( mixed value [, int sequenceIndex [, mixed propertyIdentifier]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.

Elenco dei parametri

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

sequenceIndex

The position at which to insert the new element. Default is NULL, which results in the new value being appended to the sequence.

propertyIdentifier

Either a property index or property name, used to identify a property in the sequence's corresponding SDO_DataObject. A value of NULL signifies unstructured text.

Valori restituiti

None.

Eccezioni

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_InvalidConversionException

Thrown if the type of the new value cannot be juggled to match the type for the specified data object property.

SDO_Sequence::move

(no version information, might be only in CVS)

SDO_Sequence::move --  Move an item to another sequence position.

Descrizione

void SDO_Sequence::move ( int toIndex, int fromIndex )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.

Elenco dei parametri

toIndex

The destination sequence index. If this index is less than zero or greater than the size of the sequence then the value is appended.

fromIndex

The source sequence index.

Valori restituiti

None.

Eccezioni

SDO_IndexOutOfBoundsException

Thrown if the fromIndex sequence index is less than zero or greater than the size of the sequence.

CXXIX. SDO XML Data Access Service Functions

Introduzione

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 order to use the XML Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO .

The job of the XML DAS is to move data between the application and an XML data source, which can be either a file or a URL. In order to do this it needs to be told the location of the XML schema, which is passed as a parameter to the create method of the XML DAS. The schema is used to ensure conformance of XML being written out, and also to ensure that modifications made to an SDO originating from XML follow the model described by the XML schema.


Requisiti

The SDO XML Data Access Service requires PHP 5.1 or higher. It is packaged with the SDO extension and requires SDO to have been installed. See the SDO installation instructions for the details of how to do this.


Installazione

The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.


Limitations

The SDO 2.0 specification defines the mapping between XML types and SDO types. With Java SDO, this mapping is implemented by the XMLHelper. With SDO for PHP, this mapping is implemented by the XML Data Access Services. The XML DAS implements the mapping described in the SDO 2.0 specification with the following restrictions:

XML Simple Types

  1. Simple Type with abstract="true" - no PHP support for SDO abstract types.

  2. Simple Type with sdoJava:instanceClass - no PHP equivalent provided.

  3. Simple Type with sdoJava:extendedInstanceClass - no PHP equivalent provided.

  4. Simple Type with list of itemType.

  5. Simple Type with union.

XML Complex Types

  1. Complex Type with abstract="true" - no PHP support for SDO abstract types.

  2. Complex Type with sdo:aliasName - no PHP support for SDO Type aliases.

  3. Complex Type with open content - no PHP support for SDO open types.

  4. Complex Type with open attribute - no PHP support for SDO open types.

XSD Attribute

  1. Attribute with sdo:aliasName - no PHP support for SDO property aliases.

  2. Attribute with default value - no PHP support for SDO property defaults.

  3. Attribute with fixed value - no PHP support for SDO read-only properties or default values.

  4. Attribute reference.

  5. Attribute with sdo:string - no support for sdo:string="true".

  6. Attribute referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="...".

  7. Attribute with bi-directional property to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

XSD Elements

  1. Element with sdo:aliasName - no PHP support for SDO property aliases.

  2. Element reference.

  3. Element with nillable.

  4. Element with substitution group.

XSD Elements with Simple Type

  1. Element of SimpleType with default - no PHP support for SDO defaults

  2. Element of SimpleType with fixed value - no PHP support for SDO read-only properties or default values.

  3. Element of SimpleType with sdo:string - no support for sdo:string="true".

  4. Element referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="..."

  5. Element with bi-directional reference to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.


Esempi

The following examples are based on the letter example described in the SDO documentation. The examples assume the XML Schema for the letter is contained in a file letter.xsd and the letter instance is in the file letter.xml. These two files are reproduced here:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

Esempio 1. Loading, altering, and saving an XML document

The following example shows how an XML document can be loaded from a file, altered, and written back.

<?php
try {
    $xmldas = SDO_DAS_XML::create("letter.xsd");
    $xdoc = $xmldas->loadFromFile("letter.xml");
    $do = $xdoc->getRootDataObject();
    $do->date = "September 03, 2004";
    $do->firstName = "Anantoju";
    $do->lastName = "Madhu";
    $xmldas->saveDocumentToFile($xdoc, "letter-out.xml");
} catch (SDO_TypeNotFoundException $e) {
    print("Type is not defined in the xsd file");
} catch (SDO_DAS_XML_ParserException $e) {
    print("Problem while parsing");
}
?>

An instance of the XML DAS is first obtained from the SDO_DAS_XML::create() method, which is a static method of the SDO_DAS_XML class. The location of the xsd is passed as a parameter. Once we have an instance of the XML DAS initialised with a given schema, we can use it to load the instance document using the loadFromFile() method. There is also a loadFromString() method if you want to load an XML instance document from a string. If the instance document loads successfully, you will be returned an object of type SDO_DAS_XML_Document, on which you can call the getRootDataObject() method to get the SDO data object which is the root of the SDO data graph. You can then use SDO operations to change the graph. In this example we alter the date, firstName, and lastName properties. Then we use the saveDocumentToFile() method to write the changed document back to the file system.

This will write the following to letter-out.xml.

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <date>September 03, 2004</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Anantoju</firstName>
  <lastName>Madhu</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</FormLetter>

Esempio 2. Creating a new XML document

The previous example loaded the document from a file. This example shows how to create an SDO data graph in memory. In this example it is then saved to an XML string. Furthermore, because the letter contains both structured and unstructured content, it uses the Sequence API as well assignments to properties to construct the data graph.

<?php 
try {
    $xmldas = SDO_DAS_XML::create("letter.xsd");
    try {
        $do = $xmldas->createDataObject("http://letterSchema", "FormLetter");
        $seq = $do->getSequence();
        $seq->insert("April 09, 2005", NULL, 'date');
        $seq->insert("Acme Inc. ", NULL, NULL);
        $seq->insert("United Kingdom. ");
        $seq->insert("Dear", NULL, NULL);
        $seq->insert("Tarun", NULL, "firstName");
        $seq->insert("Nayaraaa", NULL, "lastName");
        $do->lastName = "Nayar";
        $seq->insert("Please note that your order number ");
        $seq->insert(12345);
        $seq->insert(" has been dispatched today. Thanks for your business with us.");
        $type = $do->getType();
        print($xmldas->saveDataObjectToString($do, $type[0], $type[1]));
    } catch (SDO_Exception $e) {
        print($e);
    }
} catch (SDO_TypeNotFoundException $e) {
    print("Type is not defined in the xsd file");
} catch (SDO_DAS_XML_ParserException $e) {
    print("Problem while parsing");
}
?>

This will emit the following output (line breaks have been inserted for readability):

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>April 09, 2005</date>
Acme Inc. United Kingdom. 
Dear
<firstName>Tarun</firstName>
<lastName>Nayar</lastName>
Please note that your order number 12345 has been 
dispatched today. Thanks for your business with us.
</FormLetter>

Esempio 3. Setting XML document properties

This third example shows you how to use the SDO_DAS_XML_Document class. SDO_DAS_XML_Document class is provided to get and set properties of the XML declaration such as version, schema location, encoding and so on.

<?php
try {
    $xmldas = SDO_DAS_XML::create("letter.xsd");
    $xdoc = $xmldas->loadFromFile("letter.xml");
    print("Encoding is set to : " . $xdoc->getEncoding() . "\n");
    print("XML Version : " . $xdoc->getXMLVersion() . "\n");
    $xdoc->setXMLVersion("1.1");
    print($xmldas->saveDocumentToString($xdoc));
} catch (SDO_TypeNotFoundException $e) {
    print("Type is not defined in the xsd file");
} catch (SDO_DAS_XML_ParserException $e) {
    print("Problem while parsing");
}
?>

The first three lines of output show how the encoding and XML version has been obtained from the document, and how the XML version has been set in the XML header.

Encoding is set to : UTF-8
XML Version : 1.0
<?xml version="1.1" encoding="UTF-8"?>
...

Classi predefinite

The XML DAS provides three classes. The SDO_DAS_XML which is the main class used to fetch the data from the XML source and also can used to write the data back. The next one is SDO_DAS_XML_Document class, which is basically useful to get/set the XML declarations such as encoding, version etc. And the last class is SDO_DAS_XML_ParserException which will be thrown for any parser exceptions while loading xsd/xml file.


SDO_DAS_XML

This is the main class of XML DAS, which is used fetch the data from the xml source and also used to write the data back. Other than the methods to load and save xml files, it also has a method called createDataObject which can be used to create an empty DataObject of a given type.


Metodi


SDO_DAS_XML_Document

This class can be used to get/set XML Declarations such as encoding, schema location etc.


Metodi


SDO_DAS_XML_ParserException

Is a subclass of SDO_Exception . Thrown for any parser errors while loading the xsd/xml file.

Sommario
SDO_DAS_XML_Document::getEncoding --  Returns encoding string.
SDO_DAS_XML_Document::getNoNamespaceSchemaLocation --  Returns no namespace schema location.
SDO_DAS_XML_Document::getRootDataObject --  Returns the root SDO_DataObject.
SDO_DAS_XML_Document::getRootElementName --  Returns root element's name.
SDO_DAS_XML_Document::getRootElementURI --  Returns root element's URI string.
SDO_DAS_XML_Document::getSchemaLocation --  Returns schema location.
SDO_DAS_XML_Document::getXMLDeclaration --  Returns whether the xml declaration is set or not.
SDO_DAS_XML_Document::getXMLVersion --  Returns xml declaration string.
SDO_DAS_XML_Document::setEncoding --  Sets the given string as encoding.
SDO_DAS_XML_Document::setNoNamespaceSchemaLocation --  Sets the given string as no namespace schema location.
SDO_DAS_XML_Document::setSchemaLocation --  Sets the given string as schema location.
SDO_DAS_XML_Document::setXMLDeclaration --  Sets the xml declaration.
SDO_DAS_XML_Document::setXMLVersion --  Sets the given string as xml version.
SDO_DAS_XML::create --  To create SDO_DAS_XML object for a given schema file.
SDO_DAS_XML::createDataObject --  Creates SDO_DataObject for a given namespace URI and type name.
SDO_DAS_XML::loadFromFile --  Returns SDO_DAS_XML_Document object for a given path to xml instance document.
SDO_DAS_XML::loadFromString --  Returns SDO_DAS_XML_Document for a given xml instance string.
SDO_DAS_XML::saveDataObjectToFile --  Saves the SDO_DataObject object to File.
SDO_DAS_XML::saveDataObjectToString --  Saves the SDO_DataObject object to string.
SDO_DAS_XML::saveDocumentToFile --  Saves the SDO_DAS_XML_Document object to a file.
SDO_DAS_XML::saveDocumentToString --  Saves the SDO_DAS_XML_Document object to a string.

SDO_DAS_XML_Document::getEncoding

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getEncoding --  Returns encoding string.

Descrizione

string SDO_DAS_XML_Document::getEncoding ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the encoding string for the SDO_DAS_XML_Document object.

Elenco dei parametri

Valori restituiti

Returns the encoding string.

SDO_DAS_XML_Document::getNoNamespaceSchemaLocation

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getNoNamespaceSchemaLocation --  Returns no namespace schema location.

Descrizione

string SDO_DAS_XML_Document::getNoNamespaceSchemaLocation ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the no namespace schema location.

Elenco dei parametri

Valori restituiti

Returns no namespace schema location.

SDO_DAS_XML_Document::getRootDataObject

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getRootDataObject --  Returns the root SDO_DataObject.

Descrizione

SDO_DataObject SDO_DAS_XML_Document::getRootDataObject ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the root SDO_DataObject.

Elenco dei parametri

Valori restituiti

Returns the root SDO_DataObject.

SDO_DAS_XML_Document::getRootElementName

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getRootElementName --  Returns root element's name.

Descrizione

string SDO_DAS_XML_Document::getRootElementName ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns root element's name.

Elenco dei parametri

Valori restituiti

Returns root element's name.

SDO_DAS_XML_Document::getRootElementURI

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getRootElementURI --  Returns root element's URI string.

Descrizione

string SDO_DAS_XML_Document::getRootElementURI ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns root element's URI string.

Elenco dei parametri

Valori restituiti

Returns root element's URI string.

SDO_DAS_XML_Document::getSchemaLocation

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getSchemaLocation --  Returns schema location.

Descrizione

string SDO_DAS_XML_Document::getSchemaLocation ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns schema location.

Elenco dei parametri

Valori restituiti

Returns schema location.

SDO_DAS_XML_Document::getXMLDeclaration

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getXMLDeclaration --  Returns whether the xml declaration is set or not.

Descrizione

bool SDO_DAS_XML_Document::getXMLDeclaration ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns whether the xml declaration is set or not.

Elenco dei parametri

Valori restituiti

Returns whether the xml declaration is set or not. TRUE If it is set and FALSE if it is not.

SDO_DAS_XML_Document::getXMLVersion

(no version information, might be only in CVS)

SDO_DAS_XML_Document::getXMLVersion --  Returns xml declaration string.

Descrizione

string SDO_DAS_XML_Document::getXMLVersion ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns xml declaration string.

Elenco dei parametri

Valori restituiti

Returns xml declaration string.

SDO_DAS_XML_Document::setEncoding

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setEncoding --  Sets the given string as encoding.

Descrizione

void SDO_DAS_XML_Document::setEncoding ( string encoding )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Sets the given string as encoding.

Elenco dei parametri

encoding

Encoding string.

Valori restituiti

None.

SDO_DAS_XML_Document::setNoNamespaceSchemaLocation

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setNoNamespaceSchemaLocation --  Sets the given string as no namespace schema location.

Descrizione

void SDO_DAS_XML_Document::setNoNamespaceSchemaLocation ( string nnschemaLocation )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Sets the given string as no namespace schema location.

Elenco dei parametri

nnschemaLocation

no namespace schema location.

Valori restituiti

None.

SDO_DAS_XML_Document::setSchemaLocation

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setSchemaLocation --  Sets the given string as schema location.

Descrizione

void SDO_DAS_XML_Document::setSchemaLocation ( string schemaLocation )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Sets the given string as schema location.

Elenco dei parametri

schemaLocation

schema location.

Valori restituiti

None.

SDO_DAS_XML_Document::setXMLDeclaration

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setXMLDeclaration --  Sets the xml declaration.

Descrizione

void SDO_DAS_XML_Document::setXMLDeclaration ( bool xmlDeclatation )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Sets the given given boolean value for xml declaration. Pass TRUE to set it and FLASE to not to unset it.

Elenco dei parametri

xmlDeclatation

boolean value to set the XML declaration.

Valori restituiti

None.

SDO_DAS_XML_Document::setXMLVersion

(no version information, might be only in CVS)

SDO_DAS_XML_Document::setXMLVersion --  Sets the given string as xml version.

Descrizione

void SDO_DAS_XML_Document::setXMLVersion ( string xmlVersion )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Sets the given string as xml version.

Elenco dei parametri

xmlVersion

xml version string.

Valori restituiti

None.

SDO_DAS_XML::create

(no version information, might be only in CVS)

SDO_DAS_XML::create --  To create SDO_DAS_XML object for a given schema file.

Descrizione

SDO_DAS_XML SDO_DAS_XML::create ( string xsd_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 is the only static method of SDO_DAS_XML class. Used to instantiate SDO_DAS_XML object.

Elenco dei parametri

xsd_file

Path to XSD Schema file.

Valori restituiti

Returns SDO_DAS_XML object on success otherwise throws an exception as described below.

Eccezioni

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any symantical problems while parsing the given XSD File.

SDO_DAS_XML::createDataObject

(no version information, might be only in CVS)

SDO_DAS_XML::createDataObject --  Creates SDO_DataObject for a given namespace URI and type name.

Descrizione

SDO_DataObject SDO_DAS_XML::createDataObject ( string namespace_uri, string type_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.

Creates SDO_DataObject for a given namespace URI and type name. The type should be defined in the underlying model otherwise SDO_TypeNotFoundException will be thrown.

Elenco dei parametri

namespace_uri

Namespace URI of the type name.

type_name

Type Name.

Valori restituiti

Returns SDO_DataObject on success.

Eccezioni

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML::loadFromFile

(no version information, might be only in CVS)

SDO_DAS_XML::loadFromFile --  Returns SDO_DAS_XML_Document object for a given path to xml instance document.

Descrizione

SDO_XMLDocument SDO_DAS_XML::loadFromFile ( string xml_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.

Constructs the tree of SDO_DataObjects from the given address to xml instance document. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Elenco dei parametri

xml_file

Path to Instance document. This can be a path to a local file or it can be a URL.

Valori restituiti

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Eccezioni

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if the a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any symantical problems while parsing the given XSD File.

SDO_DAS_XML::loadFromString

(no version information, might be only in CVS)

SDO_DAS_XML::loadFromString --  Returns SDO_DAS_XML_Document for a given xml instance string.

Descrizione

SDO_DAS_XML_Document SDO_DAS_XML::loadFromString ( string xml_string )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Constructs the tree of SDO_DataObjects from the given xml instance string. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Elenco dei parametri

xml_string

xml string.

Valori restituiti

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Eccezioni

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if the a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML::saveDataObjectToFile

(no version information, might be only in CVS)

SDO_DAS_XML::saveDataObjectToFile --  Saves the SDO_DataObject object to File.

Descrizione

void SDO_DAS_XML::saveDataObjectToFile ( SDO_DataObject do, string root_uri, string root_name, string xml_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.

Saves the SDO_DataObject object as an XML File.

Elenco dei parametri

do

DataObject, which needs to be saves as an XML File.

root_uri

URI string for the root DataObject.

root_name

Type name of the root DataObject.

Valori restituiti

None.

SDO_DAS_XML::saveDataObjectToString

(no version information, might be only in CVS)

SDO_DAS_XML::saveDataObjectToString --  Saves the SDO_DataObject object to string.

Descrizione

string SDO_DAS_XML::saveDataObjectToString ( SDO_DataObject do, string root_uri, string root_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.

Saves the SDO_DataObject object as an XML string.

Elenco dei parametri

do

DataObject, which needs to be saves as an XML File.

root_uri

URI string for the root DataObject.

root_name

Type name of the root DataObject.

Valori restituiti

xml string

SDO_DAS_XML::saveDocumentToFile

(no version information, might be only in CVS)

SDO_DAS_XML::saveDocumentToFile --  Saves the SDO_DAS_XML_Document object to a file.

Descrizione

void SDO_DAS_XML::saveDocumentToFile ( SDO_XMLDocument xdoc, string xml_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.

Saves the SDO_DAS_XML_Document object to a file.

Elenco dei parametri

xdoc

SDO_DAS_XML_Document object.

xml_file

xml file.

Valori restituiti

SDO_DAS_XML::saveDocumentToString

(no version information, might be only in CVS)

SDO_DAS_XML::saveDocumentToString --  Saves the SDO_DAS_XML_Document object to a string.

Descrizione

string SDO_DAS_XML::saveDocumentToString ( SDO_XMLDocument xdoc )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Saves the SDO_DAS_XML_Document object to string.

Elenco dei parametri

xdoc

SDO_DAS_XML_Document object.

Valori restituiti

xml string.

CXXX. SDO Relational Data Access Service Functions

Introduzione

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 order to use the Relational Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, the disconnected way of working, the change summary, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO. In addition, the Relational DAS makes use of the PDO extension to isolate itself from specifics of different back-end relational databases. In order to use the Relational DAS you will need to be able to create and pass a PDO database connection; for this reason you might also want to take a look at the section on PDO.

The job of the Relational DAS is to move data between the application and a relational database. In order to do this it needs to be told the mapping between the database entities - tables, columns, primary keys and foreign keys - and the elements of the SDO model - types, properties, containment properties and so on. You specify this information as metadata when you construct the Relational DAS.

Overview of Operation

  1. The first step is to call the Relational DAS's constructor, passing the metadata that defines the mapping between database and SDO model. There are examples of this below.

  2. The next step might be to call the executeQuery() or executePreparedQuery() methods on the Relational DAS, passing either a literal SQL statement for the DAS to prepare and execute, or a prepared statement with placeholders and a list of values to be inserted. You may also need to specify a small amount of metadata about the query itself, so that the Relational DAS knows exactly what columns will be returned from the database and in what order. You will also need to pass a PDO database connection.

    The return value from executeQuery() or executePreparedQuery() is a normalised data graph containing all the data from the result set. For a query that returns data obtained from a number of tables, this graph will contain a number of data objects, linked by SDO containment references. There may also be SDO non-containment references within the data.

    Once the query has been executed and the data graph constructed, there is no need for either that instance of the the Relational DAS or the database connection. There are no locks held on the database. Both the Relational DAS and the PDO database connection can be garbage collected.

  3. Quite possibly the data in the data graph will go through a number of modifications. The data graph can be serialised into the PHP session and so may have a lifetime beyond just one client-server interaction. Data objects can be created and added to the graph, the data objects already in the graph can be deleted, and data objects in the graph can be modified.

  4. Finally, the changes made to the data graph can be applied back to the database using the applyChanges() method of the Relational DAS. For this, another instance of the Relational DAS must be constructed, using the same metadata, and another connection to the database obtained. The connection and the data graph are passed to applyChanges(). At this point the Relational DAS examines the change summary and generates the necessary INSERT, UPDATE and DELETE SQL statements to apply the changes. Any UPDATE and DELETE statements are qualified with the original values of the data so that should the data have changed in the database in the meantime this will be detected. Assuming no such collisions have occurred the changes will be committed to the database. The application can then continue to work with the data graph, make more changes and apply them, or can discard it.

There are other ways of working with the data in the database: it is possible to just create data objects and write them to the database without a preliminary call to executeQuery(), for example. This scenario and others are explored in the Examples section below.


Installazione

The installation instructions for all the SDO components are in the SDO install section of the SDO documentation.

In any case, the essential facts are that the Relational DAS is written in PHP and it should be placed somewhere on the PHP include_path .

Your application will of course need to include the Relational DAS with a statement like this:
<?php
require_once 'SDO/DAS/Relational.php';
?>


Requisiti

The Relational DAS requires that the SDO extension be installed. The SDO extension requires a version of PHP 5.1, and the Relational DAS requires a recent version that contains an important fix for PDO. The most up-to-date information about required levels of PHP should be found in the changelog for the package on PECL. At the time of writing, though, the Relational DAS requires the most recent beta level of PHP 5.1, that is PHP 5.1.0b3.

The Relational DAS uses PDO to access the relational database, and so should run with a variety of different relational databases. At the time of writing it has been tested in the following configurations

  • MySQL 4.1.17, on Windows. The Relational DAS operates correctly with the php_pdo_mysql driver that comes with the pre-built binaries for PHP 5.1.0b3.

  • MySQL 4.1.17, on Linux. It is necessary to have the most up-to-date PDO driver for MySQL, which comes built in to PHP 5.1.0b3. It may be necessary to uninstall the usual driver that would have come from PECL using pear uninstall pdo_mysql . You will need to configure PHP with the --with-pdo-mysql option.

  • DB2 8.2 Personal Edition, on Windows. The Relational DAS operates correctly with the php_pdo_odbc driver that comes with the pre-built binaries for PHP 5.1.0b3.

  • DB2 8.2 Personal Developer's Edition, on Linux. The Developer's Edition is needed because it contains the include files needed when PHP is configured and built. You will need to configure PHP with the --with-pdo-odbc=ibm-db2 option.

The Relational DAS applies changes to the database within a user-delimited transaction: that is, it issues a call to PDO::beginTransaction() before beginning to apply changes, and PDO::commit() or PDO::rollback() on completion. Whichever database is chosen, the database and the PDO driver for the database must support these calls.


Limitations

There are the following limitations in the current release of the Relational DAS:

  • No support for nulls. There is no support for SQL NULL type. It is not legal to assign PHP NULL to a data object property and the Relational DAS will not write that back as a NULL to the database. If nulls are found in the database on a query, the property will remain unset.

  • Only two types of SDO relationship. The metadata described below allows the Relational DAS to model just two types of SDO relationship: multi-valued containment properties and single-valued non-containment properties. In SDO, whether a property is single- or multi-valued, and whether it is containment or non-containment, are independent. The full range of possibilities that SDO allows cannot all be defined. There may be relationships that it would be useful to model but which the current implementation cannot manage. One example is a single-valued containment relationship.

  • No support for the full range of SDO data types. The Relational DAS defines all primitive properties in the SDO model as being of type string. SDO defines a richer set of types containing various integer, float, boolean and data and time types. String is adequate for the purposes of the Relational DAS since the combination of PHP, PDO and the database will ensure that values passed as strings will be converted to the proper type before being put in the database. This does affect some scenarios in which the Relational DAS has to work with a data graph that has come from or will go to a different DAS.

  • Only one foreign key per table. The metadata only provides the means to specify one foreign key per table. This foreign key may be mapped to one of the two types of SDO relationship supported. Obviously there are some scenarios that cannot be described under this limitation - it is not possible to have two non-containment references from one table to another for example.


Esempi

This section illustrates how the Relational DAS can be used to create, retrieve, update and delete data in a relational database. Many of the examples are illustrated with a three-table database that contains companies, departments within those companies, and employees that work in those departments. This example is used in a number of places within the SDO literature. See the examples section of the Service Data Objects specification or the Examples section of the documentation for the SDO extension.

The Relational DAS is constructed with metadata that defines the relational database and how it should be mapped to SDO. The long section that follows describes this metadata and how to construct the Relational DAS. The examples that follow it all assume that this metadata is in an included php file.

The examples below and others can all be found in the Scenarios directory in the Relational DAS package.

The Relational DAS throws exceptions in the event that it finds errors in the metadata or errors when executing SQL statements against the database. For brevity the examples below all omit the use of try/catch blocks around the calls to the Relational DAS.

These examples all differ from the expected use of SDO in two important respects.

First, they show all interactions with the database completed within one script. In this respect these scenarios are not realistic but are chosen to illustrate just the use of the Relational DAS. It is expected that interactions with the database will be separated in time and the data graph serialised and deserialised into the PHP session one or more times as the application interacts with an end user.

Second, all queries executed against the database use hard-coded queries with no variables substituted. In this case it is safe to use the simple executeQuery() call, and this is what the examples illustrate. In practice, though, it is unlikely that the SQL statement is known entirely ahead of time. In order to allow variables to be safely substituted into the SQL queries, without running the risk of injecting SQL with unknown effects, it is safer to use the executePreparedQuery() which takes a prepared SQL statement containing placeholders and a list of values to be substituted.


Specifying the metadata

This first long section describes in detail how the metadata describing the database and the required SDO model is supplied to the Relational DAS.

When the constructor for the Relational DAS is invoked, it needs to be passed several pieces of information. The bulk of the information, passed as an associative array in the first argument to the constructor, tells the Relational DAS what it needs to know about the relational database. It describes the names of the tables, columns, primary keys and foreign keys. It should be fairly easy to understand what is required, and once written it can be placed in a php file and included when needed. The remainder of the information, passed in the second and third arguments to the constructor, tells the Relational DAS what it needs to know about the relationships between objects and the shape of the data graph; it ultimately determines how the data from the database is to be normalised into a graph.


Database metadata

The first argument to the constructor describes the target relational database.

Each table is described by an associative array with up to four keys.

KeyValue
nameThe name of the table.
columns An array listing the names of the columns, in any order.
PKThe name of the column containing the primary key.
FKAn array with two entries, 'from' and 'to', which define a column containing a foreign key, and a table to which the foreign key points. If there are no foreign keys in the table then the 'FK' entry does not need to be specified. Only one foreign key can be specified. Only a foreign key pointing to the primary key of a table can be specified.

<?php
/*****************************************************************
* METADATA DEFINING THE DATABASE
******************************************************************/
$company_table = array (
    'name' => 'company',
    'columns' => array('id', 'name',  'employee_of_the_month'),
    'PK' => 'id',
    'FK' => array (
        'from' => 'employee_of_the_month',
        'to' => 'employee',
        ),
    );
$department_table = array (
    'name' => 'department', 
    'columns' => array('id', 'name', 'location', 'number', 'co_id'),
    'PK' => 'id',
    'FK' => array (
        'from' => 'co_id',
        'to' => 'company',
        )
    );
$employee_table = array (
    'name' => 'employee',
    'columns' => array('id', 'name', 'SN', 'manager', 'dept_id'),
    'PK' => 'id',
    'FK' => array (
        'from' => 'dept_id',
        'to' => 'department',
        )
    );
$database_metadata = array($company_table, $department_table, $employee_table);
?>

This metadata corresponds to a relational database that might have been defined to MySQL as:

create table company (
   id integer auto_increment,
   name char(20),
   employee_of_the_month integer,
   primary key(id)
 );
 create table department (
   id integer auto_increment,
   name char(20),
   location char(10),
   number integer(3),
   co_id integer,
   primary key(id)
 );
 create table employee (
   id integer auto_increment,
   name char(20),
   SN char(4),
   manager tinyint(1),
   dept_id integer,
   primary key(id)
 );

or to DB2 as:

create table company ( \
    id integer not null generated by default as identity,  \
    name varchar(20), \
    employee_of_the_month integer, \
    primary key(id) )
create table department ( \
    id integer not null generated by default as identity, \
    name varchar(20), \
    location varchar(10), \
    number integer, \
    co_id integer, \
    primary key(id) )
create table employee ( \
    id integer not null generated by default as identity, \
    name varchar(20), \
    SN char(4), \
    manager smallint, \
    dept_id integer, \
    primary key(id) )

Note that although in this example there are no foreign keys specified to the database and so the database is not expected to enforce referential integrity, the intention behind the co_id column on the department table and the dept_id column on the employee table is they should contain the primary key of their containing company or department record, respectively. So these two columns are acting as foreign keys.

There is a third foreign key in this example, that from the employee_of_the_month column of the company record to a single row of the employee table. Note the difference in intent between this foreign key and the other two. The employee_of_the_month column represents a single-valued relationship: there can be only one employee of the month for a given company. The co_id and dept_id columns represent multi-valued relationships: a company can contain many departments and a department can contain many employees. This distinction will become evident when the remainder of the metadata picks out the company-department and department-employee relationships as containment relationships.

There are a few simple rules to be followed when constructing the database metadata:

  • All tables must have primary keys, and the primary keys must be specified in the metadata. Without primary keys it is not possible to keep track of object identities. As you can see from the SQL statements that create the tables, primary keys can be auto-generated, that is, generated and assigned by the database when a record is inserted. In this case the auto-generated primary key is obtained from the database and inserted into the data object immediately after the row is inserted into the database.

  • It is not necessary to specify in the metadata all the columns that exist in the database, only those that will be used. For example, if the company table had another column that the application did not want to access with SDO, this need not be specified in the metadata. On the other hand it would have done no harm to specify it: if specified in the metadata but never retrieved, or assigned to by the application, then the unused column will not affect anything.

  • In the database metadata note that the foreign key definitions identify not the destination column in the table which is pointed to, but the table name itself. Strictly, the relational model permits the destination of a foreign key to be a non-primary key. Only foreign keys that point to a primary key are useful for constructing the SDO model, so the metadata specifies the table name. It is understood that the foreign key points to the primary key of the given table.

Given these rules, and given the SQL statements that define the database, the database metadata should be easy to construct.


What the Relational DAS does with the metadata

The Relational DAS uses the database metadata to form most of the SDO model. For each table in the database metadata, an SDO type is defined. Each column which can represent a primitive value (columns which are not defined as foreign keys) are added as properties to the SDO type.

All primitive properties are given a type of string in the SDO model, regardless of their SQL type. When writing values back to the database the Relational DAS will create SQL statements that treat the values as strings, and the database will convert them to the appropriate type.

Foreign keys are interpreted in one of two ways, depending on the metadata in the third argument to the constructor that defines the SDO containment relationships. A discussion of this is therefore deferred until the section on SDO containment references below.


Specifying the application root type

The second argument to the constructor is the application root type. The true root of each data graph is an object of a special root type and all application data objects come somewhere below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, the application root type can be inferred, and this argument can be omitted.


Specifying the SDO containment references

The third argument to the constructor defines how the types in the model are to be linked together to form a graph. It identifies the parent-child relationships between the types which collectively form a graph. The relationships need to be supported by foreign keys to be found in the data, in a way shortly to be described.

The metadata is an array containing one or more associative arrays, each of which identifies a parent and a child. The example below shows a parent-child relationship from company to department, and another from department to employee. Each of these will become an SDO multi-valued containment property in the SDO model.

<?php
$department_reference = array( 'parent' => 'company', 'child' => 'department');
$employee_reference = array( 'parent' => 'department', 'child' => 'employee');

$SDO_reference_metadata = array($department_reference, $employee_reference);           
?>

Foreign keys in the database metadata are interpreted as either multi-valued containment properties or single-valued non-containment properties, depending on whether they have a corresponding SDO containment reference specified in the metadata. In the example here, the foreign keys from department to company (the co_id column in the department table) and from employee to department (the dept_id column in the employee table) are interpreted as supporting the SDO containment references. Each containment reference mentioned in the SDO containment references metadata must have a corresponding foreign key present in the database and defined in the database metadata. The values of the foreign key columns for containment references do not appear in the data objects, instead they are represented by the containment reference from the parent to the child. So the co_id column in the department row in the database, for example, does not appear as a property on the department type, but instead as a containment relationship called department on the company type. Note that the foreign key and the parent-child relationship appear to have opposite senses: the foreign key points from the department to the company, but the parent-child relationship points from company to department.

The third foreign key in this example, the employee_of_the_month , is handled differently. This is not mentioned in the SDO containment references metadata. As a consequence this is interpreted in the second way: it becomes a single-valued non-containment reference on the company object, to which can be assigned references to SDO data objects of the employee type. It does appear as a property on the company type. The way to assign a value to it in the SDO data graph is to have a graph that contains an employee object through the containment references, and to assign the object to it. This is illustrated in the later examples below.


One-table examples

The following set of examples all use the Relational DAS to work with a data graph containing just one application data object, a single company and the data just to be found the company table. These examples do not exercise the power of SDO or the Relational DAS and of course the same result could be achieved more economically with direct SQL statements but they are intended to illustrate how to work with the Relational DAS.

For this very simple scenario it would be possible to simplify the database metadata to include just the company table - if that were done the second and third arguments to the constructor and the column specifier used in the query example would become optional.

Esempio 1. Creating a data object

The simplest example is that of creating a single data object and writing it to the database. In this example a single company object is created, its name is set to 'Acme', and the Relational DAS is called to write the changes to the database. The company name is set here using the property name method. See the Examples section on the SDO extension for other ways of accessing the properties of an object.

Data objects can only be created when you have a data object to start with, however. It is for that reason that the first call to the Relational DAS here is to obtain a root object. This is in effect how to ask for an empty data graph - the special root object is the true root of the tree. The company data object is then created with a call to createDataObject() on the root object. This creates the company data object and inserts it in the graph by inserting into a multi-valued containment property on the root object called 'company'.

When the Relational DAS is called to apply the changes a simple insert statement 'INSERT INTO company (name} VALUES ("Acme");' will be constructed and executed. The auto-generated primary key will be set into the data object and the change summary will be reset, so that it would be possible to continue working with the same data object, modify it, and apply the newer changes a second time.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Obtain a root object and create a company object underneath.
 * Make a simple change to the data object. 
 ***************************************************************/
$root = $das  -> createRootDataObject();
$acme = $root -> createDataObject('company');

$acme->name = "Acme";

/**************************************************************
 * Get a database connection and write the object to the database
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das -> applyChanges($dbh, $root);
?>

Esempio 2. Retrieving a data object

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

In this example the third argument to executeQuery(), the column specifier is needed as there are other tables in the metadata with column names of name and id. If there were no possible ambiguity it could be omitted.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 ***************************************************************/
$root = $das->executeQuery($dbh,
           'select name, id from company where name="Acme"',
			array('company.name', 'company.id') );			

/**************************************************************
 * Echo name and id 
 ***************************************************************/
foreach ($root['company'] as $company) {
	echo "Company obtained from the database has name = " . 
    $company['name'] . " and id " . $company['id'] . "\n";
}
?>

Esempio 3. Updating a data object

This example combines the previous two, in the sense that in order to be updated the object must first be retrieved. The application code reverses the company name (so 'Acme' becomes 'emcA') and then the changes are written back to the database in the same way that they were when the object was created. Because the query searches for the name both ways round the program can be run repeatedly to find the company and reverse its name each time.

In this example the same instance of the Relational DAS is reused for the applyChanges(), as is the PDO database handle. This is quite alright; it also alright to allow the previous instances to be garbage collected and to obtain new instances. No state data regarding the graph is held the Relational DAS once it has returned a data graph to the application. All necessary data is either within the graph itself, or can be reconstructed from the metadata.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 ***************************************************************/
$root = $das->executeQuery($dbh,
    'select name, id from company where name="Acme" or name="emcA"',
    array('company.name', 'company.id') );

/**************************************************************
 * Alter the name of just the first company
 ***************************************************************/
$company = $root['company'][0];
echo "obtained a company with name of " . $company->name . "\n";
$company->name = strrev($company->name);

/**************************************************************
 * Write the change back
 ***************************************************************/
$das->applyChanges($dbh,$root);
?>

Esempio 4. Deleting a data object

Any companies called 'Acme' or its reverse 'emcA' are retrieved. They are then all deleted from the graph with unset.

In this example they are all deleted in one go by unsetting the containing reference. It is also possible to delete them individually.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 ***************************************************************/
$root = $das->executeQuery($dbh,
    'select name, id from company where name="Acme" or name="emcA"',
    array('company.name', 'company.id') );

/**************************************************************
 * Delete any companies found from the data graph
 ***************************************************************/
unset($root['company']);

/**************************************************************
 * Write the change(s) back
 ***************************************************************/
$das->applyChanges($dbh,$root);
?>


Two-table examples

The following set of examples all use two tables from the company database: the company and department tables. These examples exercise more of the function of the Relational DAS.

In this series of examples a company and department are created, retrieved, updated, and finally deleted. This illustrates the lifecycle for a data graph containing more than one object. Note that this example clears out the company and department tables at the start so that the exact results of the queries can be known.

You can find these examples combined into one script called 1cd-CRUD in the Scenarios directory in the Relational DAS package.

Esempio 5. One company, one department - Create

As in the earlier example of creating just one company data object, the first action after constructing the Relational DAS is to call createRootDataObject() to obtain the special root object of the otherwise empty data graph. The company object is then created as a child of the root object, and the department object as a child of the company object.

When it comes to applying the changes, the Relational DAS has to perform special processing to maintain the foreign keys that support the containment relationships, especially if auto-generated primary keys are involved. In this example, the relationship between the auto-generated primary key id in the company table and the co_id column in the department table must be maintained. When inserting a company and department for the first time the Relational DAS has to first insert the company row, then call PDO's getLastInsertId() method to obtain the auto-generated primary key, then add that as the value of the co_id column when inserting the department row.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the two tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();

/**************************************************************
* Create a company with name Acme and one department, the Shoe department
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

$root = $das -> createRootDataObject();

$acme = $root -> createDataObject('company');
$acme -> name = "Acme";

$shoe = $acme->createDataObject('department');
$shoe->name = 'Shoe';

$das -> applyChanges($dbh, $root);

?>

Esempio 6. One company, one department - Retrieve and Update

In this case the SQL query passed to executeQuery() performs an inner join to join the data from the company and department tables. Primary keys for both the company and department tables must be included in the query. The result set is re-normalised to form a normalised data graph. Note that a column specifier is passed as the third argument to the executeQuery() call enabling the Relational DAS to know which column is which in the result set.

Note that the co_id column although used in the query is not needed in the result set. In order to understand what the Relational DAS is doing when it builds the data graph it may be helpful to visualise what the result set looks like. Although the data in the database is normalised, so that multiple department rows can point through their foreign key to one company row, the data in the result set is non-normalised: that is, if there is one company and multiple departments, the values for the company are repeated in each row. The Relational DAS has to reverse this process and turn the result set back into a normalised data graph, with just one company object.

In this example the Relational DAS will examine the result set and column specifier, find data for both the company and department tables, find primary keys for both, and interpret each row as containing data for a department and its parent company. If it has not seen data for that company before (it uses the primary key to check) it creates a company object and then a department object underneath it. If it has seen data for that company before and has already created the company object it just creates the department object underneath.

In this way the Relational DAS can retrieve and renormalise data for multiple companies and multiple departments underneath them.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Retrieve the company and Shoe department, then delete Shoe and add IT
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];            // get the first company - will be 'Acme'
$shoe = $acme['department'][0];         // get the first department underneath - will be 'Shoe'

unset($acme['department'][0]);

$it = $acme->createDataObject('department');
$it->name = 'IT';

$das -> applyChanges($dbh, $root);
?>

Esempio 7. One company, two departments - Retrieve and Delete

In this example the company and department are retrieved and then deleted. It is not necessary to delete them individually (although that would be possible) - deleting the company object from the data graph also deletes any departments underneath it.

Note the way that the company object is actually deleted using the PHP unset call. The unset has to be performed on the containing reference which in this case is the company reference on the special root object. You must use:
<?php
unset($root['company'][0]);
?>
and not:
<?php
unset($acme); //WRONG
?>
Simply unsetting $acme would destroy the variable but leave the data in the data graph untouched.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Retrieve the company and IT department, then delete the whole company
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];
$it = $acme['department'][0];

unset($root['company'][0]);

$das -> applyChanges($dbh, $root);

?>


Three-table example

The following examples use all three tables from the company database: the company, department, and employee tables. These introduce the final piece of function not exercised by the examples above: the non-containment reference employee_of_the_month.

Like the examples above for company and department, this set of examples is intended to illustrate the full lifecycle of such a data graph.

Esempio 8. One company, one department, one employee - Create

In this example a company is created containing one department and just one employee. Note that this example clears out all three tables at the start so that the exact results of the queries can be known.

Note how once the company, department and employee have been created, the employee_of_the_month property of the company can be made to point at the new employee. As this is a non-containment reference, this cannot be done until the employee object has been created within the graph. Non-containment references need to be managed carefully. For example if the employee were now deleted from under the department, it would not be correct to try to save the graph without first clearing or re-assigning the employee_of_the_month property. The closure rule for SDO data graphs requires that any object pointed at by a non-containment reference must also be reachable by containment references.

When it comes to inserting the graph into the database, the procedure is similar to the example of inserting the company and department, but employee_of_the_month introduces an extra complexity. The Relational DAS needs to insert the objects working down the tree formed by containment references, so company, then department, then employee. This is necessary so that it always has the auto-generated primary key of a parent on hand to include in a child row. But when the company row is inserted the employee who is employee of the month has not yet been inserted and the primary key is not known. The procedure is that after the employee record is inserted and its primary key known, a final step is performed in which the the company record is updated with the employee's primary key.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the three tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM EMPLOYEE;');
$rows_affected = $pdo_stmt->execute();

/*************************************************************************************
* Create a tiny but complete company.
* The company name is Acme.
* There is one department, Shoe.
* There is one employee, Sue.
* The employee of the month is Sue.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root 			= $das  -> createRootDataObject();
$acme 			= $root -> createDataObject('company');
$acme -> name 	= "Acme";
$shoe 			= $acme -> createDataObject('department');
$shoe -> name 	= 'Shoe';
$shoe -> location = 'A-block';
$sue 			= $shoe -> createDataObject('employee');
$sue -> name 	= 'Sue';
$acme -> employee_of_the_month = $sue;

$das -> applyChanges($dbh, $root);

echo "Wrote back Acme with one department and one employee\n";
?>

Esempio 9. One company, one department, one employee - Retrieve and update

The SQL statement passed to the Relational DAS is this time an inner join that retrieves data from all three tables. Otherwise this example introduces nothing that has not appeared in a previous example.

The graph is updated by the addition of a new department and employee and some alterations to the name properties of the existing objects in the graph. The combined changes are then written back. The Relational DAS will process and apply an arbitrary mixture of additions, modifications and deletions to and from the data graph.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
 * Find the company again and change various aspects.
 * Change the name of the company, department and employee.
 * Add a second department and a new employee.
 * Change the employee of the month.
 *************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
    "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
    "from company c, department d, employee e " .
    "where e.dept_id = d.id and d.co_id = c.id and c.name='Acme'",
     array('company.id','company.name','company.employee_of_the_month',
     'department.id','department.name','employee.id','employee.name'));
$acme 	= $root['company'][0];

$shoe	= $acme->department[0];
$sue	= $shoe -> employee[0];

$it 	= $acme->createDataObject('department');
$it->name = 'IT';
$it->location = 'G-block';
$billy 	= $it->createDataObject('employee');
$billy->name = 'Billy';

$acme->name = 'MegaCorp';
$shoe->name = 'Footwear';
$sue->name = 'Susan';

$acme->employee_of_the_month = $billy;
$das -> applyChanges($dbh, $root);
echo "Wrote back company with extra department and employee and all the names changed (Megacorp/Footwear/Susan)\n";

?>

Esempio 10. One company, two departments, two employees - Retrieve and delete

The company is retrieved as a complete data graph containing five data objects - the company, two departments and two employees. They are all deleted by deleting the company object. Deleting an object from the graph deletes all the object beneath it in the graph. Five SQL DELETE statements will be generated and executed. As always they will be qualified with a WHERE clause that contains all of the fields that were retrieved, so that any updates to the data in the database in the meantime by another process will be detected.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
 * Now read it one more time and delete it.
 * You can delete part, apply the changes, then carry on working with the same graph but
 * care is needed to keep closure - you cannot delete the employee who is eotm without
 * reassigning. For safety here we delete the company all in one go. 
 *************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
    "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
    "from company c, department d, employee e " .
    "where e.dept_id = d.id and d.co_id = c.id and c.name='MegaCorp';",
     array('company.id','company.name','company.employee_of_the_month',
     'department.id','department.name','employee.id','employee.name'));
$megacorp = $root['company'][0];

unset($root['company']);
$das -> applyChanges($dbh, $root);

echo "Deleted the company, departments and employees all in one go.\n";

?>


Tracing

You may be interested in seeing the SQL statements that are generated in order to apply changes back to the database. At the top of the SDO/DAS/Relational.php you will find a number of constants which control whether the process of constructing and executing the SQL statements is to be traced. Try setting DEBUG_EXECUTE_PLAN to TRUE to see the generated SQL statements.


Classi predefinite

The Relational DAS provides two classes: the Relational DAS itself and the subclass of Exception that can be thrown. The Relational DAS has four publicly useful calls: the constructor, the createRootDataObject() call to obtain the root object of an empty data graph, the executeQuery() call to obtain a data graph containing data from a relational database, and the applyChanges() call to write changes made to a data graph back to the relational database.


SDO_DAS_Relational

The only object other than an SDO_DAS_Relational_Exception with which the application is expected to interact.


Metodi

  • __construct - construct the Relational DAS with a model derived from the passed metadata

  • createRootDataObject - obtain an otherwise empty data graph containing just the special root object

  • executeQuery - execute an SQL query passed as a literal string and return the results as a normalised data graph

  • executePreparedQuery - execute an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

  • applyChanges - examine the change summary in the data graph and apply those changes back to the database, subject to an assumption of optimistic concurrency


SDO_DAS_Relational_Exception

Is a subclass of PHP's Exception. It adds no behaviour to Exception. Thrown, with useful descriptive text, to signal errors in the metadata or unexpected failures to perform SQL operations.

Sommario
SDO_DAS_Relational::applyChanges --  Applies the changes made to a data graph back to the database.
SDO_DAS_Relational::__construct --  Creates an instance of a Relational Data Access Service
SDO_DAS_Relational::createRootDataObject --  Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
SDO_DAS_Relational::executePreparedQuery --  Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
SDO_DAS_Relational::executeQuery --  Executes a given SQL query against a relational database and returns the results as a normalised data graph.

SDO_DAS_Relational::applyChanges

(no version information, might be only in CVS)

SDO_DAS_Relational::applyChanges --  Applies the changes made to a data graph back to the database.

Descrizione

void SDO_DAS_Relational::applyChanges ( PDO database_handle, SDODataObject root_data_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.

Given a PDO database handle and the special root object of a data graph, examine the change summary in the datagraph and applies the changes to the database. The changes that it can apply can be creations of data objects, deletes of data objects, and modifications to properties of data objects.

Elenco dei parametri

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:
$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

root_data_object

The special root object which is at the top of every SDO data graph.

Valori restituiti

None. Note however that the datagraph that was passed is still intact and usable. Furthermore, if data objects were created and written back to a table with autogenerated primary keys, then those primary keys will now be set in the data objects. If the changes were successfully written, then the change summary associated with the datagraph will have been cleared, so that it is possible to now make further changes to the data graph and apply those changes in turn. In this way it is possible to work with the same data graph and apply changes repeatedly.

Eccezioni

SDO_DAS_Relational::applyChanges() can throw an SDO_DAS_Relational_Exception if it is unable to apply all the changes correctly.

The Relational DAS starts a database transaction before beginning to apply the changes and will commit the transaction only if they are all successful. The Relational DAS generates qualified update and delete statements which contain a where clause that specifies that the row to be updated or deleted must contain the same values that it did when the data was first retrieved. This is how the the optimistic concurrency is implemented. If any of the qualified update or delete statements fails to update or delete their target row, it may be because the data has been altered in the database in the meantime. In any event, if any update fails for any reason, the transaction is rolled back and an exception thrown. The exception will contain the generated SQL statement that failed.

The Relational DAS also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Esempi

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method. Please see also the section on Tracing to see how you can see what SQL statements are generated by the Relational DAS.

SDO_DAS_Relational::__construct

(no version information, might be only in CVS)

SDO_DAS_Relational::__construct --  Creates an instance of a Relational Data Access Service

Descrizione

SDO_DAS_Relational SDO_DAS_Relational::__construct ( array database_metadata [, string application_root_type [, array SDO_containment_references_metadata]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Constructs an instance of a Relational Data Access Service from the passed metadata.

Elenco dei parametri

database_metadata

An array containing one or more table definitions, each of which is an associative array containing the keys name, columns, PK, and optionally, FK. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

application_root_type

The root of each data graph is an object of a special root type and the application data objects come below that. Of the various application types in the SDO model, one has to be the the application type immediately below the root of the data graph. If there is only one table in the database metadata, so the application root type can be inferred, this argument can be omitted.

SDO_containment_references_metadata

An array containing one or more definitions of a containment relation, each of which is an associative array containing the keys parent and child. The containment relations describe how the types in the model are connected to form a tree. The type specified as the application root type must be present as one of the parent types in the containment references. If the application only needs to work with one table at a time, and there are no containment relations in the model, this argument can be omitted. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

Valori restituiti

Returns an SDO_DAS_Relational object on success.

Eccezioni

SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.

Esempi

For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

SDO_DAS_Relational::createRootDataObject

(no version information, might be only in CVS)

SDO_DAS_Relational::createRootDataObject --  Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.

Descrizione

SDODataObject SDO_DAS_Relational::createRootDataObject ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Returns the special root object at the top of an otherwise empty data graph. This call is used when the application wants to create a data graph from scratch, without having called executeQuery() to create a data graph.

The special root object has one multi-valued containment property, with a name of the application root type that was passed when the Relational DAS was constructed. The property can take values of only that type. The only thing that the application can usefully do with the root type is to call createDataObject() on it, passing the name of the application root type, in order to create a data object of their own application type.

Elenco dei parametri

None.

Valori restituiti

The root object.

Eccezioni

None.

Esempi

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

SDO_DAS_Relational::executePreparedQuery

(no version information, might be only in CVS)

SDO_DAS_Relational::executePreparedQuery --  Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.

Descrizione

SDODataObject SDO_DAS_Relational::executePreparedQuery ( PDO database_handle, PDOStatement prepared_statement, array value_list [, array column_specifier] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Executes a given query against the relational database, using the supplied PDO database handle. Differs from the simpler executeQuery() in that it takes a prepared statement and a list of values. This is the appropriate call to use either when the statement is to executed a number of times with different arguments, and there is therefore a performance benefit to be had from preparing the statement only once, or when the the SQL statement is to contain varying values taken from a source that cannot be completely trusted. In this latter case it may be unsafe to construct the SQL statement by simply concatenating the parts of the statement together, since the values may contain pieces of SQL. To guard against this, a so-called SQL injection attack, it is safer to prepare the SQL statement with placeholders (also known as parameter markers, denoted by '?') and supply a list of the values to be substituted as a separate argument. Otherwise this function is the same as executeQuery() in that it uses the model that it built from the the metadata to interpret the result set and returns a data graph.

Elenco dei parametri

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:
$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

prepared_statement

A prepared SQL statement to be executed against the database. This will have been prepared by PDO's prepare() method.

value_list

An array of the values to be substituted into the SQL statement in place of the placeholders. In the event that there are no placeholders or parameter markers in the SQL statement then this argument can be specified as NULL or as an empty array;

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata, For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Valori restituiti

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Eccezioni

SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Esempi

Esempio 1. Retrieving a data object using executePreparedQuery()

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

Other examples of the use of executePreparedQuery() can be found in the example code supplied in sdo/DAS/Relational/Scenarios .

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 * Use a prepared query with a placeholder.
 ***************************************************************/
$name = 'Acme';
$pdo_stmt = $dbh->prepare('select name, id from company where name=?');
$root = $das->executePreparedQuery(
    $dbh, 
    $pdo_stmt,
    array($name), 
    array('company.name', 'company.id'));

/**************************************************************
 * Echo name and id 
 ***************************************************************/
foreach ($root['company'] as $company) {
	echo "Company obtained from the database has name = " . 
    $company['name'] . " and id " . $company['id'] . "\n";
}
?>

SDO_DAS_Relational::executeQuery

(no version information, might be only in CVS)

SDO_DAS_Relational::executeQuery --  Executes a given SQL query against a relational database and returns the results as a normalised data graph.

Descrizione

SDODataObject SDO_DAS_Relational::executeQuery ( PDO database_handle, string SQL_statement [, array column_specifier] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Executes a given query against the relational database, using the supplied PDO database handle. Uses the model that it built from the the metadata to interpret the result set. Returns a data graph.

Elenco dei parametri

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:
$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

SQL_statement

The SQL statement to be executed against the database.

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata. For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Valori restituiti

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Eccezioni

SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Esempi

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

CXXXI. Funzioni per i semafori, la memoria condivisa ed IPC

Introduzione

Questo modulo fornisce le funzioni relative all'IPC di System V. Queste includono semafori, memoria condivisa e messaggi tra i processi (IPC).

I semafori possono essere utilizzati per fornire un accesso esclusivo alle risorse sulla macchina corrente, oppure per limitare il numero di processi che possono utilizzare simultaneamente una risorsa.

Questo modulo fornisce anche le funzioni per la memoria condivisa a partire dalla gestione della memoria condivisa di System V. La memoria condivisa può essere utilizzata per fornire l'accesso a variabili globali. Differenti demoni httpd e anche altri programmi (tipo Perl, C, ...) sono in grado di accedere a questi dati creando uno scambio di dati globale. Si ricordi che la memoria condivisa non è garantita nei confronti di accessi simultanei. Si utilizzino i semafori per la sincronizzazione.

Tabella 1. Limiti della memoria condivisa posti da UNIX

SHMMAXdimensione massima della memoria condivisa, solitamente 131072 bytes
SHMMINdimensione minima della memoria condivisa, solitamente 1 byte
SHMMNI massimo ammontare dei segmenti di memoria condivisa sul sistema, solitamente 100
SHMSEG numero massimo di segmenti di memoria condivisa per processo, solitamente 6

Le funzioni relative ai messaggi possono essere usate per inviare e ricevere messaggi da/per altri processi. Esse permettono un semplice ed efficace metodo di interscambio dati tra i processi, senza dovere ricorrere ad alternative quali i socket nel dominio Unix.

Nota: Questo modulo non è disponibile su piattaforme Windows.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Di default non viene abilitato il supporto per queste funzioni. Per abilitare il supporto dei semafori di System V, compilare il PHP con l'opzione --enable-sysvsem. Per abilitare il supporto della memoria condivisa, compilare il PHP con l'opzione --enable-sysvshm. Per abilitare il supporto dei messaggi, compilare il PHP con l'opzione --enable-sysvmsg.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 2. Opzioni per la configurazione dei Semafori

NomeDefaultModificabileVariazioni
sysvmsg.value"42"PHP_INI_ALL 
sysvmsg.string"foobar"PHP_INI_ALL 
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Costanti predefinite

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 3. Costanti per i messaggi System V

CostanteTipo
MSG_IPC_NOWAITinteger
MSG_NOERRORinteger
MSG_EXCEPTinteger

Sommario
ftok --  Converte il percorso e un identificatore di progetto in un chiave IPC di System V
msg_get_queue --  Crea, o si collega ad una coda di messaggi
msg_receive --  Riceve un messaggio da una coda
msg_remove_queue --  Distrugge una coda di messaggi
msg_send --  Invia un messaggio ad una coda di messaggi
msg_set_queue --  Valorizza le informazioni nella struttura dati della coda dei messaggi
msg_stat_queue --  Restituisce informazioni dalla struttura dati della coda
sem_acquire -- Acquisisce un semaforo
sem_get -- Ottiene l'id di un semaforo
sem_release -- Rilascia un semaforo
sem_remove -- Rimuove un semaforo
shm_attach -- Crea oppure apre un segmento di memoria condivisa
shm_detach -- Disconnette da un segmento di memoria condivisa
shm_get_var -- Restituisce una variabile dalla memoria condivisa
shm_put_var --  Inserisce o aggiorna una variabile nella memoria condivisa
shm_remove_var -- Rimuove una variabile dalla memoria condivisa
shm_remove -- Rimuove un segmento di memoria condivisa dal sistema Unix

ftok

(PHP 4 >= 4.2.0, PHP 5)

ftok --  Converte il percorso e un identificatore di progetto in un chiave IPC di System V

Descrizione

int ftok ( string pathname, string proj )

La funzione converte il parametro pathname di un file accessibile e l'identificatore di un progetto (proj) in un numero interger da utilizzare, ad esempio, con shmop_open() e le altre chiavi IPC di System V. Il parametro proj dovrebbe essere una stringa di un carattere.

Se la funzione riesce sarà restituito il valore della chiave creata, altrimenti si restituirà -1.

Vedere anche: shmop_open() e sem_get().

msg_get_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_get_queue --  Crea, o si collega ad una coda di messaggi

Descrizione

resource msg_get_queue ( int chiave [, int permessi] )

La funzione msg_get_queue() restituisce un id che può essere utilizzato per accedere alla coda dei messaggi System V con la data chiave. La prima chiamata crea la coda dei messaggi con i permessi indicati da permessi (default: 0666). La seconda chiamata alla funzione msg_get_queue() per la medesima chiave restituirà un identificatore di coda di messaggi differente, ma entrambi accederanno alla medesima coda di messaggi. Se la coda dei messaggi esiste già, il parametro permessi sarà ignorato.

Vedere anche: msg_remove_queue(), msg_receive(), msg_send(), msg_stat_queue() e msg_set_queue().

msg_receive

(PHP 4 >= 4.3.0, PHP 5)

msg_receive --  Riceve un messaggio da una coda

Descrizione

bool msg_receive ( resource coda, int tipo_desiderato, int &tipo_messaggio, int dimensione_max, mixed &messaggio [, bool unserialize [, int flags [, int codice_errore [, int &codice_errore]]]] )

La funzione msg_receive() riceve il primo messaggio dalla coda specificata in coda del tipo indicato in tipo_desiderato. Il tipo di messaggio che è stato ricevuto viene memorizzato in tipo_messaggio. La dimensione massima del messaggio accettata viene indicata in dimensione_max; se il messaggio nella coda è più grande, la funzione darà esito negativo (a meno che non sia impostato il parametro flags come descritto in seguito). Il messaggio ricevuto sarà memorizzato in messaggio, a meno che non si verifichino degli errori in ricezione, in tal caso il parametro opzionale errorcode sarà valorizzato con il valore della variabile errno per aiutare ad identificare la causa.

Se il parametro tipo_desiderato è 0, verrà restituito il primo messaggio dalla coda. Se, invece, tipo_desiderato è maggiore di 0, sarà restuito il primo messaggio di quel tipo. Mentre se tipo_desiderato è minore di 0, sarà restituito dalla coda il primo messaggio con il tipo più basso o uguale al valore assoluto di tipo_desiderato. Se nessun messaggio soddisfa i criteri impostati, lo script attenderà fino all'arrivo nella coda di un messaggio adeguato. Si può evitare il blocco dello script indicando MSG_IPC_NOWAIT nel parametro flags.

Il parametro unserialize (default TRUE), se viene impostato a TRUE indica di trattare il messaggio come se fosse serializzato utilizzando lo stesso meccanismo del modulo delle sessioni. In tal modo il messaggio può essere deserializzato e restituito allo script. Questo permette di ricevere facilmente array o complesse strutture oggetto da altri script PHP, o, se si sta utilizzando il serializzatore WDDX, da sorgenti compatibili con WDDX. Se unserialize è impostato a FALSE, il messaggio sarà restituito come una stringa.

Il parametro opzionale flags permette di passare flag alla chiamata di sistema msgrcv. Il default è 0, ma possono essere specificati uno o più dei seguenti valori (sommandoli o legandoli con OR).

Tabella 1. Valori dei flag per msg_receive

MSG_IPC_NOWAITSe non ci sono messaggi del tipo_desiderato, la funzione ritorna immediatamente senza aspettare. La funzione fallirà e restituirà un valore intero corrispondente a ENOMSG.
MSG_EXCEPTUsando questo flag in combinazione con tipo_desiderato maggiore di 0, si forza la funzione a ricevere il primo messaggio che non sia uguale a tipo_desiderato.
MSG_NOERROR Se il messaggio è più lungo di dimensione_max, l'attivazione di questo flag troncherà il messaggio a dimensione_max e non sarà segnalato alcun errore.

Una volta eseguita con successo la ricezione, la struttura dati della coda dei messaggi verrà aggiornata come segue: msg_lrpid sarà impostato all'ID di processo del processo chiamante, msg_qnum verrà decrementato di 1 e msg_rtime sarà impostato all'ora corrente.

La funzione msg_receive() restituisce TRUE se ha successo oppure FALSE se non riesce. Se la funzione fallisce, il parametro opzionale codice_errore verrà impostato al valore della variabile errno.

Vedere anche: msg_remove_queue(), msg_send(), msg_stat_queue() e msg_set_queue().

msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_remove_queue --  Distrugge una coda di messaggi

Descrizione

bool msg_remove_queue ( resource coda )

La funzione msg_remove_queue() rimuove la coda di messaggi specificata dal parametro coda. Si utilizzi questa funzione solo quando tutti i processi hanno terminato di lavorare con la coda dei messaggi e si ha la necessità di rilasciare le risorse di sistema occupate.

Vedere anche: msg_get_queue(), msg_receive(), msg_stat_queue() e msg_set_queue().

msg_send

(PHP 4 >= 4.3.0, PHP 5)

msg_send --  Invia un messaggio ad una coda di messaggi

Descrizione

bool msg_send ( resource coda, int tipo_messaggio, mixed messaggio [, bool serialize [, bool blocco [, int &codice_errore]]] )

La funzione msg_send() invia il messaggio di tipo tipo_messaggio (che DEVE essere maggiore di 0) ad una coda di messaggi indicata in coda.

Se il messaggio è troppo grande per essere contenuto nella coda, lo script attenderà fino a quando un'altro processo, leggendo i messaggi dalla coda, non libera lo spazio necessario per il messaggio da inviare. Questo viene detto blocco; si può prevenire il blocco indicando nel parametro opzionale blocco il valore FALSE, in questo caso msg_send() restituirà immediatamente FALSE se il messaggio è troppo grande per la coda, e impostando il parametro opzionale codice_errore a EAGAIN, si indica di ritentare l'invio del messaggio dopo poco tempo.

Il parametro opzionale serialize controlla come inviare il messaggio. serialize, quando è impostato al valore di default TRUE, indica che il messaggio, prima di essere inviato alla coda, deve essere serializzato utilizzando il medesimo meccanismo del modulo delle sessioni. Questo permette ad array complessi o ad oggetti di essere inviati ad altri script PHP, oppure, se si sta usando il modulo di serializzazione di WDDX, di essere inviati a client compatibili con WDDX.

Una volta eseguito con successo l'invio, la struttura dati della coda dei messaggi viene aggiornata come segue: msg_lspid viene impostato all'ID di processo del processo chiamante, msg_qnum viene incrementato di 1 e msg_stime viene impostato all'ora corrente.

Vedere anche: msg_remove_queue(), msg_receive(), msg_stat_queue() e msg_set_queue().

msg_set_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_set_queue --  Valorizza le informazioni nella struttura dati della coda dei messaggi

Descrizione

bool msg_set_queue ( resource coda, array dati )

msg_set_queue() permette di modificare i valori dei campi msg_perm.uid, msg_perm.gid, msg_perm.mode e msg_qbytes della sottostante struttura dati della coda. Per specificare il valore, occorre impostare il valore nella chiave dell'array dati che si desidera modificare.

Per potere cambiare la struttura dati occorre che il PHP sia eseguito con lo stesso utente che ha creato la coda, sia proprietario della coda (code determinato dal campo msg_perm.xxx), o sia eseguito con i privilegi di root. Sono richiesti i privilegi di root per potere aumentare msg_qbytes a valori superiori ai limiti definiti dal sistema.

Vedere anche: msg_remove_queue(), msg_receive(), msg_stat_queue() e msg_get_queue().

msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_stat_queue --  Restituisce informazioni dalla struttura dati della coda

Descrizione

array msg_stat_queue ( resource coda )

msg_stat_queue() restituisce i dati della coda dei messaggi indicata in coda. Questo può essere utile, ad esempio, per determinare quale processo ha inviato il messaggio che è stato appena ricevuto.

Il valore restituito è un array le cui chiavi e valori hanno il seguente significato:

Tabella 1. Struttura dell'array di msg_stat_queue

msg_perm.uid Il parametro uid del proprietario della coda
msg_perm.gid Il parametro gid del proprietario della coda.
msg_perm.mode La modalità di accesso alla coda.
msg_stime L'orario in cui è stato inserito in coda l'ultimo messaggio.
msg_rtime L'orario in cui l'ultimo messaggio è stato ricevuto dalla coda.
msg_ctime L'orario in cui è avvenuta l'ultima modifica alla coda.
msg_qnum Il numero di messaggi in attesa di essere letti dalla coda.
msg_qbytes Il numero di byte dello spazio attualemnet disponibile nella coda per trattenere i messaggi fino a quando non sono ricevuti.
msg_lspid Il pid del processo che ha inviato l'ultimo messaggio.
msg_lrpid Il pid del processo che ha ricevuto l'ultimo messaggio dalla coda.

Vedere anche: msg_remove_queue(), msg_receive(), msg_get_queue() e msg_set_queue().

sem_acquire

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sem_acquire -- Acquisisce un semaforo

Descrizione

bool sem_acquire ( resource sem_identifier )

La funzione sem_acquire() si blocca (se necessario) fino a quando non riesce ad acquisire il semaforo. Se un processo tenta di acquisire un semaforo che ha già acquisito può restare bloccato per sempre se la nuova acquisizione del semaforo causa il superamento del numero massimo di semafori consentito. sem_identifier è una risorsa semaforo ottenuta da sem_get().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Dopo avere processato una richiesta, qualsiasi semaforo acquisito dal processo, ma non esplicitamente rilasciato, sarà rilasciato automaticamente e causerà un messaggio di warning.

Vedere anche: sem_get() e sem_release().

sem_get

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sem_get -- Ottiene l'id di un semaforo

Descrizione

resource sem_get ( int key [, int max_acquire [, int perm [, int auto_release]]] )

La funzione sem_get() restituisce un identificativo che può essere utilizzato per accedere al semaforo con chiave indicata in key. Se necessario il semaforo viene creato con i bit dei permessi valorizzati come specificato in perm (di default 666). In max_acquire è indicato il numero massimo di processi che possono acquisire il semaforo simultaneamente (1 per default). In realtà questo valore è modificabile solo se il processo è l'unico, in quel momento, ad essere collegato al semaforo.

Il parametro facoltativo auto_release indica se il semaforo deve essere rilasciato automaticamente alla richiesta di shutdown. Parametro disponibile dal PHP 4.3.0.

La funzione ritorna un identificatore positivo di semaforo se ha successo, oppure FALSE se si verifica un errore.

Una seconda chiamata a sem_get() per la medesima chiave restituisce un identificativo di semaforo differente, ma entrambi gli gli identificativi accedono al medesimo semaforo sottostante.

Vedere anche: sem_acquire(), sem_release() e ftok().

sem_release

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sem_release -- Rilascia un semaforo

Descrizione

bool sem_release ( resource sem_identifier )

La funzione sem_release() rilascia il semaforo se questo è attualmente acquisito dal processo chiamante. In caso contrario sarà generato un messaggio di warning.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Dopo avere rilasciato un semaforo, occorre eseguire di nuovo sem_acquire() per ri-acquisirlo.

Vedere anche: sem_get() e sem_acquire().

sem_remove

(PHP 4 >= 4.1.0, PHP 5)

sem_remove -- Rimuove un semaforo

Descrizione

bool sem_remove ( resource sem_identifier )

La funzione sem_remove() rimuove il semaforo indicato da sem_identifier se questo è stato generato in orecedenza da sem_get(). In caso contrario si genera un messaggio di warning

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Una volta rimosso, il semaforo non è più accessibile.

Vedere anche: sem_get(), sem_release() e sem_acquire().

shm_attach

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_attach -- Crea oppure apre un segmento di memoria condivisa

Descrizione

int shm_attach ( int key [, int memsize [, int perm]] )

La funzione shm_attach() restituisce un identificativo che può essere utilizzato per accedere alla memoria condivisa identificata dalla chiave key la prima chiamata crea il segmento di memoria condivisa di dimensione memsize (la dimensione di default può essere indicata in sysvshm.init_mem in php.ini, altrimenti viene fissata a 10000 bytes) e con i bit dei permessi (default: 0666).

Una seconda chiamata alla funzione shm_attach() con il medesimo parametro key restituirà un identificativo di memoria condivisa differente, ma entrambi accederanno alla medesima memoria condivisa sottostante. I parametri Memsize e perm saranno ignorati.

Vedere anche: ftok() e shm_detach().

shm_detach

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_detach -- Disconnette da un segmento di memoria condivisa

Descrizione

bool shm_detach ( int shm_identifier )

La funzione shm_detach() disconnette dal segmento di memoria condivisa indicato dal parametro shm_identifier creato tramite la funzione shm_attach(). Si ricordi che la memoria condivisa continua a esistere nel sistema Unix e i dati sono ancora presenti.

La funzione shm_detach() restituisce sempre TRUE.

Vedere anche shm_attach(), shm_remove() e shm_remove_var().

shm_get_var

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_get_var -- Restituisce una variabile dalla memoria condivisa

Descrizione

mixed shm_get_var ( int shm_identifier, int variable_key )

La funzione shm_get_var() restituisce la variabile identificata dalla chiave variable_key, da un segmento di memoria condivisa identificato tramite shm_identifier. La variabile resta presente nella memoria condivisa.

shm_put_var

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_put_var --  Inserisce o aggiorna una variabile nella memoria condivisa

Descrizione

bool shm_put_var ( int shm_identifier, int variable_key, mixed variable )

La funzione shm_put_var() inserisce o aggiorna la variabile indicata in variable con chiave variable_key. Sono suportati Tutti i tipi di variabili sono supportati.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Verrà generato un warning (E_WARNING level) se il parametro shm_identifier non è un puntatore valido ad un segmento di memoria condivisa SysV oppure se non vi è sufficiente memoria condivisa per completare la richiesta.

shm_remove_var

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_remove_var -- Rimuove una variabile dalla memoria condivisa

Descrizione

int shm_remove_var ( int shm_identifier, int variable_key )

Rimuove la variabile identificata da variable_key e libera la memoria occupata.

Vedere anche shm_remove().

shm_remove

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

shm_remove -- Rimuove un segmento di memoria condivisa dal sistema Unix

Descrizione

int shm_remove ( int shm_identifier )

La funzione shm_remove() rimuove un segmento di memoria condivisa identificata da shm_identifier. Tutti i dati contenuti saranno persi.

Vedere anche shm_remove_var().

CXXXII. SESAM Database Functions

Introduzione

SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.

In numerous productive BS2000 installations, SESAM/SQL-Server has proven

  • the ease of use of Java-, Web- and client/server connectivity,

  • the capability to work with an availability of more than 99.99%,

  • the ability to manage tens and even hundreds of thousands of users.

There is a PHP 3 SESAM interface available which allows database operations via PHP-scripts.

Nota: Access to SESAM is only available with the latest CVS-Version of PHP 3. PHP 4 does not support the SESAM database.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

sesam_oml string

Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions. The BS2000 PLAM library must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.

sesam_configfile string

Name of SESAM application configuration file. Required for using SESAM functions. The BS2000 file must be readable by the apache server's user id.

The application configuration file will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

sesam_messagecatalog string

Name of SESAM message catalog file. In most cases, this directive is not necessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

The message catalog must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.


Configuration notes

There is no standalone support for the PHP SESAM interface, it works only as an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using Apache directives.

Tabella 1. SESAM Configuration directives

DirectiveMeaning
php3_sesam_oml Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions.

Example:

php3_sesam_oml $.SYSLNK.SESAM-SQL.030

php3_sesam_configfile Name of SESAM application configuration file. Required for using SESAM functions.

Example:

php3_sesam_configfile $SESAM.SESAM.CONF.AW

It will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

php3_sesam_messagecatalog Name of SESAM message catalog file. In most cases, this directive is not necessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

Example:

php3_sesam_messagecatalog $.SYSMES.SESAM-SQL.030

In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:

  • starting the SESAM database handler (DBH), and

  • connecting the databases with the SESAM database handler

To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.

In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.

The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.

Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).

Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.


Runtime considerations

Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.

When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.

Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.


Cursor Types

The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:

Tabella 2. Scrolled Cursor Post-Processing

Scroll TypeAction
SESAM_SEEK_NEXTnone
SESAM_SEEK_PRIORnone
SESAM_SEEK_FIRST set scroll type to SESAM_SEEK_NEXT
SESAM_SEEK_LAST set scroll type to SESAM_SEEK_PRIOR
SESAM_SEEK_ABSOLUTEAuto-Increment internal offset value
SESAM_SEEK_RELATIVEnone. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards)


Porting note

Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective PHP sesam functions include a note that the index is zero based.


Security concerns

When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to PHP scripts which must administer the database by using password control and/or SSL security.


Migration from other SQL databases

No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:

  • Vendor specific data types

    Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).

  • Keywords as SQL identifiers

    In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).

  • Display length in data types

    SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).

  • SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes

    Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.

  • int ... DEFAULT '0000'

    Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );

  • $count = xxxx_num_rows();

    Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.

  • DROP TABLE thename;

    In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.


Notes on the use of various SQL types

SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.

At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:

Tabella 3. SQL to PHP Type Conversions

SQL TypePHP Type
SMALLINT, INTEGERinteger
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLEfloat
DATE, TIME, TIMESTAMPstring
VARCHAR, CHARACTERstring
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so you will have to check for the existence of the individual fields yourself (use isset() or empty() to test for empty fields). That allows more user control over the appearance of empty fields (than in the case of an empty string as the representation of an empty field).


Support of SESAM's "multiple fields" feature

The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:

Esempio 1. Creating a "multiple field" column

CREATE TABLE multi_field_test (
    pkey CHAR(20) PRIMARY KEY,
    multi(3) CHAR(12)
)
and can be filled in using:

Esempio 2. Filling a "multiple field" column

INSERT INTO multi_field_test (pkey, multi(2..3) )
    VALUES ('Second', <'first_val', 'second_val'>)
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).

When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.


Vedere anche:

For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.

Sommario
sesam_affected_rows --  Get number of rows affected by an immediate query
sesam_commit --  Commit pending updates to the SESAM database
sesam_connect -- Open SESAM database connection
sesam_diagnostic --  Return status information for last SESAM call
sesam_disconnect -- Detach from SESAM connection
sesam_errormsg -- Returns error message of last SESAM call
sesam_execimm -- Execute an "immediate" SQL-statement
sesam_fetch_array -- Fetch one row as an associative array
sesam_fetch_result -- Return all or part of a query result
sesam_fetch_row -- Fetch one row as an array
sesam_field_array --  Return meta information about individual columns in a result
sesam_field_name --  Return one column name of the result set
sesam_free_result -- Releases resources for the query
sesam_num_fields --  Return the number of fields/columns in a result set
sesam_query -- Perform a SESAM SQL query and prepare the result
sesam_rollback --  Discard any pending updates to the SESAM database
sesam_seek_row --  Set scrollable cursor mode for subsequent fetches
sesam_settransaction -- Set SESAM transaction parameters

sesam_affected_rows

(PHP 3 CVS only)

sesam_affected_rows --  Get number of rows affected by an immediate query

Description

int sesam_affected_rows ( string result_id )

result_id is a valid result id returned by sesam_query().

Returns the number of rows affected by a query associated with result_id.

The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries. The number returned is the number of affected rows.

Esempio 1. sesam_affected_rows() example

<?php
$result = sesam_execimm("DELETE FROM PHONE WHERE LASTNAME = '" . strtoupper($name) . "'");
if (!$result) {
    /* ... error ... */
}
echo sesam_affected_rows($result).
    " entries with last name " . $name . " deleted.\n";
?>

See also sesam_query() and sesam_execimm().

sesam_commit

(PHP 3 CVS only)

sesam_commit --  Commit pending updates to the SESAM database

Description

bool sesam_commit ( void )

Returns: TRUE on success, FALSE on errors

sesam_commit() commits any pending updates to the database.

Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.

See also: sesam_rollback().

Esempio 1. Committing an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (!sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)"))
        die("insert failed");
    if (!sesam_commit())
        die("commit failed");
}
?>

sesam_connect

(PHP 3 CVS only)

sesam_connect -- Open SESAM database connection

Description

bool sesam_connect ( string catalog, string schema, string user )

Returns TRUE if a connection to the SESAM database was made, or FALSE on error.

sesam_connect() establishes a connection to an SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.

When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)

The "schema" references the desired database schema (see SESAM handbook).

The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.

See also sesam_disconnect().

Esempio 1. Connect to a SESAM database

<?php
if (!sesam_connect ("mycatalog", "myschema", "otto")) {
    die("Unable to connect to SESAM");
}
?>

sesam_diagnostic

(PHP 3 CVS only)

sesam_diagnostic --  Return status information for last SESAM call

Description

array sesam_diagnostic ( void )

Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:

Tabella 1. Status information returned by sesam_diagnostic()

ElementContents
$array["sqlstate"] 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE)
$array["rowcount"] number of affected rows in last update/insert/delete (set after "immediate" statements only)
$array["errmsg"] "human readable" error message string (set after errors only)
$array["errcol"] error column number of previous error (0-based; or -1 if undefined. Set after errors only)
$array["errlin"] error line number of previous error (0-based; or -1 if undefined. Set after errors only)

In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:

Esempio 1. Displaying SESAM error messages with error position

<?php
// Function which prints a formatted error message,
// displaying a pointer to the syntax error in the
// SQL statement
function PrintReturncode($exec_str) 
{
    $err = Sesam_Diagnostic();
    $colspan=4; // 4 cols for: sqlstate, errlin, errcol, rowcount
    if ($err["errlin"] == -1)
        --$colspan;
    if ($err["errcol"] == -1)
        --$colspan;
    if ($err["rowcount"] == 0)
        --$colspan;
    echo "<table border=\"1\">\n";
    echo "<tr><th colspan=\"" . $colspan . "\"><span class=\"spanred\">ERROR:</span> ".
         htmlspecialchars($err["errmsg"]) . "</th></tr>\n";
    if ($err["errcol"] >= 0) {
        echo "<tr><td colspan=\"" . $colspan . "\"><pre>\n";
        $errstmt = $exec_str . "\n";
        for ($lin=0; $errstmt != ""; ++$lin) {
            if ($lin != $err["errlin"]) { // $lin is less or greater than errlin
                if (!($i = strchr($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                if ($line != "\n")
                    echo htmlspecialchars($line);
            } else {
                if (! ($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen ($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                for ($col=0; $col < $err["errcol"]; ++$col) {
                    echo (substr($line, $col, 1) == "\t") ? "\t" : ".";
                }
                echo "<span class=\"spanred\">\\</span>\n";
                echo "<span class=\"normal\">" . htmlspecialchars($line) . "</span>";
                for ($col=0; $col < $err["errcol"]; ++$col) {
                    echo (substr ($line, $col, 1) == "\t") ? "\t" : ".";
                }
                echo "<span class=\"spanred\">/</span>\n";
            }
        }
        echo "</pre></td></tr>\n";
    }
    echo "<tr>\n";
    echo " <td>sqlstate=" . $err["sqlstate"] . "</td>\n";
    if ($err["errlin"] != -1)
        echo " <td>errlin=" . $err["errlin"] . "</td>\n";
    if ($err["errcol"] != -1)
        echo " <td>errcol=" . $err["errcol"] . "</td>\n";
    if ($err["rowcount"] != 0)
         echo " <td>rowcount=" . $err["rowcount"] . "</td>\n";
    echo "</tr>\n";
    echo "</table>\n";
}

if (!sesam_connect ("mycatalog", "phoneno", "otto"))
  die ("cannot connect");

$stmt = "SELECT * FROM phone\n" .
        " WHERE@ LASTNAME='KRAEMER'\n" .
        " ORDER BY FIRSTNAME";
if (!($result = sesam_query ($stmt)))
    PrintReturncode ($stmt);
?>

See also: sesam_errormsg() for simple access to the error string only

sesam_disconnect

(PHP 3 CVS only)

sesam_disconnect -- Detach from SESAM connection

Description

bool sesam_disconnect ( void )

Returns: always TRUE.

sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).

Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.

sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.

Esempio 1. Closing a SESAM connection

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    /* ... some queries and stuff ... */
    sesam_disconnect(); 
}
?>

See also sesam_connect().

sesam_errormsg

(PHP 3 CVS only)

sesam_errormsg -- Returns error message of last SESAM call

Description

string sesam_errormsg ( void )

Returns the SESAM error message associated with the most recent SESAM error.

Esempio 1. sesam_errormsg() example

<?php
if (!sesam_execimm($stmt)) {
  echo sesam_errormsg() . "<br />\n";
}
?>

See also sesam_diagnostic() for the full set of SESAM SQL status information.

sesam_execimm

(PHP 3 CVS only)

sesam_execimm -- Execute an "immediate" SQL-statement

Description

string sesam_execimm ( string query )

Returns: A SESAM "result identifier" on success, or FALSE on error.

sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the sesam_affected_rows() function.

Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".

The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.

<?php
$stmt = "INSERT INTO mytable VALUES ('one', 'two')";
$result = sesam_execimm($stmt);
$err = sesam_diagnostic();
echo "sqlstate = " . $err["sqlstate"] . "\n".
       "Affected rows = " . $err["rowcount"] . " == " .
       sesam_affected_rows($result) . "\n";
?>

See also sesam_query() and sesam_affected_rows().

sesam_fetch_array

(PHP 3 CVS only)

sesam_fetch_array -- Fetch one row as an associative array

Description

array sesam_fetch_array ( string result_id [, int whence [, int offset]] )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.

result_id is a valid result id returned by sesam_query() (select type queries only!).

For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row() function for details.

sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.

Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.

SELECT TBL1.COL AS FOO, TBL2.COL AS BAR FROM TBL1, TBL2

A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:

CREATE TABLE ... ( ... MULTI(3) INT )

the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.

Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Esempio 1. SESAM fetch array

<?php
$result = sesam_query("SELECT * FROM phone\n" .
                       "  WHERE LASTNAME='" . strtoupper($name) . "'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    /* ... error ... */
}
// print the table:
echo "<table border=\"1\">\n";
while (($row = sesam_fetch_array($result)) && count($row) > 0) {
    echo "<tr>\n";
    echo "<td>" . htmlspecialchars($row["firstname"]) . "</td>\n";
    echo "<td>" . htmlspecialchars($row["lastname"]) . "</td>\n";
    echo "<td>" . htmlspecialchars($row["phoneno"]) . "</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
sesam_free_result($result);
?>

See also: sesam_fetch_row() which returns an indexed array.

sesam_fetch_result

(PHP 3 CVS only)

sesam_fetch_result -- Return all or part of a query result

Description

mixed sesam_fetch_result ( string result_id [, int max_rows] )

Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.

Tabella 1. Mixed result set returned by sesam_fetch_result()

Array ElementContents
int $arr["count"] number of columns in result set (or zero if this was an "immediate" query)
int $arr["rows"] number of rows in result set (between zero and max_rows)
bool $arr["truncated"] TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries.
mixed $arr[col][row] result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.
Note that the amount of memory used up by a large query may be gigantic. Use the max_rows parameter to limit the maximum number of rows returned, unless you are absolutely sure that your result will not use up all available memory.

See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description of the sesam_query() function for a complete example using sesam_fetch_result().

sesam_fetch_row

(PHP 3 CVS only)

sesam_fetch_row -- Fetch one row as an array

Description

array sesam_fetch_row ( string result_id [, int whence [, int offset]] )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().

result_id is a valid result id returned by sesam_query() (select type queries only!).

whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:

Tabella 1. Valid values for "whence" parameter

ValueConstantMeaning
0SESAM_SEEK_NEXT read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT)
1SESAM_SEEK_PRIOR read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR)
2SESAM_SEEK_FIRST rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3SESAM_SEEK_LAST seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4SESAM_SEEK_ABSOLUTE seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented)
5SESAM_SEEK_RELATIVE seek relative to current scroll position, where offset can be a positive or negative offset value.
This parameter is only valid for "scrollable" cursors.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.

sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.

Subsequent calls to sesam_fetch_row() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Esempio 1. SESAM fetch rows

<?php
$result = sesam_query("SELECT * FROM phone\n" .
                       "  WHERE LASTNAME='" . strtoupper($name) . "'\n" .
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    /* ... error ... */
}
// print the table in backward order
echo "<table border=\"1\">\n";
$row = sesam_fetch_row($result, SESAM_SEEK_LAST);
while (is_array($row)) {
    echo "<tr>\n";
    for ($col = 0; $col < $row["count"]; ++$col) {
        echo "<td>" . htmlspecialchars($row[$col]) . "</td>\n";
    }
    echo "</tr>\n";
    // use implied SESAM_SEEK_PRIOR
    $row = sesam_fetch_row($result);
}
echo "</table>\n";
sesam_free_result($result);
?>

See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.

sesam_field_array

(PHP 3 CVS only)

sesam_field_array --  Return meta information about individual columns in a result

Description

array sesam_field_array ( string result_id )

result_id is a valid result id returned by sesam_query().

Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.

Tabella 1. Mixed result set returned by sesam_field_array()

Array ElementContents
int $arr["count"] Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns.
string $arr[col]["name"] column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name.
string $arr[col]["count"] The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute.
string $arr[col]["type"] PHP variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same PHP type.
string $arr[col]["sqltype"] SQL variable type of the column data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • "CHARACTER"

  • "VARCHAR"

  • "NUMERIC"

  • "DECIMAL"

  • "INTEGER"

  • "SMALLINT"

  • "FLOAT"

  • "REAL"

  • "DOUBLE"

  • "DATE"

  • "TIME"

  • "TIMESTAMP"

describing the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same SQL type.
string $arr[col]["length"] The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute.
string $arr[col]["precision"] The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute.
string $arr[col]["scale"] The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute.

See also sesam_query() for an example of the sesam_field_array() use.

sesam_field_name

(PHP 3 CVS only)

sesam_field_name --  Return one column name of the result set

Description

int sesam_field_name ( string result_id, int index )

Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.

For "immediate" queries, or for dynamic columns, an empty string is returned.

Nota: The column index is zero-based, not one-based as in SESAM.

See also: sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".

sesam_free_result

(PHP 3 CVS only)

sesam_free_result -- Releases resources for the query

Description

int sesam_free_result ( string result_id )

Releases resources for the query associated with result_id. Returns FALSE on error.

sesam_num_fields

(PHP 3 CVS only)

sesam_num_fields --  Return the number of fields/columns in a result set

Description

int sesam_num_fields ( string result_id )

After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result. Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.

For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.

See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.

sesam_query

(PHP 3 CVS only)

sesam_query -- Perform a SESAM SQL query and prepare the result

Description

string sesam_query ( string query [, bool scrollable] )

Returns: A SESAM "result identifier" on success, or FALSE on error.

A "result_id" resource is used by other functions to retrieve the query results.

sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().

For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.

See also: sesam_fetch_row() and sesam_fetch_result().

Esempio 1. Show all rows of the "phone" table as a HTML table

<?php
if (!sesam_connect("phonedb", "demo", "otto"))
    die("cannot connect");
$result = sesam_query("select * from phone");
if (!$result) {
    $err = sesam_diagnostic();
    die ($err["errmsg"]);
}
echo "<table border>\n";
// Add title header with column names above the result:
if ($cols = sesam_field_array($result)) {
    echo "<tr><th colspan=" . $cols["count"] . ">Result:</th></tr>\n";
    echo "<tr>\n";
    for ($col = 0; $col < $cols["count"]; ++$col) {
        $colattr = $cols[$col];
        /* Span the table head over SESAM's "Multiple Fields": */
        if ($colattr["count"] > 1) {
            echo "<th colspan=\"" . $colattr["count"] . "\">" . $colattr["name"] .
                "(1.." . $colattr["count"] . ")</th>\n";
            $col += $colattr["count"] - 1;
        } else
            echo "<th>" . $colattr["name"] . "</th>\n";
    }
    echo "</tr>\n";
}

do {
    // Fetch the result in chunks of 100 rows max.
    $ok = sesam_fetch_result($result, 100);
    for ($row=0; $row < $ok["rows"]; ++$row) {
        echo " <tr>\n";
        for ($col = 0; $col < $ok["cols"]; ++$col) {
            if (isset($ok[$col][$row])) {
                echo "<td>" . $ok[$col][$row] . "</td>\n";
            } else {
                echo "<td>-empty-</td>\n";
            }
        }
        echo "</tr>\n";
    }
} while ($ok["truncated"]); // while there may be more data

echo "</table>\n";
// free result id
sesam_free_result($result);
?>

sesam_rollback

(PHP 3 CVS only)

sesam_rollback --  Discard any pending updates to the SESAM database

Description

bool sesam_rollback ( void )

Returns: TRUE on success, FALSE on errors

sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.

At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.

See also: sesam_commit().

Esempio 1. Discarding an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)")
        && sesam_execimm ("INSERT INTO othertable VALUES (*, 'Another Test', 1)")) {
        sesam_commit();
    } else {
        sesam_rollback();
    }
}
?>

sesam_seek_row

(PHP 3 CVS only)

sesam_seek_row --  Set scrollable cursor mode for subsequent fetches

Description

bool sesam_seek_row ( string result_id, int whence [, int offset] )

result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).

whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:

Tabella 1. Valid values for "whence" parameter

ValueConstantMeaning
0SESAM_SEEK_NEXTread sequentially
1SESAM_SEEK_PRIORread sequentially backwards
2SESAM_SEEK_FIRST fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3SESAM_SEEK_LAST fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4SESAM_SEEK_ABSOLUTE fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented)
5SESAM_SEEK_RELATIVE fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches).

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.

sesam_settransaction

(PHP 3 CVS only)

sesam_settransaction -- Set SESAM transaction parameters

Description

bool sesam_settransaction ( int isolation_level, int read_only )

Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE otherwise.

sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only.

sesam_settransaction() can only be called before starting a transaction, not after the transaction has been started already.

To simplify the use in PHP scripts, the following constants have been predefined in PHP (see SESAM handbook for detailed explanation of the semantics):

Tabella 1. Valid values for "Isolation_Level" parameter

ValueConstantMeaning
1SESAM_TXISOL_READ_UNCOMMITTEDRead Uncommitted
2SESAM_TXISOL_READ_COMMITTEDRead Committed
3SESAM_TXISOL_REPEATABLE_READRepeatable Read
4SESAM_TXISOL_SERIALIZABLESerializable

Tabella 2. Valid values for "Read_Only" parameter

ValueConstantMeaning
0SESAM_TXREAD_READWRITERead/Write
1SESAM_TXREAD_READONLYRead-Only

The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.

Esempio 1. Setting SESAM transaction parameters

<?php
sesam_settransaction (SESAM_TXISOL_REPEATABLE_READ,
                     SESAM_TXREAD_READONLY);
?>

CXXXIII. PostgreSQL Session Save Handler

Introduzione

Nota: Questo modulo non è disponibile su piattaforme Windows.

This module provides an additional session save handler for the session module using PostgreSQLPostgreSQL as a storage system. A user session save handler may be used ((session_set_save_handler(), but this module is written in C. Therefore, this module could be twice as fast, compared to a session save handler written in PHP.

Session PgSQL is designed to scale any size of web sites and offers some advanced features:

session tables are created automatically
automatic session table vacuum
better garbage collection
multiple PostgreSQL servers support
automatic database server failover (switching)
automatic database server load balancing if there are multiple PostgreSQL servers.
short circuit UPDATE


Requisiti

You need at least PHP >= 4.3.0, and PostgreSQL >=7.2.0 as database server. libpq that comes with PostgreSQL 7.2.0 or later (and header files to build) and libmm (and header files).


Installazione

Short installation note:

  • Untar the tar.gz archive into php4/ext (Latest official releases can be found at SourceForge PHP Form Extension Project)

  • If the new directory is now called something like session_pgsql. You should name it to session_pgsql (except you only want to build it as self-contained php-module).

  • Run ./buildconf in php4

  • Run configure --with-session-pgsql (and your other options)

  • make; make install


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

PostgreSQL session save handler is still under development. Refer to the README file in the source distribution for configuration details.


Table definitions

Session table definition
CREATE TABLE php_session (
  sess_id            text,
  sess_name          text,
  sess_data          text,
  sess_created       integer,
  sess_modified      integer,
  sess_expire        integer,
  sess_addr_created  text,
  sess_addr_modified text,
  sess_counter       integer,
  sess_error         integer,
  sess_warning       integer,
  sess_notice        integer,
  sess_err_message   text,
  sess_custom        text
);

CREATE INDEX php_session_idx ON php_session USING BTREE (sess_id);

Avvertimento

If you use HASH for INDEX, you'll have a deadlock problem when the server load is very high. Even if it's unlikely to have a deadlock under normal operation, it can occur. Do not use HASH for INDEX.

You may change the session table as long as all fields are defined.

Application variables table definition
CREATE TABLE php_app_vars (
  app_modified       integer,
  app_name           text,
  app_vars           text
);


Contact Information

I have at the moment not very much time to further develop this extension. I will implement more and more features in the near future.

If you have comments, bug fixes, enhancements or want to help developing this, you can drop me a mail at yohgaki@php.net. Any help is very welcome.

Sommario
session_pgsql_add_error -- Increments error counts and sets last error message
session_pgsql_get_error -- Returns number of errors and last error message
session_pgsql_get_field -- Get custom field value
session_pgsql_reset -- Reset connection to session database servers
session_pgsql_set_field -- Set custom field value
session_pgsql_status -- Get current save handler status

session_pgsql_add_error

(PECL)

session_pgsql_add_error -- Increments error counts and sets last error message

Descrizione

bool session_pgsql_add_error ( int error_level [, string error_message] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

error_level

error_message

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

session_pgsql_get_error

(PECL)

session_pgsql_get_error -- Returns number of errors and last error message

Descrizione

array session_pgsql_get_error ( [bool with_error_message] )

Get the number of errors and optional the error messages.

Elenco dei parametri

with_error_message

Set to TRUE the literal error message for each error is also returned.

Valori restituiti

The number of errors are returned as array.

session_pgsql_get_field

(PECL)

session_pgsql_get_field -- Get custom field value

Descrizione

string session_pgsql_get_field ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

session_pgsql_reset

(PECL)

session_pgsql_reset -- Reset connection to session database servers

Descrizione

bool session_pgsql_reset ( void )

Reset the connection to the session database servers.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

session_pgsql_set_field

(PECL)

session_pgsql_set_field -- Set custom field value

Descrizione

bool session_pgsql_set_field ( string value )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

value

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

session_pgsql_status

(PECL)

session_pgsql_status -- Get current save handler status

Descrizione

array session_pgsql_status ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CXXXIV. Funzioni di gestione della sessione

Il supporto delle sessioni in PHP consiste nel mantenere certi dati attraverso accessi successivi.Questo vi dà la capacità di costruire applicazioni più consone alle vostre esigenze e di accrescere le qualità del vostro sito web.

Se avete dimestichezza con la gestione delle sessioni di PHPLIB, noterete che alcuni concetti sono simili al supporto dele sessioni in PHP.

Al visitatore che accede al vostro sito web viene assegnato un id unico, il cosidetto id di sessione. Questo viene registrato in un cookie sul lato utente o è propagato tramite l'URL.

Il supporto delle sessioni vi permette di registrare numeri arbitrari di variabili che vengono preservate secondo richiesta.Quando un visitatore accede al vostro sito, PHP controllerà automaticamente (se session.auto_start è settato a 1) o su vostra richiesta (esplicitamente tramite session_start() o implicitamente tramite session_register()) se uno specifico id di sessione sia stato inviato con la richiesta. In questo caso , il precedente ambiente salvato viene ricreato.

Tutte le variabili registrate vengono serializzate dopo che la richiesta è finita. Le variabili registrate che non sono definite vengono marcate come indefinite. All'accesso successivo, queste non vengono definite dal modulo di sessione fino a quando l'utente non le definisce più tardi.

La configurazione di track_vars e register_globals influenza come le variabili di sessione vengono memorizzate una e più volte.

Nota: In PHP 4.0.3, track_vars è sempre attiva.

Nota: In PHP 4.1.0, $_SESSION è disponibile come variabile globale proprio come $_POST, $_GET, $_REQUEST e così via. $HTTP_SESSION_VARS non è sempre globale, $_SESSION lo è sempre. Per questo motivo, global non dovrebbe essere usato per $_SESSION.

Se track_vars è attiva e register_globals non è attiva, solo i membri dell'array associativo globale $HTTP_SESSION_VARS possono essere registrati come variabili di sessione. Le variabili di sessione ripristinate saranno disponibili nell'array $HTTP_SESSION_VARS.

Esempio 1. Registrare una variabile con track_vars attiva

<?php
if (isset($HTTP_SESSION_VARS['count'])) {
   $HTTP_SESSION_VARS['count']++;
}
else {
   $HTTP_SESSION_VARS['count'] = 0;
}
?>

L'uso di $_SESSION (o $HTTP_SESSION_VARS con PHP 4.0.6 o precedente) è raccomandato per sicurezza e leegibilità del codice.Con $_SESSION o $HTTP_SESSION_VARS, non c'è bisogno di usare le funzioni session_register()/session_unregister()/session_is_registered(). Gli utenti possono accedere alla variabile di sessione come a una variabile normale.

Esempio 2. Registrare una variabile con $_SESSION.

<?php
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
} else {
    $_SESSION['count']++;
}
?>

Esempio 3. Resettare una variabile con $_SESSION.

<?php
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);

?>

Se register_globals è attiva, allora tutte le variabili globali possono essere registrate come variabili di sessione e le variabili di sessione saranno ripristinate in corrispondenza delle variabili globali. Dal momento che PHP ha bisogno di sapere quali variabili globali sono registrate come variabili di sessione , gli utenti devono registrare le variabili con la funzione session_register() mentre $HTTP_SESSION_VARS/$_SESSION non ha bisogno di usare session_register().

Attenzione

Se state usando $HTTP_SESSION_VARS/$_SESSION e register_globals non è attiva, non usate session_register(), session_is_registered() e session_unregister().

Se attivate register_globals, session_unregister() dovrebbe essere usata dal momento in cui le variabili di sessione vengono registrate come variabili globali quando i dati di sessione vengono deserializzati. Disattivare register_globals è raccomandato sia per motivi di sicurezza che di prestazione.

Esempio 4. Registrare una variabile con register_globals attiva

<?php
if (!session_is_registered('count')) {
    session_register("count");
    $count = 0;
}
else {
    $count++;
}
?>

Se entrambe track_vars e register_globals sono attivate, allora le variabili globali e le entrate di $HTTP_SESSION_VARS/$_SESSION riporteranno lo stesso valore per variabili già registrate.

Se l'utente usa session_register() pre registrare una variabile di sessione, $HTTP_SESSION_VARS/$_SESSION non avranno questa variabile nell'array fino a che non sarà caricata dall'archivio di sessione.(i.e. fino alla prossima richiesta)

Ci sono due metodi per propagare l'id di sessione:

  • I Cookies

  • Un parametro dell'URL

Il modulo di sessione supporta entrambi i metodi. I cookies sono ottimi, ma dal momento che possono non essere a disposizione (i clients non sono costretti ad accettarli ), non possiamo dipendere da questi. Il secondo metodo incorpora l'id di sessione direttamente negli URL.

PHP ha la capacità di farlo in modo trasparente quando compilato con --enable-trans-sid. Se attivate questa opzione, gli URL relativi saranno modificati per contenere l'id di sessione automaticamente. In alternativa, potete usare la costante Alternatively, you can use the constant SID che è definita, se il client non ha mandato il cookie appropriato. SID può avere la forma di session_name=session_id o può essere una stringa vuota.

L'esempio seguente dimostra come registrare una variabile e come collegare una pagina all'altra correttamente usando SID.

Esempio 5. Contare il numero di accessi di un singolo utente

<?php
if (!session_is_registered('count')) {
    session_register('count');
    $count = 1;
}
else {
    $count++;
}
?>

Salve visitatore , hai visitato questa pagina <?php echo $count; ?> times.<p>;

<?php
# il <?php echo SID?> (<?=SID?> può essere usato se short tag è attivo) 
# è necessario per preservare l'id di sessione
# nel caso incui l'utente abbia disattivato i cookies
?>

Per continuare, <A HREF="nextpage.php?<?php echo SID?>">clicca qui</A>

Il <?=SID?> non è necessario, se --enable-trans-sid è stato usato per compilare PHP.

Nota: Gli URL non relativi si presume che puntino a siti esterni e quindi non hanno il SID , perchè sarebbe rischioso per la sicurezza propagare il SID a un altro server.

Per implementare l'archiviazione in database , o qualsiasi altro metodo di archiviazione, avete bisogno di usare session_set_save_handler() per creare un set di funzioni di archiviazione a livello utente.

Il sistema di gestione delle sessioni supporta un numero di opzioni di configurazione che potete posizionare nel vostro file php.ini. Ne daremo una breve spiegazione.

  • session.save_handler definisce il nome dell'handler che è usato per archiviare e rilasciare i dati associati a una sessione. Di default è files.

  • session.save_path definisce l'argomento che è passato all'handler di sessione. Se scegliete handler files di default , questo è il percorso dove i files vengono creati. Di default è /tmp. Se la profondità del percorso session.save_path è più di 2, l'accumulo (gc) non sarà effettuato.

    Avvertimento

    Se lasciate questo settato a directory leggibile da tutti , come If you leave this set to a world-readable directory, such as /tmp (il default), altri utenti sul potrebbero essere in grado di dirottare le sessioni prendendo la lista dei files in quella directory.

  • session.name specifica il nome della sessione che è usata come nome del cookie. Dovrebbe contenere solo caratteri alfanumerici. Di default è PHPSESSID.

  • session.auto_start specifica se il modulo di sessione inizia una sessione automaticamente su richiesta iniziale. Di default è 0 (disattivata).

  • session.cookie_lifetime specifica il tempo di vita insecondi del cookie che viene mandato al browser. Il valore 0 significa "fino a che il browser viene chiuso". Di default è 0.

  • session.serialize_handler definisce il nome dell'handler che è usato per serializzare/deserializzare i dati. Al momento, un formato interno di PHP(nome php) e WDDX è supportato (nome wddx). WDDX è solo disponibile, se PHP è compilato con WDDX support. Il defailt è php.

  • session.gc_probability specifica la probabilità , in percentuale ,che la routine gc (garbage collection) sia cominciata ad ogni richiesta in percentuale. Di default è 1.

  • session.gc_maxlifetime specifica il numero di secondi dopo i quali i dati saranno considerati 'spazzatura' e cancellati.

  • session.referer_check contiene la sottostringa con cui volete controllare ogni HTTP referer. Se il referer è stato mandato dal client e la sottostringa non è stata trovata, l'id incorporato nella sessione verrà marcato come non valido. Il default è una stringa vuota.

  • session.entropy_file dà un percorso a una risorsa esterna (file) che sarà usata come una addizionale sorgente entropica nella crazione dell'id di sessione. Esempi sono /dev/random o /dev/urandom che sono disponibili sulla maggior parte dei sistemi Unix.

  • session.entropy_length specifica il numero di bytes che saranno letti dal file specificato sopra. Di default è 0 (disattivato).

  • session.use_cookies specifica se il modulo userà i cookies per archiviare l'id di sessione sul lato client. Di default è 1 (attivo).

  • session.cookie_path specifica il percorso da stabilire in session_cookie. Di default è /.

  • session.cookie_domain specifica il dominio settato in session_cookie. Di default è niente.

  • session.cache_limiter specifica il metodo di controllo della cache da usare per le pagine di sessione (none/nocache/private/private_no_expire/public). Di default è nocache.

  • session.cache_expire specifica il tempo-di-vita , in minuti , delle pagine nella cache, questo non ha effetto sul limitatore nocache. Di default è 180.

  • session.use_trans_sid specifica se il supporto sid trasparente è attivato o no se attivato compilandolo con --enable-trans-sid. Di default è 1 (attivo).

  • url_rewriter.tags specifica quali html tags sono riscritti per includere l'id di sessione se il supporto sid trasparente è attivato. Di default è a=href,area=href,frame=src,input=src,form=fakeentry

Nota: L'handling di sessione è stato aggiunto in PHP 4.0.

Sommario
session_cache_expire -- Ritorna il valore corrente di scadenza della cache
session_cache_limiter -- Assume o imposta il limitatore di cache corrente
session_commit -- Alias di session_write_close()
session_decode -- Decodifica i dati di sessione da una stringa
session_destroy -- Distrugge tutti i dati registrati in una sessione
session_encode --  Codifica i dati della sessione corrente in una stringa
session_get_cookie_params --  Restituisce i parametri del cookie di sessione
session_id -- Assume o imposta l'id di sessione corrente
session_is_registered --  Scopre se una variabile è registrata nella sessione
session_module_name -- Assume o imposta il corrente modulo di sessione
session_name -- Dà e/o stabilisce il nome della sessione corrente
session_regenerate_id --  Update the current session id with a newly generated one
session_register --  Registra una o più variabili con la sessione corrente
session_save_path -- Assume o stabilisce il percorso di salvataggio sessione corrente
session_set_cookie_params --  Imposta i parametri del cookie di sessione
session_set_save_handler --  Imposta le funzioni di archiviazione sessioni a livello utente
session_start -- Inizializza i dati di sessione
session_unregister --  Deregistra una variabile dalla sessione corrente
session_unset --  Libera tutte le variabili di sessione
session_write_close -- Scrive i dati di sessione e termina la sessione

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5)

session_cache_expire -- Ritorna il valore corrente di scadenza della cache

Descrizione

int session_cache_expire ( [int nuova_scadenza_cache] )

session_cache_expire() ritorna il valore corrente di session.cache_expire. Il valore ritornato deve essere espressio in minuti, di default 180. Se si assegna nuova_scadenza_cache , il valore corrente di scadenza della cache viene sostituito con nuova_scadenza_cache.

La scadenza della cache viene reimpostata al valore predefinito di 180 memorizzato in session.cache_limiter ad ogni richiesta di pagina. Quindi, è necessario chiamare session_cache_expire() in ogni pagina (e prima di invocare session_start()).

Esempio 1. session_cache_expire() esempio

<?php

/* assegna il limite della cache su 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* imposta la scadenza della cache su 30 minuti */
session_cache_expire(30);
$cache_expire = session_cache_expire();

/* avvia la sessione */

session_start();

echo "Il limite della cache ora è impostato su $cache_limiter<br />";
echo "Le pagine di sessione nella cache scadranno dopo $cache_expire minutes";
?>

Nota: Impostazione nuova_scadenza_cache è utile soltanto, se session.cache_limiter è impostato su un valore diverso da nocache.

Vedere inoltre le impostazioni di configurazione session.cache_expire, session.cache_limiter e session_cache_limiter().

session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5)

session_cache_limiter -- Assume o imposta il limitatore di cache corrente

Descrizione

string session_cache_limiter ( [string cache_limiter] )

session_cache_limiter() restituisce il nome del limitatore di cache corrente. Se cache_limiter è specificato, il nome del limitatore di cache corrente viene cambiato nel nuovo valore.

Il limitatore di cache controlla quali header HTTP che influenzano la cache vengono mandati al client. Questi header determinano i modi in cui il contenuto della pagina può essere mandato in cache, sia da parte del client che da parte di eventuali proxy. Impostando il limitatore di cache a nocache, per esempio, non permetterebbe nessun caching lato client. Un valore di public, invece, permetterebbe il caching. Può anche essere impostato a private, che è leggermente più restrittivo di public.

Nella modalità private, l'header Expire mandato al client, potrebbe causare confusione per alcuni browser incluso Mozilla. Si può evitare questo problema con la modalità  private_no_expire. In questo modo l'header Expire non viene mai spedito al client.

Nota: private_no_expire è stato aggiunto in PHP 4.2.0dev.

Il limitatore di cache è resettato al valore di default archiviato in session.cache_limiter alla richiesta iniziale. Per questo motivo, avete bisogno di chiamare session_cache_limiter() per ogni richiesta (e prima che session_start() sia chiamata).

Esempio 1. session_cache_limiter() esempi

<?php

# set the cache limiter to 'private'

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "Il limitatore di cache è adesso impostato a $cache_limiter<p>";
?>

session_commit

(PHP 4 >= 4.3.11, PHP 5)

session_commit -- Alias di session_write_close()

Descrizione

This function is an alias of: session_write_close().

session_decode

(PHP 4, PHP 5)

session_decode -- Decodifica i dati di sessione da una stringa

Descrizione

bool session_decode ( string data )

session_decode() decodifica i dati di sessione in data, impostando le varibili archiviate nella sessione.

Vedere inoltre session_encode().

session_destroy

(PHP 4, PHP 5)

session_destroy -- Distrugge tutti i dati registrati in una sessione

Descrizione

bool session_destroy ( void )

session_destroy() distrugge tutti i dati associati alla sessione corrente. Non desetta nessuna delle variabili globali associate alla sessione o desetta il cookie di sessione.

Questa funzione ritorna TRUE in caso di successo e FALSE in caso di fallimento nel distruggere i dati di sessione.

Esempio 1. Distruggere una sessione

<?php

// Inizializza la sessione.
// Se state usando session_name("qualcosa"), non dimenticatevelo adesso!
session_start();
// Desetta tutte le variabili di sessione.
session_unset();
// Infine , distrugge la sessione.
session_destroy();

?>

Esempio 2. Distruggere una sessione con $_SESSION

<?php

// Inizializza la sessione.
// Se state usando session_name("qualcosa"), non dimenticatevelo adesso!
session_start();
// Desetta tutte le variabili di sessione.
$_SESSION = array();
// Infine distrugge la sessione.
session_destroy();

?>

session_encode

(PHP 4, PHP 5)

session_encode --  Codifica i dati della sessione corrente in una stringa

Descrizione

string session_encode ( void )

session_encode() restituisce una stringa con i contenuti della sessione corrente codificati.

session_get_cookie_params

(PHP 4, PHP 5)

session_get_cookie_params --  Restituisce i parametri del cookie di sessione

Descrizione

array session_get_cookie_params ( void )

La funzione session_get_cookie_params() restituisce un con le informazioni sul cookie di sessione corrente, l'array contiene i seguenti elementi:

  • "lifetime" - La durata del cookie.

  • "path" - Il percorso dove l'informazione è archiviata.

  • "domain" - Il dominio di validità del cookie.

  • "secure" - Il cookie dovrebbe essere spedito solo attraverso connessioni sicure. (Questo elemento è stato aggiunto in PHP 4.0.4.)

session_id

(PHP 4, PHP 5)

session_id -- Assume o imposta l'id di sessione corrente

Descrizione

string session_id ( [string id] )

session_id() restituisce l'id di sessione per la sessione corrente. Se id è specificato, sostituirà l'id di sessione corrente.

La costante SID può essere usata anche per fornire nome e id correnti di sessione come una stringa fatta in modo che si possa aggiungere agli Url.

session_is_registered

(PHP 4, PHP 5)

session_is_registered --  Scopre se una variabile è registrata nella sessione

Descrizione

bool session_is_registered ( string name )

session_is_registered() restituisce TRUE se c'è una variabile con il nome name registrato nella sessione corrente.

Nota: Se è usata $_SESSION (o $HTTP_SESSION_VARS per PHP 4.0.6 o inferiore), usate isset() per controllare che una variabile sia registrata in $_SESSION.

Attenzione

Se state usando $HTTP_SESSION_VARS/$_SESSION, non usate session_register(), session_is_registered() e session_unregister().

session_module_name

(PHP 4, PHP 5)

session_module_name -- Assume o imposta il corrente modulo di sessione

Descrizione

string session_module_name ( [string module] )

session_module_name() restituisce il nome del corrente modulo di sessione. Se module è specificato, sarà invece usato quel modulo.

session_name

(PHP 4, PHP 5)

session_name -- Dà e/o stabilisce il nome della sessione corrente

Descrizione

string session_name ( [string name] )

session_name() ritorna il nome della sessione corrente. Se name è specificato, il nome della sessione corrente viene cambiato al suo valore.

Il nome della sessione riporta l'id nei coookies e negli URl. Dovrebbe contenere solo caratteri alfanumerici; dovrebbe essere corto e descrittivo (i.e. per utenti con l'avviso di cookie attivo). Il nome di sessione è resettato al valore di default archiviato in session.name quando avviene la richiesta iniziale. Tuttavia, avete bisogno di chiamare session_name() per ogni richiesta (e prima vengono chiamate session_start() o session_register()).

Esempio 1. session_name() esempi

<?php

// imposta il nome di sessione a WebsiteID

$previous_name = session_name("WebsiteID");

echo "Il precedente nome di sessione è $previous_name<p>";
?>

session_regenerate_id

(PHP 4 >= 4.3.2, PHP 5)

session_regenerate_id --  Update the current session id with a newly generated one

Descrizione

bool session_regenerate_id ( [bool delete_old_session] )

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Elenco dei parametri

delete_old_session

Whether to delete the old associated session file or not. Defaults to FALSE.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Log delle modifiche

VersioneDescrizione
4.3.3 Since then, if session cookies are enabled, use of session_regenerate_id() will also submit a new session cookie with the new session id.
5.1.0 Added the delete_old_session parameter.

Esempi

Esempio 1. A session_regenerate_id() example

<?php
session_start();

$old_sessionid = session_id();

session_regenerate_id();

$new_sessionid = session_id();

echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";

print_r($_SESSION);
?>

session_register

(PHP 4, PHP 5)

session_register --  Registra una o più variabili con la sessione corrente

Descrizione

bool session_register ( mixed name [, mixed ...] )

session_register() accetta un numero di argomenti variabile, ognuno dei quali può sia essere una stringa contenente il nome di una variabile o un array che contiene i nomi delle variabili o altri arrays. Per ogni nome, session_register() registra la variabile globale con quel nome nella sessione corrente.

Attenzione

Questo registra un variabile global. Se volete registrare una variabile di sessione interna a una funzione, avete bisogno di assicurarvi di farla globale usando global() o usate gli arrays di sessione come scritto sotto.

Attenzione

Se state usando $HTTP_SESSION_VARS/$_SESSION, non usate session_register(), session_is_registered() e session_unregister().

Questa funzione restituisce TRUE quando tutte le variabili sono registrate con successo nella sessione.

Se session_start() non è stata chiamata prima che questa funzione venga chiamata, avverrà una chiamata imlicita senza parametri a session_start().

Potete anche creare una variabile di sessione semplicemente impostando l'appropriato membro di $HTTP_SESSION_VARS o $_SESSION (PHP >= 4.1.0) array.

$barney = "Una grande torta fiammeggiante.";
session_register("barney");

$HTTP_SESSION_VARS["zim"] = "Mars attack.";

# the auto-global $_SESSION array was introduced in PHP 4.1.0
$_SESSION["spongebob"] = "Ha i pantaloni a quadri.";

Nota: Non è possibile registrare risorse variabili in una sessione. Per esempio, non potete creare una connessione a un database e archiviare l'id della connessione come una variabile di sessione e aspettarvi che la connessione sia ancora valida la prossima volta che la sessione viene riastabilita. Le funzioni PHP che restituiscono una risorsa sono identificate avendo un tipo di restituzione resource nelle loro definizioni di funzione. Una lista di funzioni che restituisce risorse è disponibile nell'appendice resource types.

Se viene usata $_SESSION (o $HTTP_SESSION_VARS per PHP 4.0.6 or inferiore), assegna la variabile a $_SESSION. i.e. $_SESSION['var'] = 'ABC';

Vedere anche session_is_registered() e session_unregister().

session_save_path

(PHP 4, PHP 5)

session_save_path -- Assume o stabilisce il percorso di salvataggio sessione corrente

Descrizione

string session_save_path ( [string path] )

session_save_path() restituisce il percorso della directory corrente usata per salvare i dati di sessione. Se path è specificato, il percorso in quale i dati vengono salvati verrà cambiata.

Nota: Su alcuni sistemi operativi, potreste voler specificare un percorso su un filesystem che gestisce molti piccoli files in modo efficiente. Per esempio, su Linux, reiserfs potrebbe garantire una migliore prestazione di ext2fs.

session_set_cookie_params

(PHP 4, PHP 5)

session_set_cookie_params --  Imposta i parametri del cookie di sessione

Descrizione

void session_set_cookie_params ( int lifetime [, string path [, string domain]] )

Imposta i parametri del cookie definiti nel file php.ini. L'effetto di questa funzione dura solo per la durata dello script.

session_set_save_handler

(PHP 4, PHP 5)

session_set_save_handler --  Imposta le funzioni di archiviazione sessioni a livello utente

Descrizione

void session_set_save_handler ( string open, string close, string read, string write, string destroy, string gc )

session_set_save_handler() imposta le funzioni di archiviazione sessioni che sono usate per archiviare e riutilizzare i dati associati a una sessione. Ciò non è molto utile quando un altro metodo di archiviazione è preferito a quelli forniti dalle sessioni PHP. i.e. L'archiviazione dei dati di sessione in un database locale.

Nota: Dovete impostare l'opzione di configurazione session.save_handler per user nel vostro file php.ini perchè session_set_save_handler() abbia effetto.

Nota: L'handler "write" non viene eseguito fino a che l'output stream non viene chiuso. In questo modo, l'output di espressioni di debugging nell'hanlder "write" non si vedrà mai nel browser. Se l'output di debugging è necessario, è consigliabile che l'output del debug venga scritto in un file.

Il seguente esempio fornisce l'archiviazione di sessione basata su file simile al solito gestore di salvataggio di sessioni PHP files. Questo esempio potrebbe essere facilmente esteso per coprire l'archiviazione in database usando il vostro sistema database favorito con supporto PHP.

La funzione di lettura deve restituire sempre un valore stringa perchè il save handler funzioni a dovere. Restituisce una stringa vuota se non ci sono dati da leggere. I valori restituiti da altri handlers sono convertiti in espressioni booleane. TRUE per successo, FALSE in caso di fallimento.

Esempio 1. session_set_save_handler() esempio

<?php
function open ($save_path, $session_name) {
  global $sess_save_path, $sess_session_name;
       
  $sess_save_path = $save_path;
  $sess_session_name = $session_name;
  return(true);
}

function close() {
  return(true);
}

function read ($id) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "r")) {
    $sess_data = fread($fp, filesize($sess_file));
    return($sess_data);
  } else {
    return(""); // Deve restituire "" qui.
  }

}

function write ($id, $sess_data) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    return(fwrite($fp, $sess_data));
  } else {
    return(false);
  }

}

function destroy ($id) {
  global $sess_save_path, $sess_session_name;
       
  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

/*********************************************
 * ATTENZIONE - Qui avete bisogno di implementare qualche *
 * sorta di routine per il cestinaggio.  *
 *********************************************/
function gc ($maxlifetime) {
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");

session_start();

// proceed to use sessions normally

?>

session_start

(PHP 4, PHP 5)

session_start -- Inizializza i dati di sessione

Descrizione

bool session_start ( void )

session_start() creauna sessione (o riprende quella corrente basata sull'id di sessione che viene passato attraverso una variabile GET o un cookie.

Se volete usare usare una sessione con un nome, dovete chiamare session_name() prima di session_start().

Questa funzione ritorna sempre TRUE.

Nota: Se state usando una sessione basata sui cookie, dovete chiamare session_start() prima di qualsiasi altro output al browser.

session_start() registrerà un handler interno di output per riscrivere l'URL quando trans-sid è attivato. Se l'utente usa ob_gzhandler o come con ob_start(), l'ordine dell'handler di output è importante per un giusto output. Per esempio, l'utente deve registrare ob_gzhandler prima che la sessione cominci.

Nota: L'uso di zlib.output_compression è raccomandato più che di ob_gzhandler

session_unregister

(PHP 4, PHP 5)

session_unregister --  Deregistra una variabile dalla sessione corrente

Descrizione

bool session_unregister ( string name )

session_unregister() deregistra (dimentica) la variabile globale con nome name dalla sessione corrente.

Questa funzione restituisce TRUE quando la variabile viene deregistrata con successo dalla sessione.

Nota: Se viene usata $_SESSION (o $HTTP_SESSION_VARS per PHP 4.0.6 o inferiore), usate unset() per deregistrare una variabile di sessione.

Attenzione

Questa funzione non deimposta la corrispondente variabile globale per name, impedisce solo che la variabile venga salvata come parte della sessione. Dovete chiamare unset() per rimuovere la variabile globale corrispondente.

Attenzione

Se state usando $HTTP_SESSION_VARS/$_SESSION, non usate session_register(), session_is_registered() e session_unregister().

session_unset

(PHP 4, PHP 5)

session_unset --  Libera tutte le variabili di sessione

Descrizione

void session_unset ( void )

La funzione session_unset() libera tutte le variabili di sessione correntemente registrate.

Nota: Se è usata $_SESSION (o $HTTP_SESSION_VARS per PHP 4.0.6 o inferiore) è, usate unset() per deregistrare una variabile di sessione. i.e. $_SESSION = array();

session_write_close

(PHP 4 >= 4.0.4, PHP 5)

session_write_close -- Scrive i dati di sessione e termina la sessione

Descrizione

void session_write_close ( void )

Termina la sessione corrente e archivia i dati di sessione.

I dati di sessione sono di solito archiviati dopo che il vostro script è terminato senza il bisogno di chiamare session_write_close(), ma poichè i dati di sessione vengono bloccati per prevenire scritture contemporanee solo uno script può operare su una sessione in qualsiasi momento. Quando utilizzerete i framesets assieme alla sessione vedrete che i frames vengono caricati uno per uno a causa di questo bloccaggio. Potete ridurre il tempo necessario per caricare tutti i frames terminando la sessione appena tutti i cambi alle variabili di sessione sono stati fatti.

CXXXV. Funzioni relative alla memoria condivisa

Introduzione

Shmop è un set di funzioni di semplice utilizzo che permettono al PHP di leggere, scrivere, creare e cancellare i segmenti di memoria condivisa di Unix.

Nota: Occorre rilevare che nelle versioni di Windows precedenti a Windows 2000 non supportano la memoria condivisa. In Windows, le funzioni Shmop sono eseguilbili solo se il PHP sta girando come server web, tipo con Apache o ISS (nelle modalità CLI o CGI non è utilizzabile). Nella versione 4.0.3 di PHP queste funzioni hanno il prefisso shm anzichè shmop.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Per utilizzare shmop occorre compilare il PHP con il parametro --enable-shmop nella linea di configurazione.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Esempio 1. Descrizione delle operazioni con la memoria condivisa

<?php
   
// Crea un blocco di memoria condivisa di 100 byte con id 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if (!$shm_id) {
    echo "Non si riesce a creare il segmento di memoria condivisa\n";
}

// Ottiene la dimensione del blocco di memoria
$shm_size = shmop_size($shm_id);
echo "Dimesione blocco creato: " . $shm_size . ".\n";

// Scrittura di una stringa di test nella memoria condivisa
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if ($shm_bytes_written != strlen("my shared memory block")) {
    echo "Non si riesce a scrivere tutti i dati\n";
}

// Ora si rilegge la stringa
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
    echo "Non si riesce a leggere dalla memoria condivisa\n";
}
echo "I dati presenti nella memoria condivisa sono: ".$my_string."\n";

// Ora si cancella il blocco e si chiude il segmento di memoria condivisa
if (!shmop_delete($shm_id)) {
    echo "Non si riesce a marcare il blocco di memoria condivisa per la cancellazione.";
}
shmop_close($shm_id);
   
?>

Sommario
shmop_close -- Chiusura di un blocco di memoria condivisa
shmop_delete -- Cancella un blocco di memoria condivisa
shmop_open -- Crea oppure apre un segmento di memoria condivisa
shmop_read -- Legge i dati da un segmento di memoria condivisa
shmop_size -- Restituisce la dimensione di un blocco di memoria condivisa
shmop_write -- Scrittura di dati nel blocco di memoria condivisa

shmop_close

(PHP 4 >= 4.0.4, PHP 5)

shmop_close -- Chiusura di un blocco di memoria condivisa

Descrizione

int shmop_close ( int shmid )

Si utilizza la funzione shmop_close() per chiudere un segmento di memoria condivisa.

La funzione shmop_close() ha un solo parametro, shmid, che è l'identificativo del blocco di memoria condivisa creato da shmop_open().

Esempio 1. Chiusura di un blocco di memoria condivisa

<?php
shmop_close($shm_id);
?>

In questo esempio si chiude il blocco di memoria condivisa identificata da $shm_id.

shmop_delete

(PHP 4 >= 4.0.4, PHP 5)

shmop_delete -- Cancella un blocco di memoria condivisa

Descrizione

int shmop_delete ( int shmid )

La funzione shmop_delete() viene utilizzata per cancellare un blocco di memoria condivisa.

La funzione shmop_delete() ha un solo parametro, shmid, che è l'identificativo del blocco di memoria condiviso creato da shmop_open(). Se la funzione ha successo restituisce 1, altrimenti 0.

Esempio 1. Cancellazione di un segmento di memoria condivisa

<?php
shmop_delete($shm_id);
?>

In questo esempio si cancella il segmento di memoria condivisa identificato da $shm_id.

shmop_open

(PHP 4 >= 4.0.4, PHP 5)

shmop_open -- Crea oppure apre un segmento di memoria condivisa

Descrizione

int shmop_open ( int key, string flags, int mode, int size )

La funzione shmop_open() può creare oppure aprire un segmento di memoria condivisa.

La funzione shmop_open() utilizza 4 parametri: key, indica l'identificativo di sistema per il segmento di memoria condivisa, questo parametro può essere passato come numero decimale o esadecimale. Il secondo parametro è un flag che può assumere i seguenti valori:

  • "a" per accesso (SHM_RDONLY per shmat), usare questo flag quando occorre aprire un segmento di memoria condivisa esistente in sola lettura

  • "c" per creazione (IPC_CREATE), usare questo flag quando si ha la necessità di creare un nuovo segmento di memoria condivisa oppure, se esiste già un segmento con la medesima chiave, tentare di aprirlo in lettura e scrittura

  • "w" per accesso in lettura & scrittura, usare questo flag quando si deve accedere al segmento di memoria condivisa in lettura e scrittura, nella maggior parte dei casi si usa questo flag.

  • "n" per creare un nuovo segmento (IPC_CREATE|IPC_EXCL), usare questo flag quando si vuole creare un nuovo segmento di memoria condivisa, ma, se già ne esiste uno con il medesimo flag, la funzione fallisce. Ciò è utile per motivi di sicurezza, infatti questo permette di evitare problemi di concorrenza.

Il terzo parametro, mode, indica i permessi che si desidera assegnare al segmento di memoria, questi sono i medesimi permessi utilizzati per un file. Occorre passare i permessi in forma ottale, ad esempio 0644. L'ultimo parametro è la dimensione in bytes del blocco di memoria condivisa che si desidera creare.

Nota: Il terzo ed il quarto parametro dovrebbero essere a 0 se si sta aprendo un segmento di memoria esistene. Se la funzione shmop_open() ha successo, sarà restituito un id da usarsi per accedere al segmento di memoria condivisa appena creato.

Esempio 1. Creazione di un nuovo blocco di memoria condivisa

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

Questo esempio apre un blocco di memoria condivisa con id di sistema restituito da ftok().

shmop_read

(PHP 4 >= 4.0.4, PHP 5)

shmop_read -- Legge i dati da un segmento di memoria condivisa

Descrizione

string shmop_read ( int shmid, int start, int count )

La funzione shmop_read() legge una stringa da un blocco di memoria condivisa.

La funzione shmop_read() utilizza 3 parametri: shmid, che è l'identificativo del blocco di memoria condivisa creato da shmop_open(); start, che indica l'offset da cui partire a leggere e count che indica il numero dei byte da leggere.

Esempio 1. Lettura di un segmento di memoria condivisa

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

Questo esempio legge 50 byte da un blocco di memoria condivisa e posiziona i dati nella variabile $shm_data.

shmop_size

(PHP 4 >= 4.0.4, PHP 5)

shmop_size -- Restituisce la dimensione di un blocco di memoria condivisa

Descrizione

int shmop_size ( int shmid )

Si utilizza la funzione shmop_size() per ottenere la dimensione in byte del segmento di memoria condivisa.

La funzione shmop_size() ha un solo parametro, shmid, che è l'identificativo del blocco di memoria condiviso creato da shmop_open(); la funzione restituisce un numero intero che rappresenta il numero dei byte occupati dal segmento di memoria condivisa.

Esempio 1. Come ottenere la dimensione della memoria condivisa

<?php
$shm_size = shmop_size($shm_id);
?>

In questo esempio si memorizza nella variabile $shm_size la dimensione del blocco di memoria identificato da $shm_id.

shmop_write

(PHP 4 >= 4.0.4, PHP 5)

shmop_write -- Scrittura di dati nel blocco di memoria condivisa

Descrizione

int shmop_write ( int shmid, string data, int offset )

La funzione shmop_write() scrive una stringa in un segmento di memoria condivisa.

La funzione shmop_write() utilizza 3 parametri: shmid, che è l'identificativo del blocco di memoria condiviso creato da shmop_open(); data, che è la stringa che si vuole scrivere nel blocco di memoria e offset, che specifica dove cominciare a scrivere nella memoria condivisa.

Esempio 1. Scrittura di un blocco di memoria condivisa

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

Questo esempio scrive i dati della variabile $my_string nel blocco di memoria condivisa, mentre $shm_bytes_written contiene il numero dei byte scritti.

CXXXVI. SimpleXML functions

Introduzione

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.


Requisiti

The SimpleXML extension requires PHP 5.


Installazione

The SimpleXML extension is enabled by default. To disable it, use the --disable-simplexml configure option.


Esempi

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Esempio 1. Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Esempio 2. Getting <plot>

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

echo $xml->movie[0]->plot; // "So this language. It's like..."
?>

Esempio 3. Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

/* For each <movie> node, we echo a separate <plot>. */
foreach ($xml->movie as $movie) {
   echo $movie->plot, '<br />';
}

?>

Esempio 4. Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($xml->movie[0]->rating as $rating) {
    switch((string) $rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?>

Esempio 5. Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php     
include 'example.php';

$xml = simplexml_load_string($xmlstr);

if ((string) $xml->movie->title == 'PHP: Behind the Parser') {
    print 'My favorite movie.';
}

htmlentities((string) $xml->movie->title);
?>

Esempio 6. Using Xpath

SimpleXML includes builtin Xpath support. To find all <character> elements:

<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);

foreach ($xml->xpath('//character') as $character) {
    echo $character->name, 'played by ', $character->actor, '<br />';
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

Esempio 7. Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);

$xml->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $xml->asXML();
?>

The above code will output a new XML document, just like the original, except that the new XML will change Ms. Coder to Miss Coder.

Esempio 8. DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new domDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
     echo 'Error while parsing the document';
     exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

Sommario
SimpleXMLElement->asXML --  Return a well-formed XML string based on SimpleXML element
SimpleXMLElement->attributes --  Identifies an element's attributes
SimpleXMLElement->children --  Finds children of given node
SimpleXMLElement->xpath --  Runs Xpath query on XML data
simplexml_import_dom --  Get a SimpleXMLElement object from a DOM node.
simplexml_load_file --  Interprets an XML file into an object
simplexml_load_string --  Interprets a string of XML into an object

SimpleXMLElement->asXML

(no version information, might be only in CVS)

SimpleXMLElement->asXML --  Return a well-formed XML string based on SimpleXML element

Descrizione

mixed SimpleXMLElement->asXML ( [string filename] )

The asXML method formats the parent object's data in XML version 1.0.

Elenco dei parametri

filename

If specified, the function writes the data to the file rather than returning it.

Valori restituiti

If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

Esempi

Esempio 1. Get XML

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = simplexml_load_string($string);

echo $xml->asXML(); // <?xml ... <a><b><c>text</c><c>stuff</c> ...

?>

asXML also works on Xpath results:

Esempio 2. Using asXML() on Xpath results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo $node->asXML(); // <c>text</c> and <c>stuff</c>
}
?>

SimpleXMLElement->attributes

(no version information, might be only in CVS)

SimpleXMLElement->attributes --  Identifies an element's attributes

Description

SimpleXMLElement simplexml_element->attributes ( [string data] )

This function provides the attributes and values defined within an xml tag.

Nota: SimpleXML possiede regole per aggiungere proprietà iterative a diversi metodi. Queste non possono essere visualizzate con var_dump() o qualsiasi altra cosa che possa esaminare gli oggetti.

Esempio 1. Interpret an XML string

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

This script will display:

name="one"
game="lonely"

SimpleXMLElement->children

(no version information, might be only in CVS)

SimpleXMLElement->children --  Finds children of given node

Description

SimpleXMLElement simplexml_element->children ( [string nsprefix] )

This method finds the children of the element of which it is a member. The result follows normal iteration rules.

Nota: SimpleXML possiede regole per aggiungere proprietà iterative a diversi metodi. Queste non possono essere visualizzate con var_dump() o qualsiasi altra cosa che possa esaminare gli oggetti.

Esempio 1. Traversing a children() pseudo-array

<?php
$xml = simplexml_load_string(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

foreach ($xml->children() as $second_gen) {
    echo ' The person begot a ' . $second_gen['role'];

    foreach ($second_gen->children() as $third_gen) {
        echo ' who begot a ' . $third_gen['role'] . ';';
    
        foreach ($third_gen->children() as $fourth_gen) {
            echo ' and that ' . $third_gen['role'] .
                ' begot a ' . $fourth_gen['role'];
        }
    }
}
?>

This script will output:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

SimpleXMLElement->xpath

(no version information, might be only in CVS)

SimpleXMLElement->xpath --  Runs Xpath query on XML data

Description

array SimpleXMLElement->xpath ( string path )

The xpath method searches the SimpleXML node for children matching the Xpath path. It always returns an array of SimpleXMLElement objects.

Esempio 1. Xpath

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = simplexml_load_string($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}
?>

This script will display:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

simplexml_import_dom

(PHP 5)

simplexml_import_dom --  Get a SimpleXMLElement object from a DOM node.

Description

SimpleXMLElement simplexml_import_dom ( DOMNode node [, string class_name] )

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element. If any errors occur, it returns FALSE.

Esempio 1. Import DOM

<?php
$dom = new domDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title; // blah
?>

See also dom_import_simplexml().

simplexml_load_file

(PHP 5)

simplexml_load_file --  Interprets an XML file into an object

Description

object simplexml_load_file ( string filename [, string class_name [, int options]] )

This function will convert the well-formed XML document in the file specified by filename to an object of class SimpleXMLElement. If any errors occur during file access or interpretation, the function returns FALSE.

You may use the optional class_name parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Nota: Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.

Esempio 1. Interpret an XML document

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');
 
    var_dump($xml);
} else {
    exit('Failed to open test.xml.');
}
?>

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

See also: simplexml_load_string()

simplexml_load_string

(PHP 5)

simplexml_load_string --  Interprets a string of XML into an object

Description

object simplexml_load_string ( string data [, string class_name [, int options]] )

This function will take the well-formed xml string data and return an object of class SimpleXMLElement with properties containing the data held within the xml document. If any errors occur, it returns FALSE.

You may use the optional class_name parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Esempio 1. Interpret an XML string

<?php
$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

var_dump($xml);
?>

This script will display:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

At this point, you can go about using $xml->body and such.

See also: simplexml_load_file().

CXXXVII. Funzioni per SNMP


Requisiti

Per potere utilizzare le funzioni SNMP su un sistema Unix, occorre installare il pacchetto NET SNMP. Sui sistemi Windows, invece, le funzioni SNMP sono disponibili soltanto su NT e non sui sistemi Windows 95 e 98.


Installazione

Attenzione: per potere usare il pacchetto UCD SNMP, occorre definire NO_ZEROLENGTH_COMMUNITY a 1 prima di compilarlo. Dopo avere configurato UCD SNMP, occorre editare il file config.h, cercare NO_ZEROLENGTH_COMMUNITY e decommentare la linea #define. Alla fine si deve ottenere:
#define NO_ZEROLENGTH_COMMUNITY 1
Ora si può compilare PHP con --with-snmp[=DIR].

Se durante l'uso dei comandi SNMP dovessero comparire degli errori di "segmentation fault", non seguire le istruzioni precedenti. Se non si desidera ricompilare il pacchetto UCD SNMP, si può optare per compilare PHP con l'opzione --enable-ucd-snmp-hack che aggira questo problema.

La distribuzione per Windows contiene i file di supporto per SNMP nella directory mibs. Questa directory dovrebbe esse spostata in DRIVE:\usr\mibs, dove DRIVE deve essere sostituito con la lettera del disco su cui è installato il PHP, ad esempio c:\usr\mibs


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

SNMP_VALUE_LIBRARY (integer)

SNMP_VALUE_PLAIN (integer)

SNMP_VALUE_OBJECT (integer)

SNMP_BIT_STR (integer)

SNMP_OCTET_STR (integer)

SNMP_OPAQUE (integer)

SNMP_NULL (integer)

SNMP_OBJECT_ID (integer)

SNMP_IPADDRESS (integer)

SNMP_COUNTER (integer)

SNMP_UNSIGNED (integer)

SNMP_TIMETICKS (integer)

SNMP_UINTEGER (integer)

SNMP_INTEGER (integer)

SNMP_COUNTER64 (integer)

Sommario
snmp_get_quick_print --  Restituisce il valore corrente per il parametro quick_print della libreria UCD
snmp_get_valueretrieval --  Return the method how the SNMP values will be returned
snmp_read_mib --  Reads and parses a MIB file into the active MIB tree
snmp_set_enum_print --  Return all values that are enums with their enum value instead of the raw integer
snmp_set_oid_numeric_print --  Return all objects including their respective object id within the specified one
snmp_set_quick_print -- Setta il valore di quick_print
snmp_set_valueretrieval --  Specify the method how the SNMP values will be returned
snmpget -- Preleva un oggetto SNMP
snmpgetnext --  Fetch a SNMP object
snmprealwalk --  Restituisce tutti gli oggetti compresi i rispettivi ID di oggetto
snmpset -- Valorizza un oggetto SNMP
snmpwalk -- Scarica tutti gli oggetti SNMP da un agente
snmpwalkoid -- Richiesta dell'albero delle informazioni di una macchina di rete

snmp_get_quick_print

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmp_get_quick_print --  Restituisce il valore corrente per il parametro quick_print della libreria UCD

Descrizione

bool snmp_get_quick_print ( void )

La funzione restituisce il valore del parametro quick_print della libreria UCD. Per default quick_print è settato ad off.

Esempio 1. Esempio di snmp_get_quick_print()

<?php
$quickprint = snmp_get_quick_print();
?>

Nell'esempio precedente la funzione restituirebbe FALSE se quick_print fosse ad off, TRUE se quick_print fosse ad on.

La funzione snmp_get_quick_print() è disponibile soltanto con l'uso della libreria UCD SNMP. Questa funzione non è disponibile nella libreria SNMP per Windows.

Vedere anche snmp_set_quick_print() per una descrizione completa di quick_print.

snmp_get_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_get_valueretrieval --  Return the method how the SNMP values will be returned

Description

int snmp_get_valueretrieval ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmp_read_mib

(PHP 5)

snmp_read_mib --  Reads and parses a MIB file into the active MIB tree

Description

bool snmp_read_mib ( string filename )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_enum_print --  Return all values that are enums with their enum value instead of the raw integer

Description

void snmp_set_enum_print ( int enum_print )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_oid_numeric_print --  Return all objects including their respective object id within the specified one

Description

void snmp_set_oid_numeric_print ( int oid_numeric_print )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmp_set_quick_print

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmp_set_quick_print -- Setta il valore di quick_print

Descrizione

void snmp_set_quick_print ( bool quick_print )

La funzione setta il valore del parametro quick_print della libreria UCD SNMP. Quando è attivo (1), la libreria SNMP restituisce valori 'quick printed'. Ciò significa che saranno visualizzati solo i valori. Quando quick_print non è attivo (default), la libreria UCD SNMP visualizzerà informazioni extra tra i quali il tipo del valore (per esempio IpAddress oppure OID). Inoltre, se quick_print non è abilitato, la libreria visualizza il valore esadecimale per tutte le stringhe di tre caratteri o meno.

L'attivazione di quick_print viene spesso usata quando l'informazione restuita viene utilizzata piuttosto che visualizzata.

<?php
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a< br />\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a<br />\n";
?>

Il primo valore visualizzato può essere 'Timeticks: (0) 0:00:00.00', mentre con quick_print abilitato sarebbe stato '0:00:00.00'.

Per default la libreria UCD SNMP restituisce valori discorsivi, mentre quick_print viene usato per avere solo il valore.

Attualmente le stringhe sono restituite con apici aggiuntivi, questo sarà corretto in una release successiva.

La funzione snmp_set_quick_print() è disponibile soltanto con l'uso della libreria UCD SNMP. Questa funzione non è disponibile nella libreria SNMP per Windows.

snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_set_valueretrieval --  Specify the method how the SNMP values will be returned

Description

void snmp_set_valueretrieval ( int method )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmpget

(PHP 3, PHP 4, PHP 5)

snmpget -- Preleva un oggetto SNMP

Descrizione

string snmpget ( string hostname, string community, string object_id [, int timeout [, int retries]] )

La funzione restituisce il valore di un oggetto SNMP se ha successo, altrimenti FALSE se si verificano errori

La funzione snmpget(), viene utilizzata per leggere il valore dell'oggetto SNMP specificato da object_id. L'agente SNMP a cui accedere viene specificato nel parametro hostname, mentre la comunità viene indicata in community.

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

snmpgetnext

(PHP 5)

snmpgetnext --  Fetch a SNMP object

Description

string snmpgetnext ( string host, string community, string object_id [, int timeout [, int retries]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmprealwalk

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmprealwalk --  Restituisce tutti gli oggetti compresi i rispettivi ID di oggetto

Descrizione

array snmprealwalk ( string host, string community, string object_id [, int timeout [, int retries]] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

snmpset

(PHP 3 >= 3.0.12, PHP 4, PHP 5)

snmpset -- Valorizza un oggetto SNMP

Descrizione

bool snmpset ( string hostname, string community, string object_id, string type, mixed value [, int timeout [, int retries]] )

Setta il valore di un specifico oggetto SNMP. La funzione restituisce TRUE se ha successo, FALSE se si verifica un errore.

La funzione snmpset() viene usata per settare il valore dell'oggetto SNMP indicato dal parametro object_id. L'agente SNMP viene indicato nel parametro hostname e la comunità viene specificata nel parametro community.

snmpwalk

(PHP 3, PHP 4, PHP 5)

snmpwalk -- Scarica tutti gli oggetti SNMP da un agente

Descrizione

array snmpwalk ( string hostname, string community, string object_id [, int timeout [, int retries]] )

La funzione restituisce un array con i valori degli oggetti SNMP utilizzando object_id come punto di partenza, oppure FALSE se si verifica un errore.

La funzione snmpwalk() viene utilizzata per leggere tutti i valori dall'agente SNMP specificato nel parametro hostname. Il parametro Community specifica la comunità per l'agente. Con l'impostazione a NULL del parametro object_id si indica la radice dell'albero degli oggetti SNMP, pertanto saranno restituiti nell'array tutti gli oggetti dell'albero. Viceversa se si indica un valore per object_id, sarranno restituiti tutti gli oggetti sottostanti object_id.

<?php
$a = snmpwalk("127.0.0.1", "public", ""); 
?>

L'esempio precedente mostra come recuperare tutti gli oggetti SNMP dall'agente attivo sulla macchina locale. Tramite un loop (illustrato di seguito) si può accedere a tutti i valori.

<?php
for ($i=0; $i < count($a); $i++) {
    echo $a[$i];
}
?>

snmpwalkoid

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

snmpwalkoid -- Richiesta dell'albero delle informazioni di una macchina di rete

Descrizione

array snmpwalkoid ( string hostname, string community, string object_id [, int timeout [, int retries]] )

La funzione restituisce un array associativo contenente gli id degli oggetti ed il loro rispettivo valore usando l'oggetto indicato in object_id come radice. Se si verificano degli errori la funzione restituisce FALSE.

La funzione snmpwalkoid() viene utilizzata per leggere gli id di tutti gli oggetti SNMP ed i relativi valori da un agente SNMP presente sul server indicato da hostname. La comunità viene specificata nel parametro community. Con l'impostazione a NULL del parametro object_id si indica la radice dell'albero degli oggetti SNMP, pertanto saranno restituiti nell'array tutti gli oggetti dell'albero. Viceversa se si indica un valore per object_id, sarranno restituiti tutti gli oggetti sottostanti a object_id.

La presenza delle due funzioni snmpwalkoid() e snmpwalk() ha ragioni storiche. Sono presenti entrambe per compatibilità con il passato.

<?php
$a = snmpwalkoid("127.0.0.1", "public", ""); 
?>

L'esempio precedente mostra come recuperare tutti gli oggetti SNMP dall'agente attivo sulla macchina locale. Tramite un loop (illustrato di seguito) si può accedere a tutti i valori.

<?php
for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]<br />\n";
}
?>

CXXXVIII. SOAP Functions

Introduzione

The SOAP extension can be used to write SOAP Servers and Clients. It supports subsets of SOAP 1.1, SOAP 1.2 and WSDL 1.1 specifications.


Requisiti

This extension makes use of the GNOME xml library. Download and install this library. You will need at least libxml-2.5.4.


Installazione

This extension is only available if PHP was configured with --enable-soap.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. SOAP Configuration Options

NameDefaultChangeableChangelog
soap.wsdl_cache_enabled"1"PHP_INI_ALLAvailable since PHP 5.0.0.
soap.wsdl_cache_dir"/tmp"PHP_INI_ALLAvailable since PHP 5.0.0.
soap.wsdl_cache_ttl"86400"PHP_INI_ALLAvailable since PHP 5.0.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

soap.wsdl_cache_enabled boolean

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl int

Sets the number of seconds (time to live) that cached files will be used instead the originals.


Classi predefinite

SoapClient


Costruttori


Metodi


SoapFault


Costruttori


SoapHeader

SoapHeader is a special low-level class for passing or returning SOAP headers. It's just a data holder and it does not have any special methods except its constructor. It can be used in the SoapClient->__soapCall() method to pass a SOAP header or in a SOAP header handler to return the header in a SOAP response.


Costruttori


SoapParam

SoapParam is a special low-level class for naming parameters and returning values in non-WSDL mode. It's just a data holder and it does not have any special methods except its constructor.


Costruttori


SoapServer


Costruttori


Metodi


SoapVar

SoapVar is a special low-level class for encoding parameters and returning values in non-WSDL mode. It's just a data holder and does not have any special methods except the constructor. It's useful when you want to set the type property in SOAP request or response.


Costruttori


Costanti predefinite

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.

SOAP_1_1 (integer)

SOAP_1_2 (integer)

SOAP_PERSISTENCE_SESSION (integer)

SOAP_PERSISTENCE_REQUEST (integer)

SOAP_FUNCTIONS_ALL (integer)

SOAP_ENCODED (integer)

SOAP_LITERAL (integer)

SOAP_RPC (integer)

SOAP_DOCUMENT (integer)

SOAP_ACTOR_NEXT (integer)

SOAP_ACTOR_NONE (integer)

SOAP_ACTOR_UNLIMATERECEIVER (integer)

SOAP_COMPRESSION_ACCEPT (integer)

SOAP_COMPRESSION_GZIP (integer)

SOAP_COMPRESSION_DEFLATE (integer)

UNKNOWN_TYPE (integer)

XSD_STRING (integer)

XSD_BOOLEAN (integer)

XSD_DECIMAL (integer)

XSD_FLOAT (integer)

XSD_DOUBLE (integer)

XSD_DURATION (integer)

XSD_DATETIME (integer)

XSD_TIME (integer)

XSD_DATE (integer)

XSD_GYEARMONTH (integer)

XSD_GYEAR (integer)

XSD_GMONTHDAY (integer)

XSD_GDAY (integer)

XSD_GMONTH (integer)

XSD_HEXBINARY (integer)

XSD_BASE64BINARY (integer)

XSD_ANYURI (integer)

XSD_ANYXML (integer)

Added in PHP 5.1.0.

XSD_QNAME (integer)

XSD_NOTATION (integer)

XSD_NORMALIZEDSTRING (integer)

XSD_TOKEN (integer)

XSD_LANGUAGE (integer)

XSD_NMTOKEN (integer)

XSD_NAME (integer)

XSD_NCNAME (integer)

XSD_ID (integer)

XSD_IDREF (integer)

XSD_IDREFS (integer)

XSD_ENTITY (integer)

XSD_ENTITIES (integer)

XSD_INTEGER (integer)

XSD_NONPOSITIVEINTEGER (integer)

XSD_NEGATIVEINTEGER (integer)

XSD_LONG (integer)

XSD_INT (integer)

XSD_SHORT (integer)

XSD_BYTE (integer)

XSD_NONNEGATIVEINTEGER (integer)

XSD_UNSIGNEDLONG (integer)

XSD_UNSIGNEDINT (integer)

XSD_UNSIGNEDSHORT (integer)

XSD_UNSIGNEDBYTE (integer)

XSD_POSITIVEINTEGER (integer)

XSD_NMTOKENS (integer)

XSD_ANYTYPE (integer)

SOAP_ENC_OBJECT (integer)

SOAP_ENC_ARRAY (integer)

XSD_1999_TIMEINSTANT (integer)

XSD_NAMESPACE (string)

XSD_1999_NAMESPACE (string)

Sommario
is_soap_fault --  Checks if SOAP call was failed
SoapClient->__call() --  Calls a SOAP function (deprecated)
SoapClient->__construct() --  SoapClient constructor
SoapClient->__doRequest() --  Performs a SOAP request
SoapClient->__getFunctions() --  Returns list of SOAP functions
SoapClient->__getLastRequest() --  Returns last SOAP request
SoapClient->__getLastRequestHeaders() --  Returns last SOAP request headers
SoapClient->__getLastResponse() --  Returns last SOAP response.
SoapClient->__getLastResponseHeaders() --  Returns last SOAP response headers.
SoapClient->__getTypes() --  Returns list of SOAP types
SoapClient->__setCookie() --  Sets the cookie that will be sent with the SOAP request
SoapClient->__soapCall() --  Calls a SOAP function
SoapFault->__construct() --  SoapFault constructor
SoapHeader->__construct() --  SoapHeader constructor
SoapParam->__construct() --  SoapParam constructor
SoapServer->addFunction() --  Adds one or several functions those will handle SOAP requests
SoapServer->__construct() --  SoapServer constructor
SoapServer->fault() -- Issue SoapServer fault indicating an error
SoapServer->getFunctions() --  Returns list of defined functions
SoapServer->handle() --  Handles a SOAP request
SoapServer->setClass() --  Sets class which will handle SOAP requests
SoapServer->setPersistence() --  Sets persistence mode of SoapServer
SoapVar->__construct() --  SoapVar constructor
use_soap_error_handler -- Set whether to use the SOAP error handler and return the former value

is_soap_fault

(PHP 5)

is_soap_fault --  Checks if SOAP call was failed

Descrizione

bool is_soap_fault ( mixed obj )

This function is useful when you like to check if the SOAP call failed, but don't like to use exceptions. To use it you must create a SoapClient object with the exceptions option set to zero or FALSE. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

Elenco dei parametri

obj

The tested object.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. is_soap_fault() example

<?php
$client = new SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction();
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_ERROR);
}
?>

Esempio 2. SOAP's standard method for error reporting is exceptions

<?php
try {
    $client = new SoapClient("some.wsdl");
    $result = $client->SomeFunction(/* ... */);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_ERROR);
}
?>

SoapClient->__call()

(no version information, might be only in CVS)

SoapClient->__call() --  Calls a SOAP function (deprecated)

Descrizione

class SoapClient {

mixed __call ( string function_name, array arguments [, array options [, array input_headers [, array output_headers]]] )

}

This method is deprecated. Use SoapClient->__soapCall() instead of it.

SoapClient->__construct()

(no version information, might be only in CVS)

SoapClient->__construct() --  SoapClient constructor

Descrizione

class SoapClient {

__construct ( mixed wsdl [, array options] )

}

This constructor creates SoapClient objects in WSDL or non-WSDL mode.

Elenco dei parametri

wsdl

URI of the WSDL file or NULL if working in non-WSDL mode.

options

An array of options. If working in WSDL mode, this parameter is optional. If working in non-WSDL mode, you must set the location and uri options, where location is the URL to request and uri is the target namespace of the SOAP service.

The style and use options only work in non-WSDL mode. In WSDL mode, they come from the WSDL file.

The soap_version option specifies whether to use SOAP 1.1, or SOAP 1.2 client.

For HTTP authentication, you may use the login and password options. For making an HTTP connection through a proxy server, use the options proxy_host, proxy_port, proxy_login and proxy_password. For HTTPS client certificate authentication use local_cert and passphrase options.

The compression option allows to use compression of HTTP SOAP requests and responses.

The encoding option defines internal character encoding. This option does not change the encofing of SOAP requests (it is always utf-8), but converts strings into it.

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

The trace and exceptions options are useful for debuging purpose.

Esempi

Esempio 1. SoapClient examples

<?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version'   => SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080,
                                            'proxy_login'    => "some_name",
                                            'proxy_password' => "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert'     => "cert_key.pem"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/",
                                     'style'    => SOAP_DOCUMENT,
                                     'use'      => SOAP_LITERAL));

$client = new SoapClient("some.wsdl", 
  array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

$server = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

SoapClient->__doRequest()

(no version information, might be only in CVS)

SoapClient->__doRequest() --  Performs a SOAP request

Descrizione

class SoapClient {

string __doRequest ( string request, string location, string action, int version )

}

Performs SOAP request over HTTP.

This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.

Elenco dei parametri

request

The XML SOAP request.

location

The URL to request.

action

The SOAP action.

action

The SOAP version.

Valori restituiti

The XML SOAP response.

Esempi

Esempio 1. Some examples

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://', 
                                   'uri'=>'http://testuri.org')); 
var_dump($x->Add(3,4));
?>

SoapClient->__getFunctions()

(no version information, might be only in CVS)

SoapClient->__getFunctions() --  Returns list of SOAP functions

Descrizione

class SoapClient {

array __getFunctions ( void )

}

Returns the list of SOAP functions.

Nota: This function works only in WSDL mode.

Valori restituiti

The list of SOAP functions.

Esempi

Esempio 1. SoapClient->__getFunctions() example

<?php
$client = SoapClient("some.wsdl");
var_dump($client->__getFunctions());
?>

SoapClient->__getLastRequest()

(no version information, might be only in CVS)

SoapClient->__getLastRequest() --  Returns last SOAP request

Descrizione

class SoapClient {

string __getLastRequest ( void )

}

Nota: This method works only if the SoapClient object was created with the trace option.

Valori restituiti

The last SOAP request.

Esempi

Esempio 1. SoapClient->__getLastRequest() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

SoapClient->__getLastRequestHeaders()

(no version information, might be only in CVS)

SoapClient->__getLastRequestHeaders() --  Returns last SOAP request headers

Descrizione

class SoapClient {

string __getLastRequestHeaders ( void )

}

Nota: This method works only if the SoapClient object was created with the trace option.

Valori restituiti

The last SOAP request headers.

SoapClient->__getLastResponse()

(no version information, might be only in CVS)

SoapClient->__getLastResponse() --  Returns last SOAP response.

Descrizione

class SoapClient {

string __getLastResponse ( void )

}

Nota: This method works only if the SoapClient object was created with the trace option.

Valori restituiti

The last SOAP response.

Esempi

Esempio 1. SoapClient->__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE:\n" . $client->__getLastResponse() . "\n";
?>

SoapClient->__getLastResponseHeaders()

(no version information, might be only in CVS)

SoapClient->__getLastResponseHeaders() --  Returns last SOAP response headers.

Descrizione

class SoapClient {

string __getLastResponseHeaders ( void )

}

Nota: This method works only if the SoapClient object was created with the trace option.

Valori restituiti

The last SOAP response headers.

SoapClient->__getTypes()

(no version information, might be only in CVS)

SoapClient->__getTypes() --  Returns list of SOAP types

Descrizione

class SoapClient {

array __getTypes ( void )

}

This function works only in WSDL mode.

Valori restituiti

The list of SOAP types.

Esempi

Esempio 1. SoapClient->__getTypes() example

<?php
$client = new SoapClient("some.wsdl");
var_dump($client->__getTypes());
?>

SoapClient->__setCookie()

(no version information, might be only in CVS)

SoapClient->__setCookie() --  Sets the cookie that will be sent with the SOAP request

Descrizione

class SoapClient {

void __setCookie ( string name [, string value] )

}

Defines a cookie to be sent along with the SOAP requests.

Nota: Calling this method will affect all following calls to SoapClient methods.

Elenco dei parametri

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

Valori restituiti

No value is returned.

SoapClient->__soapCall()

(no version information, might be only in CVS)

SoapClient->__soapCall() --  Calls a SOAP function

Descrizione

class SoapClient {

mixed __soapCall ( string function_name [, array arguments [, array options [, mixed input_headers [, array &output_headers]]]] )

}

This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, you can simply call SOAP functions as SoapClient methods. This method useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.

On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().

Valori restituiti

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value of __soapCall will be a simple value (e.g. an integer, a string, etc). If multiple values are returned, __soapCall will return an associative array of named output parameters.

Esempi

Esempio 1. SoapClient->__soapCall() Examples

<?php

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c), NULL,
                    new SoapHeader(), $output_headers);


$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->SomeFunction($a, $b, $c);
$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c),
                    array('soapaction' => 'some_action',
                          'uri'        => 'some_uri'));
?>

SoapFault->__construct()

(no version information, might be only in CVS)

SoapFault->__construct() --  SoapFault constructor

Descrizione

class SoapFault {

__construct ( string faultcode, string faultstring [, string faultactor [, mixed detail [, string faultname [, SoapHeader headerfault]]]] )

}

This class is useful when you would like to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and details are standard elements of SOAP Fault;

Elenco dei parametri

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

Esempi

Esempio 1. Some examples

<?php
function test($x)
{
    return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

It is possible to use PHP exception mechanism to throw SOAP Fault.

Esempio 2. Some examples

<?php
function test($x)
{
    throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

SoapHeader->__construct()

(no version information, might be only in CVS)

SoapHeader->__construct() --  SoapHeader constructor

Descrizione

class SoapHeader {

__construct ( string namespace, string name [, mixed data [, bool mustUnderstand [, mixed actor]]] )

}

Constructs a new SoapHeader object.

Elenco dei parametri

namespace

The namespace of the SOAP header element.

name

The name of the SOAP header element.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

Esempi

Esempio 1. Some examples

<?php
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->__call("echoVoid", null, null,
                new SoapHeader('http://soapinterop.org/echoheader/',
                               'echoMeStringRequest',
                               'hello world'));
?>

SoapParam->__construct()

(no version information, might be only in CVS)

SoapParam->__construct() --  SoapParam constructor

Descrizione

class SoapParam {

__construct ( mixed data, string name )

}

Constructs a new SoapParam object.

Elenco dei parametri

data

The data to pass or return. You can pass this parameter directly as PHP value, but in this case it will be named as paramN and the SOAP Service may not understand it.

name

The parameter name.

Esempi

Esempio 1. Some examples

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>

SoapServer->addFunction()

(no version information, might be only in CVS)

SoapServer->addFunction() --  Adds one or several functions those will handle SOAP requests

Descrizione

class SoapServer {

void addFunction ( mixed functions )

}

Exports one or more functions for remote clients.

Elenco dei parametri

functions

To export one function, pass the function name into this parameter as a string.

To export several functions, pass an array of function names.

To export all the functions, pass a special constant SOAP_FUNCTIONS_ALL.

Nota: functions must receive all input arguments in the same order as defined in the WSDL file (They should not receive any output parameters as arguments) and return one or more values. To return several values they must return an array with named output parameters.

Valori restituiti

No value is returned.

Esempi

Esempio 1. Some examples

<?php

function echoString($inputString)
{
    return $inputString;
}

$server->addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
    return array("outputString1" => $inputString1,
                 "outputString2" => $inputString2);
}
$server->addFunction(array("echoString", "echoTwoStrings"));

$server->addFunction(SOAP_FUNCTIONS_ALL);

?>

SoapServer->__construct()

(no version information, might be only in CVS)

SoapServer->__construct() --  SoapServer constructor

Descrizione

class SoapServer {

__construct ( mixed wsdl [, array options] )

}

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

Elenco dei parametri

wsdl

If you want the WSDL mode, you must set this to the URI of a WSDL file. In the other case, you must set this to NULL and set the uri option.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor). The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

Esempi

Esempio 1. Some examples

<?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));

$server = new SoapServer(null, array('uri' => "http://test-uri/"));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

SoapServer->fault()

(no version information, might be only in CVS)

SoapServer->fault() -- Issue SoapServer fault indicating an error

Descrizione

class SoapServer {

void fault ( string code, string string [, string actor [, mixed details [, string name]]] )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SoapServer->getFunctions()

(no version information, might be only in CVS)

SoapServer->getFunctions() --  Returns list of defined functions

Descrizione

class SoapServer {

array getFunctions ( void )

}

This method returns the list of all functions added by SoapServer->addFunction() or SoapServer->setClass().

Valori restituiti

The list of all functions.

Esempi

Esempio 1. Some examples

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $server->handle();
} else {
  echo "This SOAP server can handle following functions: ";
  $functions = $server->getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?>

SoapServer->handle()

(no version information, might be only in CVS)

SoapServer->handle() --  Handles a SOAP request

Descrizione

class SoapServer {

void handle ( [string soap_request] )

}

Processes a SOAP request, calls necessary functions, and sends a response back.

Elenco dei parametri

soap_request

The SOAP request. If this argument is omitted, the request is supposed to be in the $HTTP_RAW_POST_DATA PHP variable.

Valori restituiti

No value is returned.

Esempi

Esempio 1. Some examples

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

SoapServer->setClass()

(no version information, might be only in CVS)

SoapServer->setClass() --  Sets class which will handle SOAP requests

Descrizione

class SoapServer {

void setClass ( string class_name [, mixed args [, mixed ...]] )

}

Exports all methods from specified class.

The object can be made persistent across request for a given PHP session with the SoapServer->setPersistence() method.

Elenco dei parametri

class_name

The name of the exported class.

args

These optional parameters will be passed to the default class constructor during object creation.

Valori restituiti

No value is returned.

Esempi

Esempio 1. Some examples

<?php

class foo {
    function foo() 
    {
    }
}
$server->setClass("foo");

class bar {
    function bar($x, $y) 
    {
    }
}
$server->setClass("bar", $arg1, $arg2);

?>

SoapServer->setPersistence()

(no version information, might be only in CVS)

SoapServer->setPersistence() --  Sets persistence mode of SoapServer

Descrizione

class SoapServer {

void setPersistence ( int mode )

}

This function allows saving data between requests in a PHP session. It works only with a server that exports functions from a class with SoapServer->setClass().

Elenco dei parametri

mode

One of the SOAP_PERSISTENCE_XXX constants.

Valori restituiti

No value is returned.

Esempi

Esempio 1. Some examples

<?php

$server->setPersistence(SOAP_PERSISTENCE_SESSION);

$server->setPersistence(SOAP_PERSISTENCE_REQUEST);

?>

SoapVar->__construct()

(no version information, might be only in CVS)

SoapVar->__construct() --  SoapVar constructor

Descrizione

class SoapVar {

__construct ( mixed data, int encoding [, string type_name [, string type_namespace [, string node_name [, string node_namespace]]]] )

}

Constructs a new SoapVar object.

Elenco dei parametri

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

Esempi

Esempio 1. Some examples

<?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f) 
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

use_soap_error_handler

(PHP 5)

use_soap_error_handler -- Set whether to use the SOAP error handler and return the former value

Descrizione

bool use_soap_error_handler ( [bool handler] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CXXXIX. Funzioni relative ai Socket

Introduzione

Questa estensione implementa una interfaccia a basso livello verso i socket, fornendo la possibilità di agire sia come server sia come client.

Per un esempio di una interfaccia generica lato client, vedere stream_socket_client(), stream_socket_server(), fsockopen() e pfsockopen().

Per l'utilizzo di queste funzioni, è importante ricordare che molte di esse hanno il medesimo nome della loro controparte in C, ma spesso hanno dichiarazioni differenti. Ricordarsi di leggere la descrizione per evitare confusione.

Per chi non ha familiarità con la programmazione dei socket, può trovare utili informazioni nelle pagine del manuale di Unix, ed inoltre sul web si può trovare diversi tutorial sulla programmazione dei socket in C, molti dei quali possono essere utilizzati, con lievi modifiche, nella programmazione dei socket in PHP. Il link Unix Socket FAQ può essere un buon punto di partenza.

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Le funzioni relative ai socket qui descritte sono parte di una estensione del PHP che occorre abilitare durante la fase di compila usando l'opzione --enable-sockets del comando configure.

Nota: Il supporto all'IPv6 è stato aggiunto in PHP 5.0.0.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

AF_UNIX (integer)

AF_INET (integer)

AF_INET6 (integer)

SOCK_STREAM (integer)

SOCK_DGRAM (integer)

SOCK_RAW (integer)

SOCK_SEQPACKET (integer)

SOCK_RDM (integer)

MSG_OOB (integer)

MSG_WAITALL (integer)

MSG_PEEK (integer)

MSG_DONTROUTE (integer)

SO_DEBUG (integer)

SO_REUSEADDR (integer)

SO_KEEPALIVE (integer)

SO_DONTROUTE (integer)

SO_LINGER (integer)

SO_BROADCAST (integer)

SO_OOBINLINE (integer)

SO_SNDBUF (integer)

SO_RCVBUF (integer)

SO_SNDLOWAT (integer)

SO_RCVLOWAT (integer)

SO_SNDTIMEO (integer)

SO_RCVTIMEO (integer)

SO_TYPE (integer)

SO_ERROR (integer)

SOL_SOCKET (integer)

PHP_NORMAL_READ (integer)

PHP_BINARY_READ (integer)

SOL_TCP (integer)

SOL_UDP (integer)


Errori dei socket

L'estensione dei socket è stata scritta per fornire una pratica interfaccia ai potenti socket BSD. Si noti che le funzioni girano correttamente sia su sistemi Unix sia su sistemi Win32. Quasi tutte le funzioni dei socket possono fallire in certe situazioni e quindi generare un messaggio di tipo E_WARNING per descrivere l'errore. Qualche volta ciò non accade secondo le aspettative dello sviluppatore. Ad esempio la funzione socket_read() improvvisamente può generare un messaggio di E_WARNING a causa di una interruzione inaspettata della connessione. E' prassi comune sopprimere i messaggi di warning con l'operatore @ ed intercettare il codice dell'errore utilizzando la funzione socket_last_error(). Si può anche richiamare la funzione socket_strerror() con questo codice di errore per avere un testo descrittivo del problema. Per maggiori dettagli vedere la descrizione delle funzioni.

Nota: I messaggi E_WARNING generati dal modulo dei socket sono in inglese, mentre i messaggi di errore recuperati dipendono dalle correnti impostazioni locali (LC_MESSAGES):
Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet


Esempi

Esempio 1. Esempio di programma con i socket: semplice server TCP/IP

Questo esempio illustra un semplice server. Occorre modificare le variabili address e port per adeguarle ai parametri della macchina su cui sarà eseguito. Ci si può connettere al server con un comando simile a telnet 192.168.1.53 10000 (dove l'indirizzo e la porta devono essere uguali a quanto indicato nel setup). Qualsiasi lettera sarà digitata, verrà visualizzata sul server e sul client. Per disconnettersi, digitare 'quit'.

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Si indica allo script di non uscire mentre attende una connessione */
set_time_limit(0);

/* Abilita lo scarico dell'output così si è in grado di vedere cosa passa
 * non appena arrivano i dati al server. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
    echo "socket_create() fallito: motivo: " . socket_strerror($sock) . "\n";
}

if (($ret = socket_bind($sock, $address, $port)) < 0) {
    echo "socket_bind() fallito: motivo: " . socket_strerror($ret) . "\n";
}

if (($ret = socket_listen($sock, 5)) < 0) {
    echo "socket_listen() fallito: motivo: " . socket_strerror($ret) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() fallito: motivo: " . socket_strerror ($msgsock) . "\n";
        break;
    }
    /* Invio delle istruzioni */
    $msg = "\nBenvenuti al server di test in PHP. \n" .
        "Per uscire, digitare 'quit'. Per chiudere il server digitare 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (FALSE === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() fallito: motivo: " . socket_strerror($ret) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: Testo scritto '$buf'.\n";
        socket_write($msgsock, $talkback, strlen $talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>

Esempio 2. Esempio di programma con i socket: semplice client TCP/IP

In questo esempio sarà illustrato un semplice client HTTP. Questo, molto semplicemente, si collega ad un server, invia una richiesta HEAD, visualizza la risposta ed esce.

<?php
error_reporting(E_ALL);

echo "<h2>Connessione TCP/IP </h2>\n";

/* Ottiene la porta per il servizio WWW. */
$service_port = getservbyname('www', 'tcp');

/* Ottiene l'indirizzo IP per il server cercato. */
$address = gethostbyname('www.php.net');

/* Crea un socket TCP/IP. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket_create() fallito: motivo: " . socket_strerror($socket) . "\n";
} else {
    echo "OK.\n";
}

echo "Tentativo di connessione a '$address' sulla porta '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result < 0) {
    echo "socket_connect() fallito.\nMotivo: ($result) " . socket_strerror($result) . "\n";
} else {
    echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n"; 
$in .= "Host: www.example.com\r\n"; 
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Invio HTTP HEAD...";
socket_write($socket, $in, strlen ($in));
echo "OK.\n";

echo "Lettura della risposta:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

echo "Chiusura del socket...";
socket_close($socket);
echo "OK.\n\n";
?>

Sommario
socket_accept -- Accetta una connessione su un socket
socket_bind -- Bind di un nome ad un socket
socket_clear_error -- Azzera gli erorri di un socket, oppure l'ultimo codice d'errore
socket_close -- Chiude una risorsa di tipo socket
socket_connect -- Inizia una connessione su un socket
socket_create_listen -- Apre un socket per accettare connessioni su una porta
socket_create_pair -- Crea una coppia di socket non distinguibili e li memorizza in una matrice
socket_create -- Crea un socket (punto terminale di una comunicazione).
socket_get_option -- Ottiene le opzioni per un socket
socket_getpeername --  Interroga il lato remoto di un dato socket per ottenere o la combinazione host/porta od un percorso Unix, in base al tipo di socket
socket_getsockname --  Interroga il lato locale di un dato socket e restituisce o la combinazione host/porta oppure un percorso Unix in base al tipo di socket
socket_last_error -- Restituisce l'ultimo errore su un socket.
socket_listen -- Attende una richiesta di connessione su un socket
socket_read -- Legge fino ad un massimo di byte predefiniti da un socket
socket_recv -- Riceve i dati da un socket collegato
socket_recvfrom -- Riceve i dati da un socket, che sia connesso o meno
socket_select --  Esegue la system call select() su un set di socket con un dato timeout
socket_send -- Invia i dati ad un socket collegato
socket_sendto -- Invia un messaggio ad un socket, a prescindere che sia connesso o meno
socket_set_block --  Sets blocking mode on a socket resource
socket_set_nonblock -- Attiva la modalità "nonblocking" per il descrittore di file fd
socket_set_option -- Valorizza le opzioni per un socket
socket_shutdown -- Chiude un socket in ricezione, in invio o in entrambi i sensi
socket_strerror -- Restituisce una stringa con la descrizione dell'errore.
socket_write -- Scrive su un socket.

socket_accept

(PHP 4 >= 4.1.0, PHP 5)

socket_accept -- Accetta una connessione su un socket

Descrizione

resource socket_accept ( resource socket )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Dopo la creazione del socket socket con socket_create(), l'assegnazione di un nome con socket_bind(), e averlo messo in attesa di connessione con socket_listen(), con questa funzione si inizia ad accettare le richieste di connessione su quel socket. Una volta avuta una connessione, la funzione restituisce un nuovo socket che può essere usato per la comunicazione. Se vi sono diverse richieste di connessioni pendenti verrà utilizzata la prima. Viceversa se non vi sono richieste in attesa, la funzione socket_accept() si blocca in attesa di una richiesta. Se il socket è stato configurato "non-blocking" con socket_set_blocking() o con socket_set_nonblock(), la funzione restituirà FALSE.

La risorsa socket restituita da socket_accept() non può essere utilizzata per acquisire nuove connesioni. Per questo scopo occorre continuare ad usare il socket originale, indicato in socket, che rimane aperto.

La funzione restistuisce una risorsa di tipo socket se ha successo, oppure FALSE se si verifica un errore. Il codice di errore può essere recuperato chiamando la funzione socket_last_error(). Questo codice può essere passato a socket_strerror() per ottenere una descrizione dell'errore.

Vedere anche socket_bind(), socket_connect(), socket_listen(), socket_create() e socket_strerror().

socket_bind

(PHP 4 >= 4.1.0, PHP 5)

socket_bind -- Bind di un nome ad un socket

Descrizione

bool socket_bind ( resource socket, string address [, int port] )

La funzione socket_bind() esegue il bind del nome passato in indirizzo sul socket indicato da socket,

Elenco dei parametri

socket

Una valida risorsa di tipo socket creata da socket_create().

address

Se il socket appartiene alla famiglia AF_INET, il parametro address è un classico indirizzo IP (ad esempio 127.0.0.1)

Se il socket appartiene alla famiglia AF_UNIX, il parametro address indica il percorso di un socket nel dominio Unix (ad esempio /tmp/my.sock).

port (Optional)

Il parametro port, si utilizza soltanto con le connessioni tramite un socket di tipo AF_INET, ed indica quale porta sul server remoto si debba utilizzare per eseguire la connessione.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Il codice di errore può essere recuperato con socket_last_error(). Questo codice può essere passato alla funzione socket_strerror() per ottenere una descrizione dell'errore.

Esempi

Esempio 1. Utilizzo di socket_bind() per impostare un indirizzo sorgente

<?php
// Crea il nuovo socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// Un esempio di elenco di IP del proprio computer
$sourceips['kevin']    = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';

// Bind degli indirizzi
socket_bind($sock, $sourceips['madcoder']);

// Connessione all'indirisso di destinazione
socket_connect($sock, '127.0.0.1', 80);

// Scrittura
$request = 'GET / HTTP/1.1' . "\r\n" .
           'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);

// Chiusura
socket_close($sock);

?>

Note

Nota: Questa funzione deve essere utilizzata sui socket prima di socket_connect().

Nota: Windows 9x/ME nota di compatibilità: socket_last_error() può restituire un codice di errore non valido se si tenta il bind del socket ad un indirizzo errato che non appartiene alla propria macchina.

socket_clear_error

(PHP 4 >= 4.2.0, PHP 5)

socket_clear_error -- Azzera gli erorri di un socket, oppure l'ultimo codice d'errore

Descrizione

void socket_clear_error ( [resource socket] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 azzera il codice d'errore di un dato socket, oppure azzera l'ultimo errore globale accaduto nei socket.

Questa funzione permette esplicitamente di azzerare il valore del codice di errore sia di un socket sia dell'ultimo codice di errore globale dell'estensione. Questo può essere utile per rilevare, all'interno di una parte di applicazione, se si è verificato un errore o meno.

Vedere anche socket_last_error() e socket_strerror().

socket_close

(PHP 4 >= 4.1.0, PHP 5)

socket_close -- Chiude una risorsa di tipo socket

Descrizione

void socket_close ( resource socket )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_close() chiude la risorsa socket indicata nel parametro socket.

Nota: La funzione socket_close() non può essere utilizzata con risorse di tipo file create con fopen(), popen(), fsockopen(), oppure pfsockopen(); essa è stata predisposta per i socket creati con socket_create() oppure socket_accept().

Vedere anche socket_bind(), socket_listen(), socket_create() e socket_strerror().

socket_connect

(PHP 4 >= 4.1.0, PHP 5)

socket_connect -- Inizia una connessione su un socket

Descrizione

bool socket_connect ( resource socket, string indirizzo [, int porta] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Apre una connessione usando la risorsa di tipo socket socket, la quale deve essere una risorsa di socket valida generata da socket_create().

Il parametro indirizzo può essere sia un classico indirizzo IP (ad esempio 127.0.0.1), se il socket appartiene alla famiglia AF_INET, sia il percorso di un socket nel dominio Unix, se il socket appartiene alla famiglia AF_UNIX.

Il parametro porta, utilizzato soltanto con le connessioni tramite un socket di tipo AF_INET, indica quale porta sul server remoto si debba utilizzare per eseguire la connessione.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Il codice di errore può essere recuperato con socket_last_error(). Questo codice può essere passato alla funzione socket_strerror() per ottenere una descrizione dell'errore.

Vedere anche socket_bind(), socket_listen(), socket_create(), socket_last_error() e socket_strerror().

socket_create_listen

(PHP 4 >= 4.1.0, PHP 5)

socket_create_listen -- Apre un socket per accettare connessioni su una porta

Descrizione

resource socket_create_listen ( int porta [, int backlog] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 è stata concepita per rendere semplice il compito di creare un nuovo socket che sia in attesa di nuove connessioni.

La funzione socket_create_listen() crea una nuova risorsa socket di tipo AF_INET in attesa su una data porta in tutte le interfacce locali di una nuova connessione.

Il parametro backlog indica la lunghezza massima della coda delle connessioni pendenti. Come valore per backlog, può essere passata la costante SOMAXCONN, vedere socket_listen() per maggiori dettagli.

socket_create_listen() restituisce una nuova risorsa di tipo socket se ha successo, oppure FALSE su errore. Il codice dell'errore può essere recuperato con la funzione socket_last_error(). Questo codice può essere passato alla funzione socket_strerror() per ottenere una descrizione dell'errore.

Nota: Se si desidera creare un socket che sia in attesa solo su certe interfacce, occorre utilizzare socket_create(), socket_bind() e socket_listen().

Vedere anche socket_create(), socket_bind(), socket_listen(), socket_last_error() e socket_strerror().

socket_create_pair

(PHP 4 >= 4.1.0, PHP 5)

socket_create_pair -- Crea una coppia di socket non distinguibili e li memorizza in una matrice

Descrizione

bool socket_create_pair ( int domain, int type, int protocol, array &fd )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_create_pair() crea due socket connessi ed indistinguibili e li memorizza in &fd. Questa funzione è comunemente utilizzate per l'IPC (InterProcess Communication, comunicazione tra processi).

Il parametro domain specifica la famiglia di protocolli da usare per il socket.

Tabella 1. Famiglie di indirizzi/protocolli disponibili

DominioDescrizione
AF_INET Protocollo Internet basato su IPv4. Il TCP e l'UDP sono i protocolli più comuni di questa famiglia. Supportati solo in Windows.
AF_INET6 Protocollo Internet basato su IPv6. Il TCP e l'UDP sono i protocolli più comuni di questa famiglia. Supportati solo in Windows. IPv6 Internet based protocols. Supporto aggiunto in PHP 5.0.0.
AF_UNIX Famiglia di protocolli per la comunicazione locale. Molto efficiente, basso overhead permettono un buon tipo di IPC (Interprocess Communication).

Il parametro type seleziona il tipo di comunicazione da utilizzare con il socket.

Tabella 2. Tipi di socket disponibili

TipoDescrizione
SOCK_STREAM Fornisce una connessione sequenziale, affidabile e full-duplex. Può essere supportato un meccanismo di trasmissione fuori-banda. Il protocollo TCP è basato su questo tipo di socket.
SOCK_DGRAM Supporta i datagrammi (privo di connessione, messaggi inaffidabili di una lunghezza massima prefissata). Il protocollo UDP è basato su questo tipo di socket.
SOCK_SEQPACKET Fornisce una trasmissione di dati sequenziale, affidabile, bi-direzionale per i datagrammi di lunghezza massima prefissata; all'utilizzatore è richiesto di leggere l'intero pacchetto in ogni esecuzione della funzione di lettura dal socket.
SOCK_RAW Fornisce un'accesso raw al protocollo di rete. Questo tipo di socket può essere utilizzato per costruire manualmente qualsiasi tipo di protocollo. Un comune utilizzo di questa tipologia di socket è la realizzazione di richieste ICMP (tipo il ping o traceroute).
SOCK_RDM Fornisce un'interfaccia affidabile per i datagrammi ma non ne garantisce l'ordine. Probabilmente questo non è implementato nel vostro sistema operativo.

Il parametro protocol indica lo specifico protocollo nel domain indicato da usarsi con il socket restituito. Il valore opportuno può essere recuperato utilizzando getprotobyname(). Se il protocollo desiderato è il TCP o l'UDP, si possono utilizzare le corrispondenti costanti SOL_UDP e SOL_TCP.

Tabella 3. Protocolli comuni

NomeDescrizione
icmp L'Internet Control Message Protocol viene utilizzato principalmente dai gateway e dagli host per riportare errori nelle comunicazioni con datagrammi. Il comando "ping" (presente in quasi tutti i moderni sistemi operativi) è un esempio dell'applicazione di ICMP.
udp Lo User Datagram Protocol è un protocollo privo di connessione, inaffidabile con record di lunghezza fissa. Per questo l'UDP richiede poco overhead di protocollo.
tcp Il Transmission Control Protocol è un procotollo affidabile, basato sulla connessione, orientato al flusso, full duplex. Il TCP garantisce che tutti i pacchetti siano ricevuti nel medesimo ordine in cui siano stati inviati. Se un pacchetto viene perso durante la trasmissione, il TCP provvederà automaticamente alla ritrasmissione fino a quando l'host remoto non conferma la ricezione dello stesso. Per ragioni di affidabilità e di prestazioni, è il TCP stesso a decidere l'appropriata dimensione dei pacchetti del sottostante livello di datagrammi. Pertanto le applicazioni TCP devono permettere la parziale ritrasmissione di un record.

Esempio 1. Esempio di uso di socket_create_pair()

<?php 
$sockets = array(); 
$uniqid = uniqid(''); 
if (file_exists("/tmp/$uniqid.sock")) { 
    die('Temporary socket already exists.'); 
} 
/* Setup socket pair */ 
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets)) { 
    echo socket_strerror(socket_last_error()); 
} 
/* Send and Recieve Data */ 
if (!socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n"))) { 
    echo socket_strerror(socket_last_error()); 
} 
if (!$data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) { 
    echo socket_strerror(socket_last_error()); 
} 
var_dump($data); 
 
/* Close sockets */ 
socket_close($sockets[0]); 
socket_close($sockets[1]); 
?>

Esempio 2. Esempio di IPC con socket_create_pair()

<?php 
$ary = array(); 
$strone = 'Message From Parent.'; 
$strtwo = 'Message From Child.'; 
if (!socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary)) { 
    echo socket_strerror(socket_last_error()); 
} 
$pid = pcntl_fork(); 
if ($pid == -1) { 
    echo 'Could not fork Process.'; 
} elseif ($pid) { 
    /*parent*/ 
    socket_close($ary[0]); 
    if (!socket_write($ary[1], $strone, strlen($strone))) { 
            echo socket_strerror(socket_last_error()); 
    } 
    if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) { 
        echo "Recieved $strtwo\n"; 
    } 
    socket_close($ary[1]);
} else { 
    /*child*/ 
    socket_close($ary[1]); 
    if (!socket_write($ary[0], $strtwo, strlen($strtwo))) { 
        echo socket_strerror(socket_last_error()); 
    } 
    if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) { 
        echo "Recieved $strone\n"; 
    } 
    socket_close($ary[0]);
} 
?>

socket_create

(PHP 4 >= 4.1.0, PHP 5)

socket_create -- Crea un socket (punto terminale di una comunicazione).

Descrizione

resource socket_create ( int dominio, int tipo, int protocollo )

La funzione crea un punto terminale di una comunicazione (un socket) e restituisce una risorsa di tipo socket. In una tipica connessione di rete si hanno 2 sockets, uno con il ruolo di client e l'altro con il ruolo di server.

Il parametro dominio indica il dominio (famiglia di protocolli da usarsi per la comunicazione tra i sockets).

Tabella 1. Famiglie di indirizzi/protocolli disponibili

DominioDescrizione
AF_INET Protocollo Internet basato su IPv4. TCP e UDP sono i protocolli più comuni di questa famiglia.
AF_INET6 Protocolli basati su IPv6. TCP ed UDP sono i protocolli più comuni di questa famiglia. Il supporto a questa famiglia è stato aggiunto in PHP 5.0.0.
AF_UNIX Famiglia di protocolli per le comunicazioni locali. L'alta efficenza ed il basso overhead ne fanno una buona forma di IPC (comunicazione inter-processo).

Il parametro tipo indica il tipo di comunicazione da usare con il socket.

Tabella 2. Tipi di socket disponibili

TipoDescrizione
SOCK_STREAM Fornisce una connessione sequenziale, affidabile e full-duplex. Può essere supportato un meccanismo di trasmissione fuori-banda. Il protocollo TCP è basato su questo tipo di socket.
SOCK_DGRAM Supporta i datagrammi (privo di connessione, messaggi inaffidabili di una lunghezza massima prefissata). Il protocollo UDP è basato su questo tipo di socket.
SOCK_SEQPACKET Fornisce una trasmissione di dati sequenziale, affidabile, bi-direzionale per i datagrammi di lunghezza massima prefissata; all'utilizzatore è richiesto di leggere l'intero pacchetto in ogni esecuzione della funzione di lettura dal socket.
SOCK_RAW Fornisce un'accesso raw al protocollo di rete. Questo tipo di socket può essere utilizzato per costruire manualmente qualsiasi tipo di protocollo. Un comune utilizzo di questa tipologia di socket è la realizzazione di richieste ICMP (tipo il ping o traceroute).
SOCK_RDM Fornisce un'interfaccia affidabile per i datagrammi ma non ne garantisce l'ordine. Probabilmente questo non è implementato nel vostro sistema operativo.

Il parametro protocollo indica lo specifico protocollo nel dominio indicato da usarsi con il socket restituito. Il valore opportuno può essere recuperato utilizzando getprotobyname(). Se il protocollo desiderato è il TCP o l'UDP, si possono utilizzare le corrispondenti costanti SOL_UDP e SOL_TCP.

Tabella 3. Protocolli comuni

NomeDescrizione
icmp L'Internet Control Message Protocol viene utilizzato principalmente dai gateway e dagli host per riportare errori nelle comunicazioni con datagrammi. Il comando "ping" (presente in quasi tutti i moderni sistemi operativi) è un esempio dell'applicazione di ICMP.
udp Lo User Datagram Protocol è un protocollo privo di connessione, inaffidabile con record di lunghezza fissa. Per questo l'UDP richiede poco overhead di protocollo.
tcp Il Transmission Control Protocol è un procotollo affidabile, basato sulla connessione, orientato al flusso, full duplex. Il TCP garantisce che tutti i pacchetti siano ricevuti nel medesimo ordine in cui siano stati inviati. Se un pacchetto viene perso durante la trasmissione, il TCP provvederà automaticamente alla ritrasmissione fino a quando l'host remoto non conferma la ricezione dello stesso. Per ragioni di affidabilità e di prestazioni, è il TCP stesso a decidere l'appropriata dimensione dei pacchetti del sottostante livello di datagrammi. Pertanto le applicazioni TCP devono permettere la parziale ritrasmissione di un record.

La funzione restituisce una risorsa di tipo socket se ha successo, oppure FALSE in caso di errore. In quest'ultimo caso si può ottenere il codice di errore tramite socket_last_error(). Tale codice può essere passato alla funzione socket_strerror() per ottenere una descrizione dell'errore.

Nota: Se si forniscono valori non validi per dominio o tipo, la funzione socket_create() imposta i parametri rispettivamente a AF_INET e SOCK_STREAM ed emette un messaggio di tipo E_WARNING.

Vedere anche socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error() e socket_strerror().

socket_get_option

(PHP 4 >= 4.3.0, PHP 5)

socket_get_option -- Ottiene le opzioni per un socket

Descrizione

mixed socket_get_option ( resource socket, int level, int optname )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_get_option() restituisce i valori per il parametro indicato in optname per il socket indicato da socket. La funzione restituisce FALSE se non riesce.

Il parametro level specifica a quale livello di protocollo risiede l'opzione cercata. Ad esempio, per recuperare le informzioni su opzioni a livello di socket, il parametro level deve essere impostato a SOL_SOCKET. Altri livelli tipo TCP, possono essere utilizzati specificando il numero del livello. I numeri dei livelli dei protocolli possono essere ottenuti tramite getprotobyname().

Tabella 1. Opzioni per i socket disponibili

OpzioneDescrizione
SO_DEBUG Riporta informazioni per il debug.
SO_ACCEPTCONN Indica se il socket è abilitato in ascolto.
SO_BROADCAST Indica se sono supportate le trasmissioni dei messaggi di broadcast.
SO_REUSEADDR Riporta se gli indirizzi locali possono essere riutilizzati.
SO_KEEPALIVE Riporta se la connesisone deve essere mantenuta attiva tramite la trasmissione periodica di messaggi. Se il socket connesso non risponde a questi messaggi, la connessione viene interrotta ed i processi che stavano scrivendo in quel socket riceveranno il segnale SIGPIPE.
SO_LINGER Indice se il socket debba ritardare il socket_close() se vi sono dati.
SO_OOBINLINE Indica se il socket gestisce i dati fuori-banda.
SO_SNDBUF Riporta le dimensioni del buffer di trasmissione.
SO_RCVBUF Riporta le dimensioni del buffer di ricezione.
SO_ERROR Restituisce informaizoni sugli stati di errore e li ripulisce.
SO_TYPE Restituisce il tipo disocket.
SO_DONTROUTE Indica se i messaggi in uscita ignorano i parametri standard di routing.
SO_RCVLOWAT Indica il numero minimo di byte da processare da parte del socket per le operazioni di input (default 1).
SO_RCVTIMEO Tempo di timeout per le operazioni di input.
SO_SNDLOWAT Riporta il numero minimo di byte da processare da parte del socket per le operazioni di output.
SO_SNDTIMEO Indica il tempo di timeout specificando il tempo che una funzione di output resti bloccata in attesa di potere inviare i dati.

Nota: Nelle versioni di PHP antecedenti la 4.3.0, questa funzione era chiamata socket_getopt().

socket_getpeername

(PHP 4 >= 4.1.0, PHP 5)

socket_getpeername --  Interroga il lato remoto di un dato socket per ottenere o la combinazione host/porta od un percorso Unix, in base al tipo di socket

Descrizione

bool socket_getpeername ( resource socket, string &indirizzo [, int &porta] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Se il socket dato è di tipo AF_INET oppure AF_INET6, socket_getpeername() restituisce l'indirizzo IP remoto nella notazione appropriata (ad esempio 127.0.0.1 oppure fe80::1) nel parametro indirizzo e, se presente il parametro opzionale porta, anche la porta associata.

Se il socket dato è di tipo AF_UNIX, socket_getpeername() restituirà un percorso Unix (ad esempio /var/run/daemon.sock) nel parametro indirizzo.

Nota: La funzione socket_getpeername() non dovrebbe essere usata con socket AF_UNIX creati da socket_accept(). Soltanto i socket creati con socket_connect() o un socket server primario conseguente alla chiamata di socket_bind() restituirà dei valori significativi.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. socket_getpeername() può anche restituire FALSE se il tipo di socket non è AF_INET, AF_INET6 o AF_UNIX, in questo caso l'ultimo codice di errore del socket non viene aggiornato.

Vedere anche socket_getsockname(), socket_last_error() e socket_strerror().

socket_getsockname

(PHP 4 >= 4.1.0, PHP 5)

socket_getsockname --  Interroga il lato locale di un dato socket e restituisce o la combinazione host/porta oppure un percorso Unix in base al tipo di socket

Descrizione

bool socket_getsockname ( resource socket, string &indirizzo [, int &porta] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Se il socket dato è di tipo AF_INET oppure AF_INET6, socket_getsockname() restituisce l'indirizzo IP locale nella notazione appropriata (ad esempio 127.0.0.1 oppure fe80::1) nel parametro indirizzo e, se presente il parametro opzionale porta, anche la porta associata.

Se il socket dato è di tipo AF_UNIX, socket_getsockname() restituirà un percorso Unix (ad esempio /var/run/daemon.sock) nel parametro indirizzo.

Nota: La funzione socket_getsockname() non dovrebbe essere usata con socket AF_UNIX creati da socket_accept(). Soltanto i socket creati con socket_connect() o un socket server primario conseguente alla chiamata di socket_bind() restituirà dei valori significativi.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. socket_getsockname() può anche restituire FALSE se il tipo di socket non è AF_INET, AF_INET6 o AF_UNIX, in questo caso l'ultimo codice di errore del socket non viene aggiornato.

Vedere anche socket_getpeername(), socket_last_error() e socket_strerror().

socket_last_error

(PHP 4 >= 4.1.0, PHP 5)

socket_last_error -- Restituisce l'ultimo errore su un socket.

Descrizione

int socket_last_error ( [resource socket] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 restituisce il codice di errore di un socket.

Se a questa funzione si passa una risorsa di tipo socket, essa restituisce l'ultimo errore occorso in quel socket. Se, al contrario, si omette di indicare il socket, verrà restituito l'ultimo errore generato dalle funzioni dei socket. Il secondo caso è particolarmente utile per funzioni tipo socket_create(), che in caso di errore non restituiscono un socket, o socket_select(), che possono fallire per ragioni non direttamente collegate ad un particolare socket. Il codice di errore è utilizzabile dalla funzione socket_strerror() per ottenere un testo con la spiegazione del codice di errore dato.
<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { 
    die("Non si riesce a creare il socket, codice di errore: " . socket_last_error() . 
        ",descrizione: " . socket_strerror(socket_last_error())); 
} 
?>

Nota: socket_last_error() non rimuove il codice di errore, utilizzare socket_clear_error() per questo scopo.

socket_listen

(PHP 4 >= 4.1.0, PHP 5)

socket_listen -- Attende una richiesta di connessione su un socket

Descrizione

bool socket_listen ( resource socket [, int backlog] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Una volta creato il socket socket tramite la funzione socket_create(), ed eseguito il bind ad un nome con socket_bind(), lo si può mettere in ascolto di eventuali richieste di connessione su socket.

Nota: Il numero massimo, passato con il parametro backlog dipende fortemente dalla piattaforma sottostante. Su Linux questo viene troncato, senza avvisare, a SOMAXCONN. Su Win32, se viene passata la costante SOMAXCONN, il servizio sottostante responsabile dei socket valorizza backlog al massimo valore ragionevole. Non esiste un metodo standard per determinare il reale valore massimo su questa piattaforma.

La funzione socket_listen() è disponibile solo per i socket di tipo SOCK_STREAM o SOCK_SEQPACKET.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Il codice di errore può essere recuperato con socket_last_error(). Questo codice può essere passato a socket_strerror() per ottenere una spiegazione dell'errore.

Vedere anche socket_accept(), socket_bind(), socket_connect(), socket_create() e socket_strerror().

socket_read

(PHP 4 >= 4.1.0, PHP 5)

socket_read -- Legge fino ad un massimo di byte predefiniti da un socket

Descrizione

string socket_read ( resource socket, int lunghezza [, int tipo] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_read() legge un numero massimo di byte, indicato in lunghezza, da un socket socket creato dalla funzione socket_accept() oppure da socket_create(). In alternativa si possono usare i caratteri \n, \r o \0 per indicare la fine della lettura (in base al parametro tipo, vedere più avanti)

La funzione restituisce i dati come una stringa in caso di successo, FALSE su errore. Il codice di errore può essere recuperato con socket_last_error(). Questo codice può essere passato a socket_strerror() per ottenere una descrizione dell'errore.

Nota: socket_read() può restituire una stringa di lunghezza zero ("") indicante la fine della comunicazione (ad esempio il server remoto ha chiuso la connessione).

Il parametro opzionale tipo può assumere i seguenti valori:

  • PHP_BINARY_READ - usa la funzione di sistema read(). Salvaguarda la lettura di dati binari (Default in PHP >= 4.1.0)

  • PHP_NORMAL_READ - ferma la lettura in presenza di \n oppure \r. (Default in PHP <= 4.0.6)

Vedere anche socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), socket_strerror() e socket_write().

socket_recv

(PHP 4 >= 4.1.0, PHP 5)

socket_recv -- Riceve i dati da un socket collegato

Descrizione

int socket_recv ( resource socket, string &buf, int len, int flags )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5)

socket_recvfrom -- Riceve i dati da un socket, che sia connesso o meno

Descrizione

int socket_recvfrom ( resource socket, string &buf, int len, int flags, string &name [, int &port] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

La funzione socket_recvfrom() gestisce i dati binari dal PHP 4.3.0

socket_select

(PHP 4 >= 4.1.0, PHP 5)

socket_select --  Esegue la system call select() su un set di socket con un dato timeout

Descrizione

int socket_select ( array lettura, array scrittura, array except, int tv_sec [, int tv_usec] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_select() accetta un array di socket e si mette in attesa di una variazione di stato su questi. Questa, derivando come background dai socket BSD, riconoscerà che questi array di risorse socket sono in realtà dei set di descrittori di file. Saranno monitorati 3 set di socket.

I socket indicati nell'array lettura, saranno monitorati in attesa dell'arrivo di caratteri disponibili per la lettura (più precisamente, per verificare che una lettura non sia bloccata, una risorsa socket viene definita pronta anche su fine file, in questo caso la funzione socket_read() restituirà una stringa di lunghezza zero).

I socket indicati nell'array di scrittura, sarranno monitorati per verificare che una scrittura non si blocchi.

I socket indicati nell'array except saranno monitorati per rilevare delle eccezioni.

Avvertimento

In uscita, gli array sarrano modificati in modo da indicare quale risorsa di tipo socket ha variato il proprio stato.

Non si è obbligati a passare tutti gli array a socket_select(). Se ne possono tralasciare, al loro posto utilizzare un array vuoto oppure NULL. Inoltre non si dimentichi che gli array sono passati per riferimento e che saranno modificati all'uscita dalla funzione socket_select().

Esempio 1. Esempio di socket_select()

<?php
/* Preparo l'array di lettura */  
$read = array($socket1, $socket2);  
  
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0);


if ($num_changed_sockets === false) {
    /* Gestione dell'errore */  
} else if ($num_changed_sockets > 0) {
    /* Su almeno un socket è accaduto qualcosa di interessante */  
}  
?>

Nota: A causa delle limitazioni della versione attuale del Zend Engine, non è possibile passare direttamente una costante, ad esempio NULL, come parametro ad una funzione che si aspetti questo passato per riferimento. Si utilizzi, invece, una variabile temporanea oppura una espressione il cui membro di sinistra sia una variabile temporanea:

Esempio 2. Uso di NULL con socket_select()

<?php
socket_select($r, $w, $e = NULL, 0);  
?>

I parametri tv_sec ed tv_usec insieme indicano il timeout. Il timeout indica il limite superiore di tempo che deve trascorrere prima che la funzione socket_select() esca. tv_sec può essere a zero, ciò causa una uscita immediata di socket_select(). Ciò risulta utile nei casi di polling. Se tv_sec viene impostato a NULL (nessun timeout), la funzione resta in attesa per un tempo indefinito.

Se ha successo socket_select() restituisce il numero di risorse socket contenute nell'array modificato, tale valore può essere zero se scade il timeout prima che sia accaduto qualcosa. La funzione restituisce FALSE se si verifica un errore. Il codice di errore può essere recuperato tramite la funzione socket_last_error().

Nota: Si utilizzi l'operatore === quanto si eseguono dei test per rilevare un errore. Poichè la funzione socket_select() può restituire 0 il confronto eseguito con == sarebbe valutato come TRUE:

Esempio 3. Comprensione dei risultati di socket_select()

<?php
if (false === socket_select($r, $w, $e = NULL, 0)) {  
    echo "socket_select() failed, reason: " . socket_strerror(socket_last_error()) . "\n";  
}  
?>

Nota: Si presti attenzione alle implementazioni di certi socket che richiedono di essere gestiti molto attentamente. Alcune regole di base:

  • Si cerchi di utilizzare sempre socket_select() senza il timeout. Il programma non dovrebbe avere nulla da fare se non ci sono dati disponibili. Il codice basato sui timeout solitamente non è migrabile ed è difficile da testare.

  • Nei tre set, non inserire una risorsa socket di cui non si intende controllarne il risultato dopo la chiamata a socket_select(), e ne si intende rispondere in modo appropriato. Dopo la chiamata a socket_select(), occorre verificare tutti i socket in tutti gli array. Si deve scrivere su qualsiasi socket disponibile per la scrittura, e deve essere letto qualsiasi socket diponibile per la lettura.

  • Se si ha il ritorno della disponibilità di un socket, sia in lettura che in scrittura, non è detto che sia disponile per l'intero ammontare dei dati da scrivere/leggere. Occorre essere preparati a gestire il caso in cui la disponibilità sia limitata anche ad un solo byte.

  • Nella maggior parte delle implementazioni dei socket, l'unica eccezione catturata con il parametro except è l'arrivo di dati fuori banda.

Vedere anche socket_read(), socket_write(), socket_last_error() e socket_strerror().

socket_send

(PHP 4 >= 4.1.0, PHP 5)

socket_send -- Invia i dati ad un socket collegato

Descrizione

int socket_send ( resource socket, string buf, int len, int flags )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_send() invia len bytes nel socket indicato da socket dal buffer buf

I valori di flags può essere una qualsiasi combinazione OR dei seguenti:

Tabella 1. valori possibili per flags

0x1 Tratta dati OOB (fuori banda)
0x2 Preleva il messaggio
0x4 Ignora il routing, usa l'interfaccia diretta
0x8 I dati comletano il record
0x100 I dati completano la transazione

Vedere anche socket_sendmsg() e socket_sendto().

socket_sendto

(PHP 4 >= 4.1.0, PHP 5)

socket_sendto -- Invia un messaggio ad un socket, a prescindere che sia connesso o meno

Descrizione

int socket_sendto ( resource socket, string buf, int len, int flags, string addr [, int port] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_sendto() invia len bytes dal buffer buf attraverso il socket socket alla porta port dell'indirizzo addr

Il valore ammessi per flags può essere uno dei seguenti:

Tabella 1. valori possibili per flags

0x1 Elabora dati OOB (fuori banda).
0x2 Preleva il messaggio in arrivo.
0x4 Ignora il routing, usa l'interfaccia diretta.
0x8 I dati completano il record.
0x100 I dati completano al transazione.

Esempio 1. Esempio di socket_sendto()

<?php
    $sh = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (socket_bind($sh, '127.0.0.1', 4242)) {
        echo "Socket agganciato correttamente";
    }
    $buf = 'Test Message';
    $len = strlen($buf);
    if (socket_sendto($sh, $buf, $len, 0x100, '192.168.0.2', 4242) !== false) {
        echo "Messaggio inviato correttamente";
    }
    socket_close($sh);
?>

Vedere anche socket_send() e socket_sendmsg().

socket_set_block

(PHP 4 >= 4.2.0, PHP 5)

socket_set_block --  Sets blocking mode on a socket resource

Description

bool socket_set_block ( resource socket )

The socket_set_block() function removes the O_NONBLOCK flag on the socket specified by the socket parameter.

Esempio 1. socket_set_block() example

<?php

$port = 9090;
if (!$socket = socket_create_listen($port)) {
    echo socket_strerror(socket_last_error());
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error());
}

if (!socket_set_nonblock($socket)) { // $socket is now nonblocking
    echo socket_strerror(socket_last_error());
}

if (!socket_set_block($socket)) {     // $socket is now blocking
    echo socket_strerror(socket_last_error());
}

?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also socket_set_nonblock() and socket_set_option()

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5)

socket_set_nonblock -- Attiva la modalità "nonblocking" per il descrittore di file fd

Descrizione

bool socket_set_nonblock ( resource socket )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_set_nonblock() imposta il flag O_NONBLOCK per il socket indicato dal parametro socket.

Esempio 1. Esempio di uso di socket_set_nonblock()

<?php 
$port = 9090; 
if (!$socket = socket_create_listen($port)) { 
    echo socket_strerror(socket_last_error()); 
} 
 
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { 
    echo socket_strerror(socket_last_error()); 
} 
 
if (!socket_set_nonblock($socket)) { 
    echo socket_strerror(socket_last_error()); 
} 
?>

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche socket_set_block() e socket_set_option()

socket_set_option

(PHP 4 >= 4.3.0, PHP 5)

socket_set_option -- Valorizza le opzioni per un socket

Descrizione

bool socket_set_option ( resource socket, int level, int optname, mixed optval )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_set_option() imposta l'opzione specificata dal parametro optname, per il livello di protocollo indicato da level sul socket indicato da socket, al valore indicato dal parametro optval. La funzione socket_set_option() restituisce FALSE se si verifica un errore.

Il parametro level indica il livello di protocollo nel quale si trova l'opzione. Ad esempio, per ageire sulle opzioni a livello di socket, occorre impostare il parametro level a SOL_SOCKET. Si possono utlizzare livelli, tipo TCP, semplicemente impostando il valore di protocollo nel parametro level. I valori previsti possono essere recuperati tramite la funzione getprotobyname().

Le oopzioni disponibili per i socket sono le medesime indicate per la funzione socket_get_option().

Nota: Nelle versioni di PHP antecedenti la 4.3.0, questa funzione era chiamata socket_setopt().

socket_shutdown

(PHP 4 >= 4.1.0, PHP 5)

socket_shutdown -- Chiude un socket in ricezione, in invio o in entrambi i sensi

Descrizione

bool socket_shutdown ( resource socket [, int how] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_shutdown() permette di chiudere i trasferimenti in ingresso, in uscita o in entrambe le direzione per il socket

I valori previsti per how sono i seguenti:

Tabella 1. possible values for how

0 Chiude il socket in lettura.
1 Chiude il socket in scrittura.
2 Chiude il socket in lettura e scrittura.

socket_strerror

(PHP 4 >= 4.1.0, PHP 5)

socket_strerror -- Restituisce una stringa con la descrizione dell'errore.

Descrizione

string socket_strerror ( int 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.

La funzione socket_strerror() utilizza come proprio parametro errno il codice di errore di un socket fornito da socket_last_error() e restituisce il corrispondente testo descrittivo. Questo rende più semplice piegare cosa è accaduto quando qualcosa non funziona; ad esempio, invece di dovere cercare in tutto il sistema un file che contenga la spiegazione di '-111', si può semplicemente passare il valore a socket_strerror(), e ottenere la spiegazione di ciò che è accaduto.

Esempio 1. Esempio di uso di socket_strerror()

<?php
if (false == ($socket = @socket_create (AF_INET, SOCK_STREAM,  SOL_TCP))) {
   echo "socket_create() fallito: motivo: " . socket_strerror (socket_last_error()) . "\n";
} 

if (false == (@socket_bind ($socket, '127.0.0.1', 80))) {
   echo "socket_bind() fallito: motivo: " . socket_strerror (socket_last_error($socket)) . "\n";
}
?>

Dall'esempio precedente (se non viene eseguito con i privilegi di root) ci si aspetta il seguente messaggio:
socket_bind() fallito: motivo: Permission denied

Vedere anche socket_accept(), socket_bind(), socket_connect(), socket_listen() e socket_create().

socket_write

(PHP 4 >= 4.1.0, PHP 5)

socket_write -- Scrive su un socket.

Descrizione

int socket_write ( resource socket, string buffer [, int lunghezza] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 socket_write() scrive sul socket socket i dati tratti dal campo buffer.

Il parametro opzionale lunghezza può specificare un numero alternativo di bytes da scrivere nel socket. Se questa dimensione è maggiore della lunghezza di buffer, questa viene, in modo silenzioso, ridotta alla lunghezza di buffer.

La funzione restituisce il numero di bytes scritti con successo nel socket, oppure FALSE se si verifica un errore. Il codice di errore può essere rilevato con socket_last_error(). Passando questo codice alla funzione socket_strerror() si ottiene una spiegazione dell'errore.

Nota: socket_write() non scrive necessariamente tutti i byte da un dato buffer. E' ammesso che, in base alle dimensioni dei buffer della rete ecc., soltanto un certo ammontare di dati, anche un solo byte, sia scritto nel socket, nonostante il buffer sia di dimensioni maggiori. Si deve prestare attenzione a ciò per evitare di non inviare il resto dei dati.

Nota: E' regolare per la funzione socket_write() restituire zero, ciò significa che non è stato scritto alcun byte. Si utilizzi l'operatore === per testare il caso di FALSE nelle situazioni di errore.

Vedere anche socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_read() e socket_strerror().

CXL. Standard PHP Library (SPL) Functions

Introduzione

SPL is a collection of interfaces and classes that are meant to solve standard problems.

Suggerimento: A more detailed documentation of SPL can be found here.


Installazione

This extension is available and compiled by default in PHP 5.


Costanti predefinite

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.

RIT_LEAVES_ONLY (integer)

RIT_SELF_FIRST (integer)

RIT_CHILD_FIRST (integer)

CIT_CALL_TOSTRING (integer)

CIT_CATCH_GET_CHILD (integer)

Sommario
ArrayIterator::current --  Return current array entry
ArrayIterator::key --  Return current array key
ArrayIterator::next --  Move to next entry
ArrayIterator::rewind --  Rewind array back to the start
ArrayIterator::seek --  Seek to position
ArrayIterator::valid --  Check whether array contains more entries
ArrayObject::append --  Appends the value
ArrayObject::__construct --  Construct a new array object
ArrayObject::count --  Return the number of elements in the Iterator
ArrayObject::getIterator --  Create a new iterator from an ArrayObject instance
ArrayObject::offsetExists --  Returns whether the requested $index exists
ArrayObject::offsetGet --  Returns the value at the specified $index
ArrayObject::offsetSet --  Sets the value at the specified $index to $newval
ArrayObject::offsetUnset --  Unsets the value at the specified $index
CachingIterator::hasNext --  Check whether the inner iterator has a valid next element
CachingIterator::next --  Move the iterator forward
CachingIterator::rewind --  Rewind the iterator
CachingIterator::__toString --  Return the string representation of the current element
CachingIterator::valid --  Check whether the current element is valid
CachingRecursiveIterator::getChildren --  Return the inner iterator's children as a CachingRecursiveIterator
CachingRecursiveIterator::hasChildren --  Check whether the current element of the inner iterator has children
DirectoryIterator::__construct --  Constructs a new dir iterator from a path
DirectoryIterator::current --  Return this (needed for Iterator interface)
DirectoryIterator::getATime --  Get last access time of file
DirectoryIterator::getCTime --  Get inode modification time of file
DirectoryIterator::getChildren --  Returns an iterator for the current entry if it is a directory
DirectoryIterator::getFilename --  Return filename of current dir entry
DirectoryIterator::getGroup --  Get file group
DirectoryIterator::getInode --  Get file inode
DirectoryIterator::getMTime --  Get last modification time of file
DirectoryIterator::getOwner --  Get file owner
DirectoryIterator::getPath --  Return directory path
DirectoryIterator::getPathname --  Return path and filename of current dir entry
DirectoryIterator::getPerms --  Get file permissions
DirectoryIterator::getSize --  Get file size
DirectoryIterator::getType --  Get file type
DirectoryIterator::isDir --  Returns true if file is directory
DirectoryIterator::isDot --  Returns true if current entry is '.' or '..'
DirectoryIterator::isExecutable --  Returns true if file is executable
DirectoryIterator::isFile --  Returns true if file is a regular file
DirectoryIterator::isLink --  Returns true if file is symbolic link
DirectoryIterator::isReadable --  Returns true if file can be read
DirectoryIterator::isWritable --  Returns true if file can be written
DirectoryIterator::key --  Return current dir entry
DirectoryIterator::next --  Move to next entry
DirectoryIterator::rewind --  Rewind dir back to the start
DirectoryIterator::valid --  Check whether dir contains more entries
FilterIterator::current --  Get the current element value
FilterIterator::getInnerIterator --  Get the inner iterator
FilterIterator::key --  Get the current key
FilterIterator::next --  Move the iterator forward
FilterIterator::rewind --  Rewind the iterator
FilterIterator::valid --  Check whether the current element is valid
LimitIterator::getPosition --  Return the current position
LimitIterator::next --  Move the iterator forward
LimitIterator::rewind --  Rewind the iterator to the specified starting offset
LimitIterator::seek --  Seek to the given position
LimitIterator::valid --  Check whether the current element is valid
ParentIterator::getChildren --  Return the inner iterator's children contained in a ParentIterator
ParentIterator::hasChildren --  Check whether the inner iterator's current element has children
ParentIterator::next --  Move the iterator forward
ParentIterator::rewind --  Rewind the iterator
RecursiveDirectoryIterator::getChildren --  Returns an iterator for the current entry if it is a directory
RecursiveDirectoryIterator::hasChildren --  Returns whether current entry is a directory and not '.' or '..'
RecursiveDirectoryIterator::key --  Return path and filename of current dir entry
RecursiveDirectoryIterator::next --  Move to next entry
RecursiveDirectoryIterator::rewind --  Rewind dir back to the start
RecursiveIteratorIterator::current --  Access the current element value
RecursiveIteratorIterator::getDepth --  Get the current depth of the recursive iteration
RecursiveIteratorIterator::getSubIterator --  The current active sub iterator
RecursiveIteratorIterator::key --  Access the current key
RecursiveIteratorIterator::next --  Move forward to the next element
RecursiveIteratorIterator::rewind --  Rewind the iterator to the first element of the top level inner iterator
RecursiveIteratorIterator::valid --  Check whether the current position is valid
SimpleXMLIterator::current --  Return current SimpleXML entry
SimpleXMLIterator::getChildren --  Returns an iterator for the current entry if it is a SimpleXML object
SimpleXMLIterator::hasChildren --  Returns whether current entry is a SimpleXML object
SimpleXMLIterator::key --  Return current SimpleXML key
SimpleXMLIterator::next --  Move to next entry
SimpleXMLIterator::rewind --  Rewind SimpleXML back to the start
SimpleXMLIterator::valid --  Check whether SimpleXML contains more entries
class_implements --  Return the interfaces which are implemented by the given class
class_parents --  Return the parent classes of the given class
iterator_count --  Count the elements in an iterator
iterator_to_array --  Copy the iterator into an array
spl_classes --  Return available SPL classes

ArrayIterator::current

(no version information, might be only in CVS)

ArrayIterator::current --  Return current array entry

Description

mixed ArrayIterator::current ( void )

This function returns the current array entry

Esempio 1. ArrayIterator::current() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

for($iterator = $arrayobject->getIterator();
    $iterator->valid();
    $iterator->next()) {

    echo $iterator->key() . ' => ' . $iterator->current() . "\n";
}
?>

Il precedente esempio visualizzerà:

1 => one
2 => two
3 => three

ArrayIterator::key

(no version information, might be only in CVS)

ArrayIterator::key --  Return current array key

Description

mixed ArrayIterator::key ( void )

This function returns the current array key

Esempio 1. ArrayIterator::key() example

<?php
$array = array('key' => 'value');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

echo $iterator->key(); //key
?>

ArrayIterator::next

(no version information, might be only in CVS)

ArrayIterator::next --  Move to next entry

Description

void ArrayIterator::next ( void )

This function moves the iterator to the next entry.

Esempio 1. ArrayIterator::next() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

Il precedente esempio visualizzerà:

0 => zero
1 => one

ArrayIterator::rewind

(no version information, might be only in CVS)

ArrayIterator::rewind --  Rewind array back to the start

Description

void ArrayIterator::rewind ( void )

This function rewinds the iterator to the beginning.

Esempio 1. ArrayIterator::rewind() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';
$arrayobject[] = 'two';

$iterator = $arrayobject->getIterator();

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the begining
echo $iterator->key(); //0
?>

ArrayIterator::seek

(no version information, might be only in CVS)

ArrayIterator::seek --  Seek to position

Description

void ArrayIterator::seek ( int position )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ArrayIterator::valid

(no version information, might be only in CVS)

ArrayIterator::valid --  Check whether array contains more entries

Description

bool ArrayIterator::valid ( void )

This function checks if the array contains any more entries.

Esempio 1. ArrayIterator::valid() example

<?php
$array = array('1' => 'one');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

var_dump($iterator->valid()); //bool(true)

$iterator->next(); // advance to the next item

//bool(false) because there is only one array element
var_dump($iterator->valid());
?>

ArrayObject::append

(no version information, might be only in CVS)

ArrayObject::append --  Appends the value

Description

void ArrayObject::append ( mixed newval )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ArrayObject::__construct

(no version information, might be only in CVS)

ArrayObject::__construct --  Construct a new array object

Description

ArrayObject ArrayObject::__construct ( mixed input )

This constructs a new array object. The input parameter accepts an array or another ArrayObject.

Esempio 1. ArrayObject::__construct() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

Il precedente esempio visualizzerà:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

ArrayObject::count

(no version information, might be only in CVS)

ArrayObject::count --  Return the number of elements in the Iterator

Description

int ArrayObject::count ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ArrayObject::getIterator

(no version information, might be only in CVS)

ArrayObject::getIterator --  Create a new iterator from an ArrayObject instance

Description

ArrayIterator ArrayObject::getIterator ( void )

This function will return an iterator from an ArrayObject.

Esempio 1. ArrayObject::getIterator() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

The above example will output:

1 => one
2 => two
3 => three

ArrayObject::offsetExists

(no version information, might be only in CVS)

ArrayObject::offsetExists --  Returns whether the requested $index exists

Description

bool ArrayObject::offsetExists ( mixed index )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ArrayObject::offsetGet

(no version information, might be only in CVS)

ArrayObject::offsetGet --  Returns the value at the specified $index

Description

bool ArrayObject::offsetGet ( mixed index )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ArrayObject::offsetSet

(no version information, might be only in CVS)

ArrayObject::offsetSet --  Sets the value at the specified $index to $newval

Description

void ArrayObject::offsetSet ( mixed index, mixed newval )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ArrayObject::offsetUnset

(no version information, might be only in CVS)

ArrayObject::offsetUnset --  Unsets the value at the specified $index

Description

void ArrayObject::offsetUnset ( mixed index )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingIterator::hasNext

(no version information, might be only in CVS)

CachingIterator::hasNext --  Check whether the inner iterator has a valid next element

Description

bool CachingIterator::hasNext ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingIterator::next

(no version information, might be only in CVS)

CachingIterator::next --  Move the iterator forward

Description

void CachingIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingIterator::rewind

(no version information, might be only in CVS)

CachingIterator::rewind --  Rewind the iterator

Description

void CachingIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingIterator::__toString

(no version information, might be only in CVS)

CachingIterator::__toString --  Return the string representation of the current element

Description

string CachingIterator::__toString ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingIterator::valid

(no version information, might be only in CVS)

CachingIterator::valid --  Check whether the current element is valid

Description

bool CachingIterator::valid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingRecursiveIterator::getChildren

(no version information, might be only in CVS)

CachingRecursiveIterator::getChildren --  Return the inner iterator's children as a CachingRecursiveIterator

Description

CachingRecursiveIterator CachingRecursiveIterator::getChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CachingRecursiveIterator::hasChildren

(no version information, might be only in CVS)

CachingRecursiveIterator::hasChildren --  Check whether the current element of the inner iterator has children

Description

bolean CachingRecursiveIterator::hasChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::__construct

(no version information, might be only in CVS)

DirectoryIterator::__construct --  Constructs a new dir iterator from a path

Description

DirectoryIterator DirectoryIterator::__construct ( string path )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::current

(no version information, might be only in CVS)

DirectoryIterator::current --  Return this (needed for Iterator interface)

Description

DirectoryIterator DirectoryIterator::current ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getATime

(no version information, might be only in CVS)

DirectoryIterator::getATime --  Get last access time of file

Description

int DirectoryIterator::getATime ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getCTime

(no version information, might be only in CVS)

DirectoryIterator::getCTime --  Get inode modification time of file

Description

int DirectoryIterator::getCTime ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getChildren

(no version information, might be only in CVS)

DirectoryIterator::getChildren --  Returns an iterator for the current entry if it is a directory

Description

RecursiveDirectoryIterator DirectoryIterator::getChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getFilename

(no version information, might be only in CVS)

DirectoryIterator::getFilename --  Return filename of current dir entry

Description

string DirectoryIterator::getFilename ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getGroup

(no version information, might be only in CVS)

DirectoryIterator::getGroup --  Get file group

Description

int DirectoryIterator::getGroup ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getInode

(no version information, might be only in CVS)

DirectoryIterator::getInode --  Get file inode

Description

int DirectoryIterator::getInode ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getMTime

(no version information, might be only in CVS)

DirectoryIterator::getMTime --  Get last modification time of file

Description

int DirectoryIterator::getMTime ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getOwner

(no version information, might be only in CVS)

DirectoryIterator::getOwner --  Get file owner

Description

int DirectoryIterator::getOwner ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getPath

(no version information, might be only in CVS)

DirectoryIterator::getPath --  Return directory path

Description

string DirectoryIterator::getPath ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getPathname

(no version information, might be only in CVS)

DirectoryIterator::getPathname --  Return path and filename of current dir entry

Description

string DirectoryIterator::getPathname ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getPerms

(no version information, might be only in CVS)

DirectoryIterator::getPerms --  Get file permissions

Description

int DirectoryIterator::getPerms ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getSize

(no version information, might be only in CVS)

DirectoryIterator::getSize --  Get file size

Description

int DirectoryIterator::getSize ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::getType

(no version information, might be only in CVS)

DirectoryIterator::getType --  Get file type

Description

string DirectoryIterator::getType ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isDir

(no version information, might be only in CVS)

DirectoryIterator::isDir --  Returns true if file is directory

Description

bool DirectoryIterator::isDir ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isDot

(no version information, might be only in CVS)

DirectoryIterator::isDot --  Returns true if current entry is '.' or '..'

Description

bool DirectoryIterator::isDot ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isExecutable

(no version information, might be only in CVS)

DirectoryIterator::isExecutable --  Returns true if file is executable

Description

bool DirectoryIterator::isExecutable ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isFile

(no version information, might be only in CVS)

DirectoryIterator::isFile --  Returns true if file is a regular file

Description

bool DirectoryIterator::isFile ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isLink

(no version information, might be only in CVS)

DirectoryIterator::isLink --  Returns true if file is symbolic link

Description

bool DirectoryIterator::isLink ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isReadable

(no version information, might be only in CVS)

DirectoryIterator::isReadable --  Returns true if file can be read

Description

bool DirectoryIterator::isReadable ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::isWritable

(no version information, might be only in CVS)

DirectoryIterator::isWritable --  Returns true if file can be written

Description

bool DirectoryIterator::isWritable ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::key

(no version information, might be only in CVS)

DirectoryIterator::key --  Return current dir entry

Description

string DirectoryIterator::key ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::next

(no version information, might be only in CVS)

DirectoryIterator::next --  Move to next entry

Description

void DirectoryIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::rewind

(no version information, might be only in CVS)

DirectoryIterator::rewind --  Rewind dir back to the start

Description

void DirectoryIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::valid

(no version information, might be only in CVS)

DirectoryIterator::valid --  Check whether dir contains more entries

Description

string DirectoryIterator::valid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

FilterIterator::current

(no version information, might be only in CVS)

FilterIterator::current --  Get the current element value

Description

mixed FilterIterator::current ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

FilterIterator::getInnerIterator

(no version information, might be only in CVS)

FilterIterator::getInnerIterator --  Get the inner iterator

Description

Iterator FilterIterator::getInnerIterator ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

FilterIterator::key

(no version information, might be only in CVS)

FilterIterator::key --  Get the current key

Description

mixed FilterIterator::key ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

FilterIterator::next

(no version information, might be only in CVS)

FilterIterator::next --  Move the iterator forward

Description

void FilterIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

FilterIterator::rewind

(no version information, might be only in CVS)

FilterIterator::rewind --  Rewind the iterator

Description

void FilterIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

FilterIterator::valid

(no version information, might be only in CVS)

FilterIterator::valid --  Check whether the current element is valid

Description

bool FilterIterator::valid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LimitIterator::getPosition

(no version information, might be only in CVS)

LimitIterator::getPosition --  Return the current position

Description

int LimitIterator::getPosition ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LimitIterator::next

(no version information, might be only in CVS)

LimitIterator::next --  Move the iterator forward

Description

void LimitIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LimitIterator::rewind

(no version information, might be only in CVS)

LimitIterator::rewind --  Rewind the iterator to the specified starting offset

Description

void LimitIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LimitIterator::seek

(no version information, might be only in CVS)

LimitIterator::seek --  Seek to the given position

Description

void LimitIterator::seek ( int position )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LimitIterator::valid

(no version information, might be only in CVS)

LimitIterator::valid --  Check whether the current element is valid

Description

bool LimitIterator::valid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ParentIterator::getChildren

(no version information, might be only in CVS)

ParentIterator::getChildren --  Return the inner iterator's children contained in a ParentIterator

Description

ParentIterator ParentIterator::getChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ParentIterator::hasChildren

(no version information, might be only in CVS)

ParentIterator::hasChildren --  Check whether the inner iterator's current element has children

Description

bool ParentIterator::hasChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ParentIterator::next

(no version information, might be only in CVS)

ParentIterator::next --  Move the iterator forward

Description

void ParentIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ParentIterator::rewind

(no version information, might be only in CVS)

ParentIterator::rewind --  Rewind the iterator

Description

void ParentIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveDirectoryIterator::getChildren

(no version information, might be only in CVS)

RecursiveDirectoryIterator::getChildren --  Returns an iterator for the current entry if it is a directory

Description

object RecursiveDirectoryIterator::getChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveDirectoryIterator::hasChildren

(no version information, might be only in CVS)

RecursiveDirectoryIterator::hasChildren --  Returns whether current entry is a directory and not '.' or '..'

Description

bool RecursiveDirectoryIterator::hasChildren ( [bool allow_links] )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveDirectoryIterator::key

(no version information, might be only in CVS)

RecursiveDirectoryIterator::key --  Return path and filename of current dir entry

Description

string RecursiveDirectoryIterator::key ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveDirectoryIterator::next

(no version information, might be only in CVS)

RecursiveDirectoryIterator::next --  Move to next entry

Description

void RecursiveDirectoryIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveDirectoryIterator::rewind

(no version information, might be only in CVS)

RecursiveDirectoryIterator::rewind --  Rewind dir back to the start

Description

void RecursiveDirectoryIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::current

(no version information, might be only in CVS)

RecursiveIteratorIterator::current --  Access the current element value

Description

mixed RecursiveIteratorIterator::current ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::getDepth

(no version information, might be only in CVS)

RecursiveIteratorIterator::getDepth --  Get the current depth of the recursive iteration

Description

int RecursiveIteratorIterator::getDepth ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::getSubIterator

(no version information, might be only in CVS)

RecursiveIteratorIterator::getSubIterator --  The current active sub iterator

Description

RecursiveIterator RecursiveIteratorIterator::getSubIterator ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::key

(no version information, might be only in CVS)

RecursiveIteratorIterator::key --  Access the current key

Description

mixed RecursiveIteratorIterator::key ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::next

(no version information, might be only in CVS)

RecursiveIteratorIterator::next --  Move forward to the next element

Description

void RecursiveIteratorIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::rewind

(no version information, might be only in CVS)

RecursiveIteratorIterator::rewind --  Rewind the iterator to the first element of the top level inner iterator

Description

void RecursiveIteratorIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

RecursiveIteratorIterator::valid

(no version information, might be only in CVS)

RecursiveIteratorIterator::valid --  Check whether the current position is valid

Description

bolean RecursiveIteratorIterator::valid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::current

(no version information, might be only in CVS)

SimpleXMLIterator::current --  Return current SimpleXML entry

Description

mixed SimpleXMLIterator::current ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::getChildren

(no version information, might be only in CVS)

SimpleXMLIterator::getChildren --  Returns an iterator for the current entry if it is a SimpleXML object

Description

object SimpleXMLIterator::getChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::hasChildren

(no version information, might be only in CVS)

SimpleXMLIterator::hasChildren --  Returns whether current entry is a SimpleXML object

Description

bool SimpleXMLIterator::hasChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::key

(no version information, might be only in CVS)

SimpleXMLIterator::key --  Return current SimpleXML key

Description

mixed SimpleXMLIterator::key ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::next

(no version information, might be only in CVS)

SimpleXMLIterator::next --  Move to next entry

Description

void SimpleXMLIterator::next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::rewind

(no version information, might be only in CVS)

SimpleXMLIterator::rewind --  Rewind SimpleXML back to the start

Description

void SimpleXMLIterator::rewind ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

SimpleXMLIterator::valid

(no version information, might be only in CVS)

SimpleXMLIterator::valid --  Check whether SimpleXML contains more entries

Description

bool SimpleXMLIterator::valid ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

class_implements

(PHP 5)

class_implements --  Return the interfaces which are implemented by the given class

Descrizione

array class_implements ( mixed class [, bool autoload] )

This function returns an array with the names of the interfaces that the given class and its parents implement.

Elenco dei parametri

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.

Valori restituiti

Returns an array or FALSE on error.

Log delle modifiche

VersioneDescrizione
5.1.0 Added the option to pass the class parameter as a string. Added the autoload parameter.

Esempi

Esempio 1. class_implements() example

<?php

interface foo { }
class bar implements foo {}

print_r(class_implements(new bar));

// since PHP 5.1 you may also specify the parameter as a string
print_r(class_implements('bar'));


function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_implements('not_loaded', true));

?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

Vedere anche:

class_parents()

class_parents

(PHP 5)

class_parents --  Return the parent classes of the given class

Descrizione

array class_parents ( mixed class [, bool autoload] )

This function returns an array with the name of the parent classes of the given class.

Elenco dei parametri

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.

Valori restituiti

Returns an array or FALSE on error.

Log delle modifiche

VersioneDescrizione
5.1.0 Added the option to pass the class parameter as a string. Added the autoload parameter.

Esempi

Esempio 1. class_parents() example

<?php

class foo { }
class bar extends foo {}

print_r(class_parents(new bar));

// since PHP 5.1 you may also specify the parameter as a string
print_r(class_parents('bar'));


function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_parents('not_loaded', true));
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [foo] => foo
)

Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

Vedere anche:

class_implements()

iterator_count

(PHP 5 >= 5.1.0RC1)

iterator_count --  Count the elements in an iterator

Description

int iterator_count ( IteratorAggregate iterator )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

iterator_to_array

(PHP 5 >= 5.1.0RC1)

iterator_to_array --  Copy the iterator into an array

Description

array iterator_to_array ( IteratorAggregate iterator )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

spl_classes

(PHP 5)

spl_classes --  Return available SPL classes

Description

array spl_classes ( void )

This function returns an array with the current available SPL classes.

Esempio 1. spl_classes() example

<?php

print_r(spl_classes());

?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [ArrayObject] => ArrayObject
    [ArrayIterator] => ArrayIterator
    [CachingIterator] => CachingIterator
    [CachingRecursiveIterator] => CachingRecursiveIterator
    [DirectoryIterator] => DirectoryIterator
    [FilterIterator] => FilterIterator
    [LimitIterator] => LimitIterator
    [ParentIterator] => ParentIterator
    [RecursiveDirectoryIterator] => RecursiveDirectoryIterator
    [RecursiveIterator] => RecursiveIterator
    [RecursiveIteratorIterator] => RecursiveIteratorIterator
    [SeekableIterator] => SeekableIterator
    [SimpleXMLIterator] => SimpleXMLIterator
)

CXLI. SQLite

Introduzione

Questo è un modulo per l'uso di SQLite Embeddable SQL Database Engine. SQLite è una libreria C che implementa al proprio interno un motore per database SQL. I programmi che compilano al proprio interno la libreria SQLite possono accedere ad un database senza dovere eseguire un processo RDBMS separato.

SQLite non è una libreria client che si deve collegare ad un qualche grosso server database. SQLite è il server. La libreria SQLite legge e scrive direttamente sul file del database.

Nota: Per maggiori informazioni vedere il sito web di SQLite (http://sqlite.org/).


Installazione

Leggere il file INSTALL allegato al pacchetto. Oppure utilizzare l'installatore PEAR con i parametri "pear install sqlite". La libreria SQLite è già inclusa. Non occorre installare altro software.

Gli utenti di Windows possono scaricare la versione DLL del module SQLite da qui: (php_sqlite.dll).

Da PHP 5, il modulo SQLite e il motore stesso saranno inclusi per default.


Requisiti

Per potere utilizzare questa funzioni, occorre compilare il PHP con il supporto per SQLite, oppure caricare dinamicamente il modulo da php.ini.


Tipi di risorse

SQLite utilizza due risorse. La prima è la connessione con il database, la seconda è il set di risultati.


Costanti predefinite

Le funzioni sqlite_fetch_array() e sqlite_current() utilizzano costanti per indicare i differenti tipi di matrici da restituire. Tali costanti sono:

Tabella 1. Costanti di SQLiteper scaricare le righe

costantesignificato
SQLITE_ASSOC Le colonne sono restituite in una matrice il cui indice è il nome del campo.
SQLITE_BOTH Le colonne sono restituite in una matrice il cui indice è costituito sia dal nome del campo sia numero della posizione di questo nella riga.
SQLITE_NUM Le colonne sono restituite in una matrice il cui indice è costituito dalla posizione del campo nella riga. La prima colonna parte da 0.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 2. Parametri di configurazione di SQLite

NomeDefaultModificabile
sqlite.assoc_case0PHP_INI_ALL
Per maggiori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

sqlite.assoc_case int

Indica se utilizzare indici misti (0), solo maiuscole (1) oppure solo minuscoli (2).

Questa opzione è utile quando si ha necessità di avere compatibilità con altri database, nei quali i nomi delle colonne sono sempre restituiti o maiuscoli o minuscoli, a prescindere dalla definizione del campo nello schema del database.

La libreria SQLite restituisce i nomi delle colonne così come sono definiti (ovvero rispettando le maiuscole o le minuscole indicate nello schema). Quando si imposta sqlite.assoc_case a 0 si rispetta la definizione. Quando si imposta il parametro a 1 oppure a 2, il PHP converte i nomi rispettivamente in maiuscolo o minuscolo.

L'utilizzo di questa opzione comporta una lieve penalità nelle performance, ma è molto più veloce che convertire i nomi dallo script PHP.

Sommario
sqlite_array_query -- Esegue una query in un dato database e restituisce una matrice
sqlite_busy_timeout -- Imposta il timeout di 'in uso', o disabilita l'handle di 'in uso'
sqlite_changes --  Restituisce il numero di righe modificate dall'ultima istruzione SQL
sqlite_close -- Chiude un database SQLite
sqlite_column -- Scarica una riga dal set di risultati corrente
sqlite_create_aggregate -- Registra un aggregato UDF da utilizzare nelle istruzioni SQL
sqlite_create_function --  Registra una funzione utente "regolare" da utilizzare nelle istruzioni SQL
sqlite_current -- Scarica la riga corrente di un set di risultati in una matrice
sqlite_error_string -- Restituisce la descrizione testuale di un codice di errore
sqlite_escape_string -- Inserisce il carattere di escape in stringa da usarsi in una query
sqlite_exec -- ESegue una query priva di risultato in un dato database
sqlite_factory -- Apre un database SQLite e restituisce un oggetto SQLiteDatabase
sqlite_fetch_all -- Scarica tutte le righe di un risultato in una matrice di matrici
sqlite_fetch_array -- Scarica in una matrice la riga successiva da un set di risultati
sqlite_fetch_column_types --  Restituisce una matrice con il formato delle colonne di una tabella
sqlite_fetch_object -- Scarica i dati deti della riga successiva come oggetto
sqlite_fetch_single -- Scarica come stringa la prima colonna di un set di risultati
sqlite_fetch_string -- Alias di sqlite_fetch_single()
sqlite_field_name -- Restituisce il nome di un particolare campo
sqlite_has_more -- Restituisce se sono disponibili o meno ulteriori righe
sqlite_has_prev -- Indica se è disponibile o meno una riga precedente
sqlite_key -- Restituisce l'indice di riga corrente
sqlite_last_error -- Restituisce il codice di errore dell'ultimo errore accorso sul database
sqlite_last_insert_rowid -- Restituisce l'identificativo di riga dell'ultima riga inserita
sqlite_libencoding -- Restituisce la codifica della libreria SQLite
sqlite_libversion -- Restituisce la versione della libreria SQLite
sqlite_next -- Si sposta al successivo numero di riga
sqlite_num_fields -- Resituitsce il numero di campi da un set di risultati
sqlite_num_rows -- Restituisce il numero di righe da un set di risultati bufferizzato
sqlite_open -- Apre un database SQLite e crea il database se non esiste
sqlite_popen --  Apre una connessione persistente ad un database SQLite e crea il database se non esiste
sqlite_prev -- Si posiziona sulla riga precedente di un set di risultati
sqlite_query -- Esegue una query su un database e restituisce un puntatore al set di risultati
sqlite_rewind -- Si posiziona sulla prima riga
sqlite_seek -- Posizionamento su una data riga di un set di risultati bufferizzato
sqlite_single_query --  Esegue una query e restituisce o una matrice per ogni singola colonna o il valore della prima riga
sqlite_udf_decode_binary -- Decodifica dati binari passati come parametri in UDF
sqlite_udf_encode_binary -- Codifica i dati binari prima di restituirli da un UDF
sqlite_unbuffered_query -- Esegue una query senza scaricare e bufferizzare i dati
sqlite_valid -- Indica se una o più righe sono disponibili

sqlite_array_query

(PHP 5)

sqlite_array_query

(no version information, might be only in CVS)

SQLiteDatabase->arrayQuery -- Esegue una query in un dato database e restituisce una matrice

Descrizione

array sqlite_array_query ( resource dbhandle, string query [, int result_type [, bool decode_binary]] )

array sqlite_array_query ( string query, resource dbhandle [, int result_type [, bool decode_binary]] )

Versione ad oggetti (metodo):

class SQLiteDatabase {

array arrayQuery ( string query [, int result_type [, bool decode_binary]] )

}

sqlite_array_query() esegue una data query e restituisce un matrice con l'intero set di risultati. E' simile a sqlite_query() e a eseguiresqlite_fetch_array() per ogni riga. sqlite_array_query() è significativamente più veloce.

Suggerimento: Le migliori performance con sqlite_array_query() si ottengono con query che restituiscono fino a 45 righe. Se si ha più dati si raccomanda di scrivere una propria funzione e di utilizzare sqlite_unbuffered_query().

Elenco dei parametri

query

Query da eseguire.

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Valori restituiti

Restituisce una matrice contenente tutti i risultati, oppure FALSE.

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

Esempi

Esempio 1. Stile procedurale

<?php
$dbhandle = sqlite_open('sqlitedb');
$result = sqlite_array_query($dbhandle, 'SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Esempio 2. Stile ad oggetti

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

sqlite_busy_timeout

(PHP 5)

sqlite_busy_timeout

(no version information, might be only in CVS)

SQLiteDatabase->busyTimeout -- Imposta il timeout di 'in uso', o disabilita l'handle di 'in uso'

Descrizione

void sqlite_busy_timeout ( resource dbhandle, int milliseconds )

Object oriented style (method):

class SQLiteDatabase {

void busyTimeout ( int milliseconds )

}

SImposta il tempo massimo che sqlite attenderà che un dbhandle diventi disponibile all'uso.

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

milliseconds

Numero di millisecondi. Se il parametro è impostato a 0, l'handle di 'in uso' viene disattivato e sqlite ritornerà immediatamente con un errore SQLITE_BUSY se un'altro processo/thread ha bloccato il database per un aggiornamento.

Il PHP imposta per default il timeout di 'in uso' a 60 secondi durante l'apertura del database.

Nota: Ci sono mille (1000) millisecondi in un secondo.

Esempi

Esempio 1. Stile procedurale

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>

Esempio 2. Stile ad oggetti

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

Vedere anche:

sqlite_open()

sqlite_changes

(PHP 5)

sqlite_changes

(no version information, might be only in CVS)

SQLiteDatabase->changes --  Restituisce il numero di righe modificate dall'ultima istruzione SQL

Descrizione

int sqlite_changes ( resource dbhandle )

Versione ad oggetti (metodo):

class SQLiteDatabase {

int changes ( void )

}

Restituisce il numero di righe modificate dall'ultima istruzione SQL eseguita sul database referenziato da dbhandle.

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

Esempi

Esempio 1. Stile procedurale

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_query($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Esempio 2. Stile ad oggetti

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

Vedere anche:

sqlite_open()

sqlite_close

(PHP 5)

sqlite_close -- Chiude un database SQLite

Descrizione

void sqlite_close ( resource dbhandle )

Chiude il database indicato dall'handle database. Se il database è persistente, questo sarà chiuso e rimosso dalla lista dei database persistenti.

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale.

Esempi

Esempio 1. Esempio di uso di sqlite_close()

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

sqlite_column

(PHP 5)

sqlite_column

(no version information, might be only in CVS)

SQLiteResult->column

(no version information, might be only in CVS)

SQLiteUnbuffered->column -- Scarica una riga dal set di risultati corrente

Descrizione

mixed sqlite_column ( resource result, mixed index_or_name [, bool decode_binary] )

class SQLiteResult {

mixed column ( mixed index_or_name [, bool decode_binary] )

}class SQLiteUnbuffered {

mixed column ( mixed index_or_name [, bool decode_binary] )

}

Scarica il valore dalla colonna index_or_name (se si tratta di una stringa) o della colonna numero index_or_name (se il parametro è un intero) dalla riga corrente del set di risultati indicato da result.

Elenco dei parametri

result

Risorsa SQLite per un set di risultati. Questo parametro non è richiesto quando la funzione è utilizzata nello stile ad oggetti.

index_or_name

Indice o nome della colonna da scaricare.

decode_binary

Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.

Note

Nota: Utilizzare questa funzione quando si opera su set di risultati con molte colonne o con colonne che contengano grandi quantità di dati.

Vedere anche:

sqlite_fetch_string()

sqlite_create_aggregate

(PHP 5)

sqlite_create_aggregate

(no version information, might be only in CVS)

SQLiteDatabase->createAggregate -- Registra un aggregato UDF da utilizzare nelle istruzioni SQL

Descrizione

bool sqlite_create_aggregate ( resource dbhandle, string function_name, callback step_func, callback finalize_func [, int num_args] )

Versione ad oggetti (metodo):

class SQLiteDatabase {

bool createAggregate ( string function_name, callback step_func, callback finalize_func [, int num_args] )

}

sqlite_create_aggregate() è simile a sqlite_create_function() tranne che le funzioni di registrazione possono essere utilizzate per calcolare un risultato aggregato da tutte le righe della query.

La differenza chiave tra questa funzione e sqlite_create_function() è che entrambe le funzioni sono necessarie per gestire gli aggregati; la funzione step_func viene richiamata per ogni riga del set di risultati. La funzione PHP personalizzata dovrebbe accumulare i dati memorizzarli nel contesto di aggregazione. Una volta che tutte le righe sono state processate, si esegue la funzione finalize_func che dovrebbe prendere i dati dal contesto di aggregazione e restituire il risultato. La funzione personalizzata deve restituire un tipo riconosciuto da SQLite (ad esempio un tipo scalare).

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

function_name

Nome della funzione usata nell'istruzione SQL.

step_func

Funzione richiamata per ogni riga del set di risultati.

finalize_func

Funzione di callback richiamata per aggragare i dati da ogni riga.

num_args

Suggerisce al parser SQLite se la funzione di callback accetta un numero predefinito di argomenti.

Esempi

Esempio 1. Esempio di una funzione di aggregazione lunghezza_massima

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string) 
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context) 
{
    return $context;
}

sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));

?>

In questo esempio creiamo una funzione di aggregazione che calcola la lunghezza della stringa più lunga presente in una colonna della tabella. Per ciascuna riga, si esegue la funzione max_len_step nella quale viene passato il parametro context. Questo parametro è come una qualsiasi variabile PHP ed è impostata per contenere un array od un oggetto. In questo esempio, verrà utilizzata semplicemente per contenere la lunghezza massima della stringa; se la string è di lunghezza superiore al valore massimo corrente, noi aggiorneremo il contesto affinchè registri il nuovo massimo.

Quando sono state processate tutte le righe, SQLite esegue la funzione max_len_finalize per determinare il risultato aggregato. In questa funzione possiamo svolgere qualsiasi tipo di operazione basata sui dati presenti nel parametro context. Nel nostro esempio abbiamo calcolato il risultato man mano che si processava la righe, pertanto non ci resta che restituire il valore.

Nota: L'esempio precedente non avrebbe funzionato correttamente se la colonna avesse contenuto dati binari. Guardare sul manuale la pagina sqlite_udf_decode_binary() per una spiegazione del perché, e l'esempio di come questo rispetti la codifica binaria.

Suggerimento: NON si raccomanda si memorizzare nel contesto una copia dei valori di ciascuna riga, per poi processarli alla fina; questo costringe SQLite a utilizzare una grande quantità di memoria per processare la query - basta pensare a quanta memoria sarebbe necessaria se si memorizzasse un milione di righe, ciscuna contenente una stringa di 32 byte.

Suggerimento: Si può utilizzare sqlite_create_function() e sqlite_create_aggregate() per non utilizzare la funzioni SQL native di SQLite.

sqlite_create_function

(PHP 5)

sqlite_create_function

(no version information, might be only in CVS)

SQLiteDatabase->createFunction --  Registra una funzione utente "regolare" da utilizzare nelle istruzioni SQL

Descrizione

bool sqlite_create_function ( resource dbhandle, string function_name, callback callback [, int num_args] )

Versione ad oggetti (metodo):

class SQLiteDatabase {

bool createFunction ( string function_name, callback callback [, int num_args] )

}

La funzione sqlite_create_function() permette di registrare una funzione PHP in SQLite come UDF (funzione definita dall'utente, User Defined Function), in modo che possa essere richiamata dalle istruzioni SQL.

Le UDF possono essere utilizzate in qualsiasi istruzione SQL che permetta di richiamare funzioni, tipo SELECT e UPDATE e anche i triggers.

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

function_name

Indica il nome della funzione che si vuole utilizzare nelle istruzioni SQL.

callback

Funzione di callback richiamata per gestire la funzione SQL.

Nota: Le funzioni di callback devono restituire un tipo noto a SQLite (ad esempio un tipo scalare).

num_args

Indicazione al parser SQLite se la funzione di callback accetta un numero predefinito di argomenti.

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Esempi

Esempio 1. Esempio di uso di sqlite_create_function()

<?php
function md5_and_reverse($string) 
{
    return strrev(md5($string));
}

if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
    
    sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);
    
    $sql  = 'SELECT md5rev(filename) FROM files';
    $rows = sqlite_array_query($dbhandle, $sql);
} else {
    echo 'Error opening sqlite db: ' . $sqliteerror;
    exit;
}
?>

In questo esempio abbiamo una funzione che calcola il valore md5 di una stringa e lo inverte. Quando sono eseguite le istruzioni SQL, queste restituiscono il nome del file trasformato dalla nostra funzione. Il valore restituito in $rows contiene il risultato processato.

L'aspetto interessante di questa tecnica è che non è necessario elaborare i dati di una query utilizzando un ciclo foreach() dopo avere eseguito una query per ottenere i dati

Il PHP registra una speciale funzione chiamata php quando apre il database la prima volta. La funzione php può essere utilizzata per chiamare qualsiasi funzione PHP senza doverla registrare prima.

Esempio 2. Esempio dell'uso della funzione php

<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>

Questo esempio chiamerà la funzione md5() per ciasuna colonna filename del database e restituirà il risultato in $rows

Nota: Per motivi di performance, il PHP non convertirà in automatico i dati binari passati da/per la UDF. Occorre convertire manualmente i parametri e restituire i valori nel medesimo modo, se si desidera elaborare i dati binari. Guardare le pagine relative a sqlite_udf_encode_binary() e sqlite_udf_decode_binary() per maggiori dettagli.

Suggerimento: Non è raccomandabile l'uso delle UDF per processare dati binari, a meno che non siano richieste all'applicazione elevate performance.

Suggerimento: Si può utilizzare sqlite_create_function() e sqlite_create_aggregate() per sovrascrivere le funzioni SQL native in SQLite.

sqlite_current

(PHP 5)

sqlite_current

(no version information, might be only in CVS)

SQLiteResult->current

(no version information, might be only in CVS)

SQLiteUnbuffered->current -- Scarica la riga corrente di un set di risultati in una matrice

Descrizione

array sqlite_current ( resource result [, int result_type [, bool decode_binary]] )

Versione ad oggetti (metodo):

class SQLiteResult {

array current ( [int result_type [, bool decode_binary]] )

}class SQLiteUnbuffered {

array current ( [int result_type [, bool decode_binary]] )

}

sqlite_current() è simile a sqlite_fetch_array() tranne che non avanza alla riga successiva prima di restituire i dati; la funzione restituisce i dati soltanto dalla posizione corrente.

Elenco dei parametri

result

Risorsa SQLite di un set di risultati. Questo parametro non è necessario quando la funzione è utilizzata ad oggetti.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.

Valori restituiti

Restituisce una matrice della riga corrente dal set di risultati, oppure FALSE se la posizione corrente è oltre la riga finale.

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

sqlite_error_string

(PHP 5)

sqlite_error_string -- Restituisce la descrizione testuale di un codice di errore

Descrizione

string sqlite_error_string ( int error_code )

Restituisce una descrizione leggibile del error_code restituito dalla funzione sqlite_last_error().

Vedere anche:

sqlite_last_error()

sqlite_escape_string

(PHP 5)

sqlite_escape_string -- Inserisce il carattere di escape in stringa da usarsi in una query

Descrizione

string sqlite_escape_string ( string item )

La funzione sqlite_escape_string() inserisce i caratteri di escape nella stringa indicata da item, per poterla utilizzare nelle istruzioni SQL. Questo processo include il raddoppio dell'apice singolo (') e la verifica della presenza di dati binari non sicuri nella stringa.

Se il parametro item contiene un NUL, oppure comincia con un carattere il cui numero ordinale è 0x01, Il PHP applicherà lo schema di codifica binaria in modo da potere memorizzare e recuperare il dato in binario.

Sebbene la codifica binaria permetta un sicuro inserimento dei dati, questo rende inutilizzabile i semplici confronti di testo e la clausola LIKE sulle colonne che contengono dati binari. In pratica, non dovrebbe essere un problema, se nello schema definito non si prevede l'uso di tali funzioni su colonne binarie (infatti è meglio memorizzati dati binari in altri modi, tipo in file a parte).

Avvertimento

La funzione addslashes() NON dovrebbe essere utilizzata per inserire i caratteri di escape nelle query SQLite; questa porta a strani risultati quando si recuperano i dati.

Nota: Non utilizzare questa funzione per codificare i dati restituiti da funzioni UDF create tramite sqlite_create_function() o sqlite_create_aggregate() - utilizzare invece sqlite_udf_encode_binary().

sqlite_exec

(PHP 5)

sqlite_exec

(no version information, might be only in CVS)

SQLiteDatabase->exec -- ESegue una query priva di risultato in un dato database

Descrizione

bool sqlite_exec ( resource dbhandle, string query )

bool sqlite_exec ( string query, resource dbhandle )

Versione ad oggetti (metodo):

class SQLiteDatabase {

bool exec ( string query )

}

Esegue un'espressione SQL, indicata da query sul database (specificato dal parametro dbhandle).

Avvertimento

SQLite esegue molteplici query separate da punto e virgola, in questo modo si può eseguire un batch di istruzioni SQL caricate da un file o racchiuse in uno script.

Elenco dei parametri

query

Query da eseguire.

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Valori restituiti

Questa funzione restituisce il valore TRUE se ha successo, oppure FALSE per insuccesso. Se si deve eseguire una query che restituisca un risultato eseguire sqlite_query().

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

Esempi

Esempio 1. Esempio procedurale

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Esempio 2. Esempio ad oggetti

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->exec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

sqlite_factory

(PHP 5)

sqlite_factory -- Apre un database SQLite e restituisce un oggetto SQLiteDatabase

Descrizione

SQLiteDatabase sqlite_factory ( string filename [, int mode [, string &error_message]] )

sqlite_factory() si comporta in modo simile a sqlite_open() in quanto apre un database SQLITE o cerca di crearlo se non esiste. Tuttavia, la funzione restituisce un oggetto SQLiteDatabase anzichè una risorsa. Vedere la pagina del manuale di sqlite_open() per maggiori dettagli.

Elenco dei parametri

filename

Il nome del file del database SQLite.

mode

Modalità del file. Intesa per essere utilizzata per aprire il database in modalità sola lettura. Attualmente questo parametro è ignorato dalla libreria SQLite. Il valore di default è il valore ottale 0666 ed è l'impostazione raccomandata.

error_message

Passato per riferimento ed è impostato per restituire un messaggio di errore descrittivo del perchè il database non può essere aperto in caso di errore.

Valori restituiti

Restituisce un oggetto SQLiteDatabase in caso di successo, NULL in caso di errore.

Esempi

Esempio 1. Esempio di uso di sqlite_factory()

<?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

/* Funzione equivalente a */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

?>

sqlite_fetch_all

(PHP 5)

sqlite_fetch_all

(no version information, might be only in CVS)

SQLiteResult->fetchAll

(no version information, might be only in CVS)

SQLiteUnbuffered->fetchAll -- Scarica tutte le righe di un risultato in una matrice di matrici

Descrizione

array sqlite_fetch_all ( resource result [, int result_type [, bool decode_binary]] )

Versione ad oggetti (metodo):

class SQLiteResult {

array fetchAll ( [int result_type [, bool decode_binary]] )

}class SQLiteUnbuffered {

array fetchAll ( [int result_type [, bool decode_binary]] )

}

sqlite_fetch_all() restituisce una matrice con l'intero set di risultati dalla risorsa result. E' simile ad eseguire sqlite_query() (oppure sqlite_unbuffered_query()) e quindi sqlite_fetch_array() per ciascuna riga del set di risultati.

Elenco dei parametri

result

Risorsa SQLite. Questo parametro non è richiesto quando si usa il metodo ad oggetti.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.

Valori restituiti

Restituisce una matrice della riga corrente da un set di risultati, oppure FALSE se la posizione corrente è oltre l'ultima riga.

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

Esempi

Esempio 1. Esempio procedurale

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Esempio 2. Esempio ad oggetti

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Vedere anche:

sqlite_fetch_array()

sqlite_fetch_array

(PHP 5)

sqlite_fetch_array

(no version information, might be only in CVS)

SQLiteResult->fetch

(no version information, might be only in CVS)

SQLiteUnbuffered->fetch -- Scarica in una matrice la riga successiva da un set di risultati

Descrizione

array sqlite_fetch_array ( resource result [, int result_type [, bool decode_binary]] )

Versione ad oggetti (metodo):

class SQLiteResult {

array fetch ( [int result_type [, bool decode_binary]] )

}class SQLiteUnbuffered {

array fetch ( [int result_type [, bool decode_binary]] )

}

Scarica la riga successiva dal set di risultati indicato da result. Se non vi sono righe successive, restituisce FALSE, altrimenti restituisce una matrice associativa rappresentante i dati della riga.

Elenco dei parametri

result

Risorsa SQLite. Questo parametro non è richiesto nella versione ad oggetti.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.

Valori restituiti

Restituisce una matrice della riga successiva dal set di risultati, FALSE se la posizine successive è oltre l'ultima riga.

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

Esempi

Esempio 1. Esempio procedurale

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Esempio 2. Esempio ad oggetti

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

sqlite_fetch_column_types

(PHP 5)

sqlite_fetch_column_types

(no version information, might be only in CVS)

SQLiteDatabase->fetchColumnTypes --  Restituisce una matrice con il formato delle colonne di una tabella

Descrizione

array sqlite_fetch_column_types ( string table_name, resource dbhandle [, int result_type] )

Versione ad oggetti (metodo):

class SQLiteDatabase {

array fetchColumnTypes ( string table_name [, int result_type] )

}

sqlite_fetch_column_types() rRestituisce una matrice con il tipo di dato delle colonne della tabella indicata da table_name.

Elenco dei parametri

table_name

Nome della tabella.

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

Valori restituiti

Restituisce una matrice con i tipi di dati delle colonne, oppure FALSE in caso di errore.

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

Esempi

Esempio 1. Esempio procedurale

<?php
$db = sqlite_open('mysqlitedb');
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10), arf text)');
$cols = sqlite_fetch_column_types('foo', $db, SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type";
}
?>

Esempio 2. Esempio ad oggetti

<?php
$db = new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type";
}
?>

Il precedente esempio visualizzerà:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT

sqlite_fetch_object

(PHP 5)

sqlite_fetch_object

(no version information, might be only in CVS)

SQLiteResult->fetchObject

(no version information, might be only in CVS)

SQLiteUnbuffered->fetchObject -- Scarica i dati deti della riga successiva come oggetto

Descrizione

object sqlite_fetch_object ( resource result [, string class_name [, array ctor_params [, bool decode_binary]]] )

Versione ad oggetti (metodo):

class SQLiteResult {

object fetchObject ( [string class_name [, array ctor_params [, bool decode_binary]]] )

}class SQLiteUnbuffered {

object fetchObject ( [string class_name [, array ctor_params [, bool decode_binary]]] )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

sqlite_fetch_single

(PHP 5)

sqlite_fetch_single

(no version information, might be only in CVS)

SQLiteResult->fetchSingle

(no version information, might be only in CVS)

SQLiteUnbuffered->fetchSingle -- Scarica come stringa la prima colonna di un set di risultati

Descrizione

string sqlite_fetch_single ( resource result [, bool decode_binary] )

Versione ad oggetti (metodo):

class SQLiteResult {

string fetchSingle ( [bool decode_binary] )

}class SQLiteUnbuffered {

string fetchSingle ( [bool decode_binary] )

}

sqlite_fetch_single() è simile a sqlite_fetch_array() tranne che restituisce il valore della prima colonna di una riga.

Questo è il mezzo migliore per recuperare i dati quando si è interessati soltanto ai valori di una singola colonna.

Elenco dei parametri

result

SQLite risorsa. Questo parametro non è richiesto quando la funzione viene usata nella versione ad oggetti.

decode_binary

Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.

Esempi

Esempio 1. Esempio di uso di sqlite_fetch_single()

<?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    $sql = "SELECT id FROM sometable WHERE id = 42";
    $res = sqlite_query($dbhandle, $sql);

    if (sqlite_num_rows($res) > 0) {
        echo sqlite_fetch_single($res); // 42
    }
    
    sqlite_close($dbhandle);
}
?>

Vedere anche:

sqlite_fetch_array()

sqlite_fetch_string

(PHP 5)

sqlite_fetch_string -- Alias di sqlite_fetch_single()

Descrizione

This function is an alias of: sqlite_fetch_single().

sqlite_field_name

(PHP 5)

sqlite_field_name

(no version information, might be only in CVS)

SQLiteResult->fieldName

(no version information, might be only in CVS)

SQLiteUnbuffered->fieldName -- Restituisce il nome di un particolare campo

Descrizione

string sqlite_field_name ( resource result, int field_index )

Versione ad oggetti (metodo):

class SQLiteResult {

string fieldName ( int field_index )

}class SQLiteUnbuffered {

string fieldName ( int field_index )

}

Dato il numero ordinale di colonna, field_index, restituisce il nome del campo dal set di risultati indicato in result.

Elenco dei parametri

result

Risorsa SQLite. Questo parametro non è richiesto quando si utilizza la funzione nella versione ad oggetti.

field_index

Numero ordinale della colonna nel set di risultati.

Valori restituiti

Restituisce il nome del campo dal set di risultati SQLite, dato il numero della colonna, oppure FALSE in caso di errore.

I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

sqlite_has_more

(PHP 5)

sqlite_has_more -- Restituisce se sono disponibili o meno ulteriori righe

Descrizione

bool sqlite_has_more ( resource result )

Indica se sono disponibili o meno ulteriori righe.

Elenco dei parametri

result

Risorsa set di risultati di SQLite.

Valori restituiti

sqlite_has_more() restituisce TRUE se sono disponibili ulteriori righe dal set di risultati result, oppure FALSE in caso contrario.

sqlite_has_prev

(PHP 5)

sqlite_has_prev

(no version information, might be only in CVS)

SQLiteResult->hasPrev -- Indica se è disponibile o meno una riga precedente

Descrizione

bool sqlite_has_prev ( resource result )

Object oriented style (method):

class SQLiteResult {

bool hasPrev ( void )

}

Indica se è disponibile o meno una riga precedente nel dato set di risultati.

Elenco dei parametri

result

Risorsa set di risultati di SQLite. Questo parametro non è richiesto nel caso si utilizzi la funzione nella versione ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

Valori restituiti

Restituisce TRUE se vi sono ulteriori righe precedenti dal set di risultati result, oppure FALSE in caso contrario.

sqlite_key

(no version information, might be only in CVS)

sqlite_key

(no version information, might be only in CVS)

SQLiteResult->key -- Restituisce l'indice di riga corrente

Descrizione

int sqlite_key ( resource result )

Object oriented style (method):

class SQLiteResult {

int key ( void )

}

sqlite_key() restituisce l'indice della riga corrente del set di risultati result.

Elenco dei parametri

result

Risorsa set di risultati di SQLite. Questo parametro non è richiesto nel caso si utilizzi la funzione nella versione ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

Valori restituiti

Restituisce l'indice della riga corrente del set di risultati result.

Log delle modifiche

VersioneDescrizione
5.0.4 Prima di PHP 5.0.4, sqlite_key() poteva essere chiamato come metodo dell'oggetto SQLiteResult, e non per via procedurale.

sqlite_last_error

(PHP 5)

sqlite_last_error

(no version information, might be only in CVS)

SQLiteDatabase->lastError -- Restituisce il codice di errore dell'ultimo errore accorso sul database

Descrizione

int sqlite_last_error ( resource dbhandle )

Versione ad oggetti (metodo):

class SQLiteDatabase {

int lastError ( void )

}

Restituisce il codice di errore dall'ultima operazione eseguita sul database dbhandle. Una descrizione interpretabile dell'errore può essere ricavata tramite la funzione sqlite_error_string().

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

Vedere anche:

sqlite_error_string()

sqlite_last_insert_rowid

(PHP 5)

sqlite_last_insert_rowid

(no version information, might be only in CVS)

SQLiteDatabase->lastInsertRowid -- Restituisce l'identificativo di riga dell'ultima riga inserita

Descrizione

int sqlite_last_insert_rowid ( resource dbhandle )

Versione ad oggetti (metodo):

class SQLiteDatabase {

int lastInsertRowid ( void )

}

Restituisce l'identificativo di riga dell'ultima riga inserita nel database dbhandle, se questo è stato creato con un campo auto-increment.

Suggerimento: In SQLite si può creare un campo auto-increment dichiarando questo come INTEGER PRIMARY KEY nello schema della tabella.

Elenco dei parametri

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

sqlite_libencoding

(PHP 5)

sqlite_libencoding -- Restituisce la codifica della libreria SQLite

Descrizione

string sqlite_libencoding ( void )

La libreria SQLite può essere compilata in modalità ISO-8859-1 o UTF-8 compatibile. Questa funzione permette di determinare quale schema di codifica è stato usato per questa versione della libreria.

Avvertimento

Per default il PHP distribuisce libsqlite nella codifica ISO-8859-1. Tuttavia questo non è proprio vero; piuttosto che gestire il formato ISO-8859-1 la libreria opera in modo coerente con le impostazioni locali per quanto riguarda i confronti e gli ordinamenti. Pertanto, più che ISO-8859-1, si dovrebbe pensare come se fosse a 8 bit.

Quando è compilato con il supporto alla codifica UTF-8, SQLite gestisce le codifiche e le decodifiche dei caratteri multi-byte UTF-8, ma non svolge ancora un lavoro completo quando opera sui dati (ad esempio non viene svolta la normalizzazione), e alcune operazioni di confronto possono non essere ancora precise.

Avvertimento

Si raccomanda di non utilizzare il PHP nella configurazione di web-server con le librerie compilate per il supporto di UTF-8, poiché libsqlite abortirà il processo se rileva dei problemi con la codifica UTF-8.

Vedere anche:

sqlite_lib_version()

sqlite_libversion

(PHP 5)

sqlite_libversion -- Restituisce la versione della libreria SQLite

Description

string sqlite_libversion ( void )

Restituisce la versione della libreria SQLite.

Vedere anche:

sqlite_libencoding()

sqlite_next

(PHP 5)

sqlite_next

(no version information, might be only in CVS)

SQLiteResult->next

(no version information, might be only in CVS)

SQLiteUnbuffered->next -- Si sposta al successivo numero di riga

Descrizione

bool sqlite_next ( resource result )

Versione ad oggetti (metodo):

class SQLiteResult {

bool next ( void )

}class SQLiteUnbuffered {

bool next ( void )

}

La funzione sqlite_next() avanza il set di risultati indicato da result alla riga successiva.

Elenco dei parametri

result

Risorsa set di risultati di SQLite. Questo parametro non è richiesto nella versione ad oggetti.

Valori restituiti

Restituisce FALSE se non vi sono ulteriori righe, TRUE in caso contrario.

sqlite_num_fields

(PHP 5)

sqlite_num_fields

(no version information, might be only in CVS)

SQLiteResult->numFields

(no version information, might be only in CVS)

SQLiteUnbuffered->numFields -- Resituitsce il numero di campi da un set di risultati

Descrizione

int sqlite_num_fields ( resource result )

Versione ad oggetti (metodo):

class SQLiteResult {

int numFields ( void )

}class SQLiteUnbuffered {

int numFields ( void )

}

Restituisce il numero di campi presenti nel set di risultati result.

Elenco dei parametri

result

Risorsa set di risultati di SQLite. Questo parametro non è richiesto nella versione ad oggetti.

sqlite_num_rows

(PHP 5)

sqlite_num_rows

(no version information, might be only in CVS)

SQLiteResult->numRows -- Restituisce il numero di righe da un set di risultati bufferizzato

Description

int sqlite_num_rows ( resource result )

Versione ad oggetti (metodo):

class SQLiteResult {

int numRows ( void )

}

Restituisce il numero di righe dal set di risultati result bufferizzato.

Elenco dei parametri

result

Risorsa set di risultati di SQLite. Questo parametro non è richiesto nella versione ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

Esempi

Esempio 1. Esempio procedurale

<?php
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);

echo "Number of rows: $rows";
?>

Esempio 2. Esempio ad oggetti

<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();

echo "Number of rows: $rows";
?>

sqlite_open

(PHP 5)

sqlite_open -- Apre un database SQLite e crea il database se non esiste

Descrizione

resource sqlite_open ( string filename [, int mode [, string &error_message]] )

Versione ad oggetti (costruttore):

class SQLiteDatabase {

__construct ( string filename [, int mode [, string &error_message]] )

}

Apre un database SQLite o lo crea se non esiste.

Elenco dei parametri

filename

Nome del database SQLite. Se il file non esiste, SQLite tenterà di crearlo. Il PHP deve avere i permessi di scrittura sul file se si desidera inserire dei dati o modficare lo schema del database, o creare il database se non esiste.

mode

Specifica la modalità del file. E' inteso per essere utilizzato per l'apertura del file in modalità read-only. Attualmente questo parametro viene ignorato da SQLite. Per default la modalità di apertura è il valore ottale 0666, ed è questa l'impostazione raccomandata.

error_message

Passato per riferimento, è impostato per contenere un messaggio descrittivo di errore nel caso non si riesca ad aprire il database a causa di un errore.

Valori restituiti

Restituisce una risorsa (database handle) se ha successo, oppure FALSE se si verifica un errore.

Esempi

Esempio 1. Esempio di uso di sqlite_open()

<?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) { 
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result)); 
} else {
    die($sqliteerror);
}
?>

Note

Suggerimento: Sui sistemi Unix, SQLite è sensibile agli script che utilizzano la chiamata di sistema fork(). Se si sta utilizzando un tale script, si raccomanda di chiudere la connessione prima dell'esecuzione del fork, e quindi ri-aprirlo nel processo figlio/padre. Per maggiori informazioni su questo particolare vedere L'interfaccia C alla libreria SQLite nella sezione intitolata Multi-Threading e SQLite.

Suggerimento: Si raccomanda di non utilizzare database SQLite su partizioni montate via NFS. Poiché è noto che NFS non è affidabile con i lock, può capitare che si riesca neppure ad aprire il database, o, se ci si riesce, il comportamento dei lock può essere indefinito.

Nota: A partire dalla versione 2.8.2 della libreria SQLite, si può specificare :memory: come valore per il parametro filename in modo da creare database che risiedano soltanto in memoria. Principalmente questo è utile per le elaborazioni temporanee, poiché il database in memoria sarà distrutto non appena il processo termina. Può anche essere utilizzato in coppia con l'istruzione SQL ATTACH DATABASE per caricare altri database in modo da potere muovere i dati tra di loro.

Nota: SQLite sensibile alla modalità sicura e a open_basedir.

sqlite_popen

(PHP 5)

sqlite_popen --  Apre una connessione persistente ad un database SQLite e crea il database se non esiste

Descrizione

resource sqlite_popen ( string filename [, int mode [, string &error_message]] )

Questa funzione agisce in modo identico a sqlite_open() tranne che utilizza il meccanismo delle risorse persistenti insito in PHP. Per maggiori informazioni sui parametri leggere la pagina del manuale relativa a sqlite_open().

sqlite_popen() per prima cosa verifica se esiste già un connessione persistente per il dato filename. Se ne trova una restituisce quella altrimenti ne apre una nuova.

Il beneficio di questo approccio è che si evita il costo, in termini di performance, di dovere ri-leggere lo schema del database e degli indici ad ogni pagina servita dal server web (qualsiasi SAPI tranne CGI o CLI).

Nota: Se si utilizza la connessione persistente, ed il sottostante database viene aggiornato da un processo che gira in background (ad esempio via crontab), e questo processo ricrea il database riscrivendolo (ad esempio cancellandolo e scrivendone uno nuovo, oppure movendo la nuova versione sulla vecchia), si possono manifestare comportamenti indefiniti quando si torna ad utilizzare la connessione persistente verso il vecchio database.

Per evitare questa situazione, occorre che il processo in background apra lo stesso database ed esegua gli aggiornamenti mediante transazioni.

Elenco dei parametri

filename

Nome del database SQLite. Se il file non esiste, SQLite tenterà di crearlo. Il PHP deve avere i permessi di scrittura sul file se si desidera inserire dei dati o modficare lo schema del database, o creare il database se non esiste.

mode

Specifica la modalità del file. E' inteso per essere utilizzato per l'apertura del file in modalità read-only. Attualmente questo parametro viene ignorato da SQLite. Per default la modalità di apertura è il valore ottale 0666, ed è questa l'impostazione raccomandata.

error_message

Passato per riferimento, è impostato per contenere un messaggio descrittivo di errore nel caso non si riesca ad aprire il database a causa di un errore.

Valori restituiti

Restituisce una risorsa (database handle) se ha successo, oppure FALSE se si verifica un errore.

sqlite_prev

(PHP 5)

sqlite_prev

(no version information, might be only in CVS)

SQLiteResult->prev -- Si posiziona sulla riga precedente di un set di risultati

Descrizione

bool sqlite_prev ( resource result )

Versione ad oggetti (metodo):

class SQLiteResult {

bool prev ( void )

}

sqlite_prev() si sposta alla riga precedente di result.

Elenco dei parametri

result

Risorsa risultato di SQLite. Questo parametro non è richiesto quando di usa la versione ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

Valori restituiti

La funzione restituisce TRUE se ha successo, oppure FALSE se non esiste un record precedente.

sqlite_query

(PHP 5)

sqlite_query

(no version information, might be only in CVS)

SQLiteDatabase->query -- Esegue una query su un database e restituisce un puntatore al set di risultati

Descrizione

resource sqlite_query ( resource dbhandle, string query )

resource sqlite_query ( string query, resource dbhandle )

Versione ad oggetti (metodo):

class SQLiteDatabase {

SQLiteResult query ( string query )

}

Esegue le istruzioni SQL indicate in query sul collegamento al database dato.

Elenco dei parametri

query

Query da eseguire.

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Valori restituiti

Questa funzione restituisce un handle o FALSE se si verifica un errore. Nei casi di query che restituiscano delle righe, l'handle restituito dalla funzione può essere utilizzato nelle funzioni sqlite_fetch_array() e sqlite_seek().

A prescindere dal tipo di query, questa funzione restituisce FALSE se la query fallisce.

sqlite_query() restituisce un puntatore ad un set di risultati bufferizzato e navigabile. Ciò è ragionevole per piccole query dove si ha la necessità di accedere alle righe in ordine casuale. I risultati bufferizzati allocano la memoria necessaria per contenere tutte le righe restituite dalla query, che non saranno restituite fino a che non saranno richieste. Se si ha soltanto la necessità di accedere alle righe in modo sequenziale, si raccomanda l'uso della funzione sqlite_unbuffered_query().

Note

Avvertimento

SQLite esegue molteplici query separate da punto e virgola, pertanto si possono eseguire dei batch SQL che possono essere caricati da file esterni o inseriti nello script. Tuttavia ciò è valido solo quando non è utilizzato il risultato della funzione, se, al contrario, viene utilizzato, verrà eseguito solo la prima query. Funzioni tipo sqlite_exec() eseguono sempre molteplici query SQL.

Quando si eseguono query molteplici, il valore restituito può essere FALSE se vi è un errore, oppure indefinito in caso contrario ( può essere TRUE oppure può restituire un handle ad un set di risultati).

sqlite_rewind

(PHP 5)

sqlite_rewind

(no version information, might be only in CVS)

SQLiteResult->rewind -- Si posiziona sulla prima riga

Descrizione

bool sqlite_rewind ( resource result )

Versione ad oggetti (metodo):

class SQLiteResult {

bool rewind ( void )

}

sqlite_rewind() si posiziona sulla prima riga del set di risultati.

Elenco dei parametri

result

Risorsa risultato di SQLite. Questo parametro non è richiesto nella versione ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

Valori restituiti

La funzione restituisce FALSE se non vi sono righe nel set di risultati, TRUE in caso contrario.

sqlite_seek

(PHP 5)

sqlite_seek

(no version information, might be only in CVS)

SQLiteResult->seek -- Posizionamento su una data riga di un set di risultati bufferizzato

Descrizione

bool sqlite_seek ( resource result, int rownum )

Versione ad oggetti (metodo):

class SQLiteResult {

bool seek ( int rownum )

}

sqlite_seek() si posiziona sulla riga indicata dal parametro rownum.

Elenco dei parametri

result

Risorsa risultato di SQLite. Questo parametro non è richiesto nella versione ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

rownum

Il numero ordinale di riga da cercare. I numeri di riga partono da zero ( 0 indica la prima riga).

Nota: This function cannot be used with unbuffered result handles.

Valori restituiti

La funzione restituisce FALSE se la riga richiesta non esiste, oppure TRUE.

sqlite_single_query

(PHP 5)

sqlite_single_query

(no version information, might be only in CVS)

SQLiteDatabase->singleQuery --  Esegue una query e restituisce o una matrice per ogni singola colonna o il valore della prima riga

Descrizione

mixed sqlite_single_query ( resource db, string query [, bool first_row_only [, bool decode_binary]] )

Versione ad oggetti (metodo):

class SQLiteDatabase {

mixed singleQuery ( string query [, bool first_row_only [, bool decode_binary]] )

}

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

sqlite_udf_decode_binary

(PHP 5)

sqlite_udf_decode_binary -- Decodifica dati binari passati come parametri in UDF

Descrizione

string sqlite_udf_decode_binary ( string data )

La funzione sqlite_udf_decode_binary() decodifica i dati binari in modo che possano essere utilizzati come parametri per sqlite_udf_encode_binary() o sqlite_escape_string().

Occorre eseguire questa funzione sui parametri passati agli UDF se questi devono gestire dati binari, poiché la codifica dei dati binari utilizzata dal PHP nasconde il contenuto.

Il PHP non esegue questa codifica/decodifica in automatico, avrebbe impatti negativi sulle performance.

Esempi

Esempio 1. Esempio di una funzione di aggregazione lunghezza_massima binary-safe

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = sqlite_open(':memory:');
sqlite_query($db, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($db, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string) 
{
    $string = sqlite_udf_decode_binary($string);
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context) 
{
    return $context;
}

sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));

?>

sqlite_udf_encode_binary

(PHP 5)

sqlite_udf_encode_binary -- Codifica i dati binari prima di restituirli da un UDF

Descrizione

string sqlite_udf_encode_binary ( string data )

sqlite_udf_encode_binary() applica la decofica dei dati binari al parametro data in modo che possa essere restituito dalle query (dato che la sottostante libreria libsqlite API non è binary safe).

Se esiste una possibilità che i dati possano essere binai (ad esempio contengono caratteri tipo NUL, oppure iniziano con il carattere 0x01), occorre eseguire questa funzione per codificare il valore da restituire all'UDF.

Il PHP non esegue questa codifica/decodifica in automatico, avrebbe impatti negativi sulle performance.

Nota: Non utilizzare sqlite_escape_string() per quitare stringhe restituite tramite UDF poiché porta ad avere una quotazione doppia. Utilizzare sqlite_udf_encode_binary()!

sqlite_unbuffered_query

(PHP 5)

sqlite_unbuffered_query

(no version information, might be only in CVS)

SQLiteDatabase->unbufferedQuery -- Esegue una query senza scaricare e bufferizzare i dati

Descrizione

resource sqlite_unbuffered_query ( resource dbhandle, string query )

resource sqlite_unbuffered_query ( string query, resource dbhandle )

Versione ad oggetti (metodo):

class SQLiteDatabase {

SQLiteUnbuffered unbufferedQuery ( string query )

}

sqlite_unbuffered_query() è simile a sqlite_query() tranne che i risultati sono restituiti in modo sequenziale una riga dopo l'altra, permettendo solo la lettura del record successivo.

Questa funzione è l'ideale per generare oggetti tipo tavole HTML in cui occorre processare una riga alla volta e non occorre muoversi a caso tra le righe.

Nota: Funzioni tipo sqlite_seek(), sqlite_rewind(), sqlite_next(), sqlite_current(), e sqlite_num_rows() non sono applicabili agli handles restituiti da sqlite_unbuffered_query().

Elenco dei parametri

query

La query da eseguire.

dbhandle

Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Valori restituiti

Resituisce un puntatore ad un risultato oppure FALSE.

sqlite_unbuffered_query() restituisce un set di risultati sequenzialeche può essere utilizzato per leggere una riga dopo l'altra.

Vedere anche:

sqlite_query()

sqlite_valid

(PHP 5)

sqlite_valid

(no version information, might be only in CVS)

SQLiteResult->valid

(no version information, might be only in CVS)

SQLiteUnbuffered->valid -- Indica se una o più righe sono disponibili

Descrizione

bool sqlite_valid ( resource result )

Versione ad oggetti (metodo):

class SQLiteResult {

bool valid ( void )

}class SQLiteUnbuffered {

bool valid ( void )

}

Verifica se una o più righe sono disponibili nel dato set di risultati.

Elenco dei parametri

result

Risorsa risultato di SQLite. Questo parametro non è richiesto quando la funzione viene usata ad oggetti.

Nota: This function cannot be used with unbuffered result handles.

Valori restituiti

Restituisce TRUE se vi sono più righe disponibili da result, oppure FALSE in caso contrario.

CXLII. SQLite Functions (PDO_SQLITE)

Introduzione

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

In PHP 5.1, the SQLite extension also provides a driver for SQLite 2 databases; while it is not technically a part of the PDO_SQLITE driver, it behaves similarly, so it is documented alongside it. The SQLite 2 driver for PDO is provided primarily to make it easier to import legacy sqlite 2 database files into an application that uses the faster, more efficient sqlite 3 driver. As a result, the SQLite 2 driver is not as feature-rich as the SQLite 3 driver.

Sommario
PDO_SQLITE DSN -- Connecting to SQLite databases
PDO::sqliteCreateAggregate --  Registers an aggregating User Defined Function for use in SQL statements
PDO::sqliteCreateFunction --  Registers a User Defined Function for use in SQL statements

PDO_SQLITE DSN

(no version information, might be only in CVS)

PDO_SQLITE DSN -- Connecting to SQLite databases

Descrizione

The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:

DSN prefix (SQLite 3)

The DSN prefix is sqlite:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append memory: to the DSN prefix.

DSN prefix (SQLite 2)

The SQLite extension in PHP 5.1 provides a PDO driver that supports accessing and creating SQLite 2 databases. This enables you to access databases you may have created with the SQLite extension in previous versions of PHP.

Nota: The sqlite2 driver is only available in PHP 5.1 if you have enabled both PDO and ext/sqlite. It is not currently available via PECL.

The DSN prefix for connecting to SQLite 2 databases is sqlite2:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append memory: to the DSN prefix.

Esempi

Esempio 1. PDO_SQLITE DSN examples

The following examples show PDO_SQLITE DSN for connecting to SQLite databases:
sqlite:/opt/databases/mydb.sq3
sqlite::memory:
sqlite2:/opt/databases/mydb.sq2
sqlite2::memory:

PDO::sqliteCreateAggregate

(no version information, might be only in CVS)

PDO::sqliteCreateAggregate --  Registers an aggregating User Defined Function for use in SQL statements

Descrizione

bool PDO::sqliteCreateAggregate ( string function_name, callback step_func, callback finalize_func [, int num_args] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

PDO::sqliteCreateAggregate() is similar to PDO::sqliteCreateFunction() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this function and PDO::sqliteCreateFunction() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Elenco dei parametri

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set.

finalize_func

Callback function to aggregate the "stepped" data from each row.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Esempi

Esempio 1. max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
    $insert->execute(array($str));
}
$insert = null;

function max_len_step(&$context, $string) 
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context) 
{
    return $context;
}

$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Suggerimento: It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Suggerimento: You can use PDO::sqliteCreateFunction() and PDO::sqliteCreateAggregate() to override SQLite native SQL functions.

Nota: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

Vedere anche:

PDO::sqliteCreateFunction()
sqlite_create_function()
sqlite_create_aggregate()

PDO::sqliteCreateFunction

(no version information, might be only in CVS)

PDO::sqliteCreateFunction --  Registers a User Defined Function for use in SQL statements

Descrizione

bool PDO::sqliteCreateFunction ( string function_name, callback callback [, int num_args] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

PDO::sqliteCreateFunction() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Elenco dei parametri

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Nota: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Esempi

Esempio 1. PDO::sqliteCreateFunction() example

<?php
function md5_and_reverse($string) 
{
    return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach() loop after you have queried for the data.

Suggerimento: You can use PDO::sqliteCreateFunction() and PDO::sqliteCreateAggregate() to override SQLite native SQL functions.

Nota: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

Vedere anche:

PDO::sqliteCreateAggregate()
sqlite_create_function()
sqlite_create_aggregate()

CXLIII. Secure Shell2 Functions

Introduzione

Bindings to the libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.


Installazione

Windows binaries may be found at http://snaps.php.net/. To install, download php_ssh2.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_ssh2.dll to your php.ini and restarting your webserver.

extension_dir=c:/php5/exts/
extension=php_ssh2.dll

Linux, BSD, and other *nix variants can be compiled using the following steps:

  • Download and install OpenSSL. If you install OpenSSL via your distribution's packaging system be sure to install the development libraries as well. This will typically be a package named openssl-dev, openssl_devel, or some variation thereof.

  • Download and install libssh2. Typically this means executing the following command from the libssh2 source tree. ./configure && make all install.

  • Run the pear installer for PECL/ssh2: pear install ssh2

  • Copy ssh2.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.

  • Add extension=ssh2.so to your php.ini

  • Restart your webserver to reload your php.ini settings.

Development Versions: There are currently no stable versions of PECL/ssh2, to force installation of the beta version of PECL/ssh2 execute: pear install ssh2-beta

Compiling PECL/ssh2 without using the PEAR command: Rather than using pear install ssh2 to automatically download and install PECL/ssh2, you may download the tarball from PECL. From the root of the unpacked tarball, run: phpize && ./configure --with-ssh2 && make to generate ssh2.so. Once built, continue the installation from step 4 above.

Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/ssh2.

Nota: You will need version 0.4 or greater of the libssh2 library (possibly higher, see release notes).


Costanti predefinite

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.

SSH2_FINGERPRINT_MD5 (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.

SSH2_FINGERPRINT_SHA1 (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.

SSH2_FINGERPRINT_HEX (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.

SSH2_FINGERPRINT_RAW (integer)

Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.

SSH2_TERM_UNIT_CHARS (integer)

Flag to ssh2_shell() specifying that width and height are provided as character sizes.

SSH2_TERM_UNIT_PIXELS (integer)

Flag to ssh2_shell() specifying that width and height are provided in pixel units.

SSH2_DEFAULT_TERM_WIDTH (integer)

Default terminal width requested by ssh2_shell().

SSH2_DEFAULT_TERM_HEIGHT (integer)

Default terminal height requested by ssh2_shell().

SSH2_DEFAULT_TERM_UNIT (integer)

Default terminal units requested by ssh2_shell().

SSH2_STREAM_STDIO (integer)

Flag to ssh2_fetch_stream() requesting STDIO subchannel.

SSH2_STREAM_STDERR (integer)

Flag to ssh2_fetch_stream() requesting STDERR subchannel.

SSH2_DEFAULT_TERMINAL (string)

Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().

Sommario
ssh2_auth_hostbased_file --  Authenticate using a public hostkey
ssh2_auth_none --  Authenticate as "none"
ssh2_auth_password --  Authenticate over SSH using a plain password
ssh2_auth_pubkey_file --  Authenticate using a public key
ssh2_connect --  Connect to an SSH server
ssh2_exec --  Execute a command on a remote server
ssh2_fetch_stream --  Fetch an extended data stream
ssh2_fingerprint --  Retreive fingerprint of remote server
ssh2_methods_negotiated --  Return list of negotiated methods
ssh2_publickey_add --  Add an authorized publickey
ssh2_publickey_init --  Initialize Publickey subsystem
ssh2_publickey_list --  List currently authorized publickeys
ssh2_publickey_remove --  Remove an authorized publickey
ssh2_scp_recv --  Request a file via SCP
ssh2_scp_send --  Send a file via SCP
ssh2_sftp_lstat --  Stat a symbolic link
ssh2_sftp_mkdir --  Create a directory
ssh2_sftp_readlink --  Return the target of a symbolic link
ssh2_sftp_realpath --  Resolve the realpath of a provided path string
ssh2_sftp_rename --  Rename a remote file
ssh2_sftp_rmdir --  Remove a directory
ssh2_sftp_stat --  Stat a file on a remote filesystem
ssh2_sftp_symlink --  Create a symlink
ssh2_sftp_unlink --  Delete a file
ssh2_sftp --  Initialize SFTP subsystem
ssh2_shell --  Request an interactive shell
ssh2_tunnel --  Open a tunnel through a remote server

ssh2_auth_hostbased_file

(PECL)

ssh2_auth_hostbased_file --  Authenticate using a public hostkey

Description

bool ssh2_auth_hostbased_file ( resource session, string username, string hostname, string pubkeyfile, string privkeyfile [, string passphrase [, string local_username]] )

Authenticate using a public hostkey read from a file. If privkeyfile is encrypted (which it should be), the passphrase must be provided. If local_username is omitted, then the value for username will be used for it.

Esempio 1. Authentication using a public hostkey

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_hostbased_file($connection, 'remoteusername', 'myhost.example.com',
                             '/usr/local/etc/hostkey_rsa.pub',
                             '/usr/local/etc/hostkey_rsa', 'secret',
                             'localusername')) {
  echo "Public Key Hostbased Authentication Successful\n";
} else {
  die('Public Key Hostbased Authentication Failed');
}
?>

Nota: ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7

ssh2_auth_none

(PECL)

ssh2_auth_none --  Authenticate as "none"

Description

mixed ssh2_auth_none ( resource session, string username )

Attempt "none" authentication which usually will (and should) fail. As part of the failure, this function will return an array of accepted authentication methods. If the server does accept "none" as an authentication method for username, this function will simply return TRUE.

Esempio 1. Using ssh2_auth_none() to retreive a list of authentication methods.

<?php
$connection = ssh2_connect('shell.example.com', 22);

$auth_methods = ssh2_auth_none($connection, 'user');

if (in_array('password', $auth_methods)) {
  echo "Server supports password based authentication\n";
}
?>

ssh2_auth_password

(PECL)

ssh2_auth_password --  Authenticate over SSH using a plain password

Description

bool ssh2_auth_password ( resource session, string username, string password )

Authenticate over SSH using a plain password

Esempio 1. Authenticating with a password

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>

ssh2_auth_pubkey_file

(PECL)

ssh2_auth_pubkey_file --  Authenticate using a public key

Description

bool ssh2_auth_pubkey_file ( resource session, string username, string pubkeyfile, string privkeyfile [, string passphrase] )

Authenticate using a public key read from a file. If privkeyfile is encrypted (which it should be), the passphrase must be provided.

Esempio 1. Authentication using a public key

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'username',
                          '/home/username/.ssh/id_rsa.pub',
                          '/home/username/.ssh/id_rsa', 'secret')) {
  echo "Public Key Authentication Successful\n";
} else {
  die('Public Key Authentication Failed');
}
?>

ssh2_connect

(PECL)

ssh2_connect --  Connect to an SSH server

Description

resource ssh2_connect ( string host [, int port [, array methods [, array callbacks]]] )

Establish a connection to a remote SSH server and return a resource on success, FALSE on error.

methods may be an associative array with up to four parameters as described below.

Tabella 1. methods may be an associative array with any or all of the following parameters.

IndexMeaningSupported Values*
kex List of key exchange methods to advertise, comma separated in order of preference. diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1
hostkey List of hostkey methods to advertise, come separated in order of preference. ssh-rsa and ssh-dss
client_to_server Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.  
server_to_client Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.  

* - Supported Values are dependent on methods supported by underlying library. See libssh2 documentation for additional information.

Tabella 2. client_to_server and server_to_client may be an associative array with any or all of the following parameters.

IndexMeaningSupported Values*
cryptList of crypto methods to advertise, comma separated in order of preference. rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none**
compList of compression methods to advertise, comma separated in order of preference. zlib and none
macList of MAC methods to advertise, come separated in order of preference. hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Crypt and MAC method "none": For security reasons, none is disabled by the underlying libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.

Tabella 3. callbackss may be an associative array with any or all of the following parameters.

IndexMeaningPrototype
ignore Name of function to call when an SSH2_MSG_IGNORE packet is received void ignore_cb($message)
debug Name of function to call when an SSH2_MSG_DEBUG packet is received void debug_cb($message, $language, $always_display)
macerror Name of function to call when a packet is received but the message authentication code failed. If the callback returns TRUE, the mismatch will be ignored, otherwise the connection will be terminated. bool macerror_cb($packet)
disconnect Name of function to call when an SSH2_MSG_DISCONNECT packet is received void disconnect_cb($reason, $message, $language)

Esempio 1. Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.

<?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n",
         $reason, $message);
}

$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
    'crypt' => '3des-cbc',
    'comp' => 'none'),
  'server_to_client' => array(
    'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?>

Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.

See Also: ssh2_fingerprint(), ssh2_auth_none(), ssh2_auth_password(), and ssh2_auth_pubkey_file()

ssh2_exec

(PECL)

ssh2_exec --  Execute a command on a remote server

Description

resource ssh2_exec ( resource session, string command [, string pty [, array env [, int width [, int height [, int width_height_type]]]]] )

Execute a command at the remote end and allocate a channel for it. Returns a stream on success or FALSE on failure.

Esempio 1. Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>

See Also: ssh2_connect(), ssh2_shell(), and ssh2_tunnel()

ssh2_fetch_stream

(PECL)

ssh2_fetch_stream --  Fetch an extended data stream

Description

resource ssh2_fetch_stream ( resource channel, int streamid )

Fetches an alternate substream associated with an SSH2 channel stream identified by streamid. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).

Esempio 1. Opening a shell and retrieving the stderr stream associated with it.

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?>

See Also: ssh2_shell(), ssh2_exec(), and ssh2_connect()

ssh2_fingerprint

(PECL)

ssh2_fingerprint --  Retreive fingerprint of remote server

Description

string ssh2_fingerprint ( resource session [, int flags] )

Returns a server hostkey hash from an active session. Defaults to MD5 fingerprint encoded as ASCII hex values.

flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW. Defaults to SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX.

Esempio 1. Checking the fingerprint against a known value

<?php
$known_host = '6F89C2F0A719B30CC38ABDF90755F2E4';

$connection = ssh2_connect('shell.example.com', 22);

$fingerprint = ssh2_fingerprint($connection,
               SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
  die("HOSTKEY MISMATCH!\n" .
      "Possible Man-In-The-Middle Attack?");
}
?>

ssh2_methods_negotiated

(PECL)

ssh2_methods_negotiated --  Return list of negotiated methods

Description

array ssh2_methods_negotiated ( resource session )

Returns list of negotiated methods.

Esempio 1. Determining what methods were negotiated

<?php
$connection = ssh2_connect('shell.example.com', 22);
$methods = ssh2_methods_negotiated($connection);

echo "Encryption keys were negotiated using: {$methods['kex']}\n";
echo "Server identified using an {$methods['hostkey']} with ";
echo "fingerprint: " . ssh2_fingerprint($connection) . "\n";

echo "Client to Server packets will use methods:\n";
echo "\tCrypt: {$methods['client_to_server']['crypt']}\n";
echo "\tComp: {$methods['client_to_server']['comp']}\n";
echo "\tMAC: {$methods['client_to_server']['mac']}\n";

echo "Server to Client packets will use methods:\n";
echo "\tCrypt: {$methods['server_to_client']['crypt']}\n";
echo "\tComp: {$methods['server_to_client']['comp']}\n";
echo "\tMAC: {$methods['server_to_client']['mac']}\n";

?>

See Also: ssh2_connect()

ssh2_publickey_add

(PECL)

ssh2_publickey_add --  Add an authorized publickey

Descrizione

bool ssh2_publickey_add ( resource pkey, string algoname, string blob [, bool overwrite [, array attributes]] )

Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Elenco dei parametri

pkey

Publickey Subsystem resource created by ssh2_publickey_init().

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

overwrite

If the specified key already exists, should it be overwritten?

attributes

Associative array of attributes to assign to this public key. Refer to ietf-secsh-publickey-subsystem for a list of supported attributes. To mark an attribute as mandatory, preceed its name with an asterix. If the server is unable to support an attribute marked mandatory, it will abort the add process.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Adding a publickey with ssh2_publickey_add()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'password');
$pkey = ssh2_publickey_init($ssh2);

$keyblob = base64_decode('
AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5PTrLRdjNONxXH1tVFGn0
Bd26BF0aCP9qyJRlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xj
zaLpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VEHYckxQ16CjSTibI5X
69GmnYC9PNqEYq/1TP+HF10=');

ssh2_publickey_add($ssh2, 'ssh-rsa', $keyblob, false, array('comment'=>"John's Key"));
?>

ssh2_publickey_init

(PECL)

ssh2_publickey_init --  Initialize Publickey subsystem

Descrizione

resource ssh2_publickey_init ( resource session )

Request the Publickey subsystem from an already connected SSH2 server.

The publickey subsystem allows an already connected and authenticated client to manage the list of authorized public keys stored on the target server in an implementation agnostic manner. If the remote server does not support the publickey subsystem, the ssh2_publickey_init() function will return FALSE.

Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Valori restituiti

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods.

ssh2_publickey_list

(PECL)

ssh2_publickey_list --  List currently authorized publickeys

Descrizione

array ssh2_publickey_list ( resource pkey )

Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Elenco dei parametri

pkey

Publickey Subsystem resource

Valori restituiti

Returns a numericly indexed array of keys, each of which is an associative array containing: name, blob, and attrs elements.

Tabella 1. Publickey elements

Array KeyMeaning
nameName of algorithm used by this publickey, for example: ssh-dss or ssh-rsa.
blobPublickey blob as raw binary data.
attrsAttributes assigned to this publickey. The most common attribute, and the only one supported by publickey version 1 servers, is comment, which may be any freeform string.

Esempi

Esempio 1. Listing authorized keys with ssh2_publickey_list()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'secret');
$pkey = ssh2_publickey_init($ssh2);

$list = ssh2_publickey_list($pkey);

foreach($list as $key) {
  echo "Key: {$key['name']}\n";
  echo "Blob: " . chunk_split(base64_encode($key['blob']), 40, "\n") . "\n";
  echo "Comment: {$key['attrs']['comment']}\n\n";
}
?>

Il precedente esempio visualizzerà:

Key: ssh-rsa
Blob: AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5P
TrLRdjNONxXH1tVFGn0Bd26BF0aCP9qyJRlvdJ3j
4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xjza
Lpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VE
HYckxQ16CjSTibI5X69GmnYC9PNqEYq/1TP+HF10
Comment: John's Key

Key: ssh-rsa
Blob: AAAAB3NzaHVt6VqSGd5C1yc2EAAAABIwA232dnJA
AIEA5HVt6VqSGd5PTrLRdjNONxX/1TP+HF1HVt6V
qSGd50H1tVFGn0BB3NzaC1yc2EAd26BF0aCP9qyJ
RlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26HVt6Vq
SGd5sDHwfL351xjzaLpipu\BGB3NzaC1yc2EA/1T
Comment: Alice's Key

ssh2_publickey_remove

(PECL)

ssh2_publickey_remove --  Remove an authorized publickey

Descrizione

bool ssh2_publickey_remove ( resource pkey, string algoname, string blob )

Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.

Elenco dei parametri

pkey

Publickey Subsystem Resource

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ssh2_scp_recv

(PECL)

ssh2_scp_recv --  Request a file via SCP

Description

bool ssh2_scp_recv ( resource session, string remote_file, string local_file )

Copy a file from the remote server to the local filesystem using the SCP protocol.

Esempio 1. Downloading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?>

See Also: ssh2_scp_send(), and copy()

ssh2_scp_send

(PECL)

ssh2_scp_send --  Send a file via SCP

Description

bool ssh2_scp_send ( resource session, string local_file, string remote_file [, int create_mode] )

Copy a file from the local filesystem to the remote server using the SCP protocol. The file will be created with the mode specified by create_mode.

Esempio 1. Uploading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>

See Also: ssh2_scp_recv(), and copy()

ssh2_sftp_lstat

(PECL)

ssh2_sftp_lstat --  Stat a symbolic link

Description

array ssh2_sftp_lstat ( resource sftp, string path )

Stats a symbolic link on the remote filesystem without following the link. This function is similar to using the lstat() function with the ssh2.sftp:// wrapper in PHP5 and returns the same values. See the documentation for stat() for details on the values which may be returned.

Esempio 1. Stating a symbolic link via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_lstat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

See Also: ssh2_sftp_stat(), lstat(), and stat()

ssh2_sftp_mkdir

(PECL)

ssh2_sftp_mkdir --  Create a directory

Description

bool ssh2_sftp_mkdir ( resource sftp, string dirname [, int mode [, bool recursive]] )

Creates a directory on the remote file server with permissions set to mode. If recursive is TRUE any parent directories required for dirname will be automatically created as well. This function is similar to using mkdir() with the ssh2.sftp:// wrapper.

Esempio 1. Creating a directory on a remote server

<?php
$connection = ssh2_connet('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_mkdir($sftp, '/home/username/newdir');
/* Or:  mkdir("ssh2.sftp://$sftp/home/username/newdir"); */
?>

See Also: mkdir(), and ssh2_sftp_rmdir()

ssh2_sftp_readlink

(PECL)

ssh2_sftp_readlink --  Return the target of a symbolic link

Description

string ssh2_sftp_readlink ( resource sftp, string link )

Returns the target of a symbolic link.

Esempio 1. Reading a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$target = ssh2_sftp_readlink($sftp, '/tmp/mysql.sock');
/* $target is now (e.g.): '/var/run/mysql.sock' */
?>

See Also: readlink(), and ssh2_sftp_symlink()

ssh2_sftp_realpath

(PECL)

ssh2_sftp_realpath --  Resolve the realpath of a provided path string

Description

string ssh2_sftp_realpath ( resource sftp, string filename )

Translates filename into the effective real path on the remote filesystem.

Esempio 1. Resolving a pathname

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd');
/* $realpath is now: '/etc/passwd' */
?>

See Also: realpath(), and ssh2_sftp_symlink() ssh2_sftp_readlink()

ssh2_sftp_rename

(PECL)

ssh2_sftp_rename --  Rename a remote file

Description

bool ssh2_sftp_rename ( resource sftp, string from, string to )

Renames a file on the remote filesystem.

Esempio 1. Renaming a file via sftp

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rename($sftp, '/home/username/oldname', '/home/username/newname');
?>

See Also: rename()

ssh2_sftp_rmdir

(PECL)

ssh2_sftp_rmdir --  Remove a directory

Description

bool ssh2_sftp_rmdir ( resource sftp, string dirname )

Removes a directory from the remote file server. This function is similar to using rmdir() with the ssh2.sftp:// wrapper.

Esempio 1. Removing a directory on a remote server

<?php
$connection = ssh2_connet('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rmdir($sftp, '/home/username/deltodel');
/* Or:  rmdir("ssh2.sftp://$sftp/home/username/dirtodel"); */
?>

See Also: rmdir(), and ssh2_sftp_mkdir()

ssh2_sftp_stat

(PECL)

ssh2_sftp_stat --  Stat a file on a remote filesystem

Description

array ssh2_sftp_stat ( resource sftp, string path )

Stats a file on the remote filesystem following any symbolic links. This function is similar to using the stat() function with the ssh2.sftp:// wrapper in PHP5 and returns the same values. See the documentation for stat() for details on the values which may be returned.

Esempio 1. Stating a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_stat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

See Also: ssh2_sftp_lstat(), lstat(), and stat()

ssh2_sftp_symlink

(PECL)

ssh2_sftp_symlink --  Create a symlink

Description

bool ssh2_sftp_symlink ( resource sftp, string target, string link )

Creates a symbolic link named link on the remote filesystem pointing to target.

Esempio 1. Creating a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?>

See Also: symlink(), and ssh2_sftp_readlink()

ssh2_sftp_unlink

(PECL)

ssh2_sftp_unlink --  Delete a file

Description

bool ssh2_sftp_unlink ( resource sftp, string filename )

Deletes a file on the remote filesystem

Esempio 1. Deleting a file

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?>

See Also: unlink()

ssh2_sftp

(PECL)

ssh2_sftp --  Initialize SFTP subsystem

Description

resource ssh2_sftp ( resource session )

Request the SFTP subsystem from an already connected SSH2 server.

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper.

Esempio 1. Opening a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
?>

See Also: ssh2_scp_send(), and ssh2_scp_recv()

ssh2_shell

(PECL)

ssh2_shell --  Request an interactive shell

Description

resource ssh2_shell ( resource session [, string term_type [, array env [, int width [, int height [, int width_height_type]]]]] )

Open a shell at the remote end and allocate a stream for it. term_type should correspond to one of the entries in the target system's /etc/termcap file and defaults to vanilla. env may be passed as an associative array of name/value pairs to set in the target environment.

width, and height define the width and height of the virtual terminal allocated for the shell process. width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Esempio 1. Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS);
?>

See Also: ssh2_exec(), ssh2_tunnel(), and ssh2_fetch_stream()

ssh2_tunnel

(PECL)

ssh2_tunnel --  Open a tunnel through a remote server

Description

resource ssh2_tunnel ( resource session, string host, int port )

Open a socket stream to an arbitrary host/port by way of the currently connected SSH server.

Esempio 1. Opening a tunnel to an arbitrary host

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa');

$tunnel = ssh2_tunnel($connection, '10.0.0.101', 12345);
?>

See Also: ssh2_connect(), and fsockopen()

CXLIV. Stream Functions

Introduzione

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Appendice M), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Capitolo 44. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Appendice M for a list of PHP builtin wrappers. If no wrapper is specified, the function default is used (typically file://).

  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Appendice M for a description of targets for builtin streams.


Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in Capitolo 44. To access the list of currently registered filters, use stream_get_filters().


Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found with the list of built-in wrappers (See Appendice M).

In addition, parameters may be set on a context using stream_context_set_params(). Currently the only context parameter supported by PHP is notification. The value of this parameter must be the name of a function to be called when an event occurs on a stream. The notification function called during an event should accept the following six parameters:

void my_notifier ( int notification_code, int severity, string message, int message_code, int bytes_transferred, int bytes_max )

notification_code and severity are numerical values which correspond to the STREAM_NOTIFY_* constants listed below. If a descriptive message is available from the stream, message and message_code will be populated with the appropriate values. The meaning of these values is dependent on the specific wrapper in use. bytes_transferred and bytes_max will be populated when applicable.


Installazione

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.


Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.


Costanti predefinite

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.

ConstantDescription
STREAM_FILTER_READ * Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE * Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
STREAM_FILTER_ALL * This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON *Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME *Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL *Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
STREAM_USE_PATHFlag indicating if the stream used the include path.
STREAM_REPORT_ERRORSFlag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT *Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT *Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT *Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND *Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN *Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE * A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED * There is no more data available on the stream.
STREAM_NOTIFY_FAILURE A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + Provides a ICMP socket.
STREAM_IPPROTO_IP + Provides a IP socket.
STREAM_IPPROTO_RAW + Provides a RAW socket.
STREAM_IPPROTO_TCP + Provides a TCP socket.
STREAM_IPPROTO_UDP + Provides a UDP socket.
STREAM_PF_INET + Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + Unix system internal protocols.
STREAM_SOCK_DGRAM + Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).

Nota: The constants marked with * are just available since PHP 5.0.0.

Nota: The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.


Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.


Esempi

Esempio 1. Using file_get_contents() to retrieve data from multiple sources

<?php
/* Read local file from /home/bar */
$localfile = file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>

Esempio 2. Making a POST request to an https server

<?php
/* Send POST request to https://secure.example.com/form_action.php
 * Include form elements named "foo" and "bar" with dummy values
 */

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, "$data\r\n");
fwrite($sock, "\r\n");

$headers = "";
while ($str = trim(fgets($sock, 4096)))
  $headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
  $body .= fgets($sock, 4096);

fclose($sock);
?>

Esempio 3. Writing data to a compressed file

<?php
/* Create a compressed file containing an arbitrarty string
 * File can be read back using compress.zlib stream or just
 * decompressed from the command line using 'gzip -d foo-bar.txt.gz'
 */
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?>

Sommario
stream_bucket_append --  Append bucket to brigade
stream_bucket_make_writeable --  Return a bucket object from the brigade for operating on
stream_bucket_new --  Create a new bucket for use on the current stream
stream_bucket_prepend --  Prepend bucket to brigade
stream_context_create -- Create a streams context
stream_context_get_default -- Retreive the default streams context
stream_context_get_options -- Retrieve options for a stream/wrapper/context
stream_context_set_option -- Sets an option for a stream/wrapper/context
stream_context_set_params -- Set parameters for a stream/wrapper/context
stream_copy_to_stream -- Copies data from one stream to another
stream_filter_append -- Attach a filter to a stream
stream_filter_prepend -- Attach a filter to a stream
stream_filter_register --  Register a stream filter implemented as a PHP class derived from php_user_filter
stream_filter_remove -- Remove a filter from a stream
stream_get_contents -- Reads remainder of a stream into a string
stream_get_filters -- Retrieve list of registered filters
stream_get_line -- Gets line from stream resource up to a given delimiter
stream_get_meta_data -- Retrieves header/meta data from streams/file pointers
stream_get_transports -- Retrieve list of registered socket transports
stream_get_wrappers -- Retrieve list of registered streams
stream_register_wrapper -- Alias of stream_wrapper_register()
stream_select -- Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
stream_set_blocking -- Set blocking/non-blocking mode on a stream
stream_set_timeout -- Set timeout period on a stream
stream_set_write_buffer -- Sets file buffering on the given stream
stream_socket_accept --  Accept a connection on a socket created by stream_socket_server()
stream_socket_client --  Open Internet or Unix domain socket connection
stream_socket_enable_crypto --  Turns encryption on/off on an already connected socket
stream_socket_get_name -- Retrieve the name of the local or remote sockets
stream_socket_pair --  Creates a pair of connected, indistinguishable socket streams
stream_socket_recvfrom -- Receives data from a socket, connected or not
stream_socket_sendto -- Sends a message to a socket, whether it is connected or not
stream_socket_server --  Create an Internet or Unix domain server socket
stream_wrapper_register -- Register a URL wrapper implemented as a PHP class
stream_wrapper_restore -- Restores a previously unregistered built-in wrapper
stream_wrapper_unregister -- Unregister a URL wrapper

stream_bucket_append

(PHP 5)

stream_bucket_append --  Append bucket to brigade

Descrizione

void stream_bucket_append ( resource brigade, resource bucket )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

stream_bucket_make_writeable

(PHP 5)

stream_bucket_make_writeable --  Return a bucket object from the brigade for operating on

Descrizione

object stream_bucket_make_writeable ( resource brigade )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

stream_bucket_new

(PHP 5)

stream_bucket_new --  Create a new bucket for use on the current stream

Descrizione

object stream_bucket_new ( resource stream, string buffer )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

stream_bucket_prepend

(PHP 5)

stream_bucket_prepend --  Prepend bucket to brigade

Descrizione

void stream_bucket_prepend ( resource brigade, resource bucket )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_create -- Create a streams context

Description

resource stream_context_create ( [array options] )

Creates and returns a stream context with any options supplied in options preset.

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value. It defaults to an empty array.

Esempio 1. Using stream_context_create()

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" . 
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

See also stream_context_set_option(), and Listing of supported wrappers with context options (Appendice M).

stream_context_get_default

(PHP 5 >= 5.1.0RC1)

stream_context_get_default -- Retreive the default streams context

Description

resource stream_context_get_default ( [array options] )

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Esempio 1. Using stream_context_get_default()

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" . 
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);


$alternate_opts = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
              "Content-length: " . strlen("baz=bomb"),
    'content'=>"baz=bomb"
  )
);

$default = stream_context_get_default($default_opts);
$alternate = stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
 * Using context options specified in $alternate_opts
 */
readfile('http://www.example.com', false, $alternate);

?>

See also stream_context_create(), and Listing of supported wrappers with context options (Appendice M).

stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5)

stream_context_get_options -- Retrieve options for a stream/wrapper/context

Description

array stream_context_get_options ( resource stream_or_context )

Returns an array of options on the specified stream or context.

stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_option -- Sets an option for a stream/wrapper/context

Description

bool stream_context_set_option ( resource stream_or_context, string wrapper, string option, mixed value )

bool stream_context_set_option ( resource stream_or_context, array options )

Sets an option on the specified context. value is set to option for wrapper

stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_params -- Set parameters for a stream/wrapper/context

Description

bool stream_context_set_params ( resource stream_or_context, array params )

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Tabella 1. Parameters

ParametersPurpose
notification Name of user-defined callback function to be called whenever a stream triggers a notification.

stream_copy_to_stream

(PHP 5)

stream_copy_to_stream -- Copies data from one stream to another

Descrizione

int stream_copy_to_stream ( resource source, resource dest [, int maxlength [, int offset]] )

Makes a copy of up to maxlength bytes of data from the current position (or from the offset position, if specified) in source to dest. If maxlength is not specified, all remaining content in source will be copied.

Elenco dei parametri

source

The source stream

dest

The destination stream

maxlength

Maximum bytes to copy

offset

The offset where to start to copy data

Valori restituiti

Returns the total count of bytes copied.

Log delle modifiche

VersioneDescrizione
5.1.0 Added the offset parameter

Esempi

Esempio 1. A stream_copy_to_stream() example

<?php
$src = fopen('http://www.example.com', 'r');
$dest1 = fopen('first1k.txt', 'w');
$dest2 = fopen('remainder.txt', 'w');

echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";

?>

Vedere anche:

copy()

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_append -- Attach a filter to a stream

Description

resource stream_filter_append ( resource stream, string filtername [, int read_write [, mixed params]] )

Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

As of PHP 5.1.0, this function returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove(). Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

Esempio 1. Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp = fopen("test.txt", "rw");

/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Write a simple string to the file
 * it will be ROT13 transformed on the
 * way out */
fwrite($fp, "This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
 * Had the filter been applied to the
 * read filter chain as well, we would see
 * the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
   ---------------

Guvf vf n grfg

 */
?>

When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.

Nota: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

See also stream_filter_register(), stream_filter_prepend(), and stream_get_filters().

stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_prepend -- Attach a filter to a stream

Description

resource stream_filter_prepend ( resource stream, string filtername [, int read_write [, mixed params]] )

Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

As of PHP 5.1.0, this function returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove(). Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.

Nota: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

See also stream_filter_register(), and stream_filter_append().

stream_filter_register

(PHP 5)

stream_filter_register --  Register a stream filter implemented as a PHP class derived from php_user_filter

Description

bool stream_filter_register ( string filtername, string classname )

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions as defined below. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

stream_filter_register() will return FALSE if the filtername is already defined.

int filter ( resource in, resource out, int &consumed, bool closing )

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()). in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered. out is a resource pointing to a second bucket brigade into which your modified buckets should be placed. consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket. If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE The filter method must return one of three values upon completion.

Return ValueMeaning
PSFS_PASS_ON Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) The filter experienced an unrecoverable error and cannot continue.

bool onCreate ( void )

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. Your implementation of this method should return FALSE on failure, or TRUE on success.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

PropertyContents
FilterClass->filternameA string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->paramsThe contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().

void onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialzed during onCreate this would be the time to destroy or dispose of them.

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

Esempio 1. Filter for capitalizing characters on foo-bar.txt stream

<?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
  function filter($in, $out, &$consumed, $closing) 
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket->data = strtoupper($bucket->data);
      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
} 

/* Register our filter with PHP */
stream_filter_register("strtoupper", "strtoupper_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtoupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");

?>

Il precedente esempio visualizzerà:

LINE1
WORD - 2
EASY AS 123

Esempio 2. Registering a generic filter class to match multiple filter names.

<?php

/* Define our filter class */
class string_filter extends php_user_filter {
  var $mode;

  function filter($in, $out, &$consumed, $closing) 
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      if ($this->mode == 1) {
        $bucket->data = strtoupper($bucket->data);
      } elseif ($this->mode == 0) {
        $bucket->data = strtolower($bucket->data);
      }

      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }

  function onCreate() 
  {
    if ($this->filtername == 'str.toupper') {
      $this->mode = 1;
    } elseif ($this->filtername == 'str.tolower') {
      $this->mode = 0;
    } else {
      /* Some other str.* filter was asked for,
         report failure so that PHP will keep looking */
      return false;
    }

    return true;
  }
} 

/* Register our filter with PHP */
stream_filter_register("str.*", "string_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened 
   We could alternately bind to str.tolower here */
stream_filter_append($fp, "str.toupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");
?>

Il precedente esempio visualizzerà:

LINE1
WORD - 2
EASY AS 123

See also stream_wrapper_register(), stream_filter_prepend(), and stream_filter_append().

stream_filter_remove

(PHP 5 >= 5.1.0RC1)

stream_filter_remove -- Remove a filter from a stream

Description

bool stream_filter_remove ( resource stream_filter )

Removes a stream filter previously added to a stream with stream_filter_prepend() or stream_filter_append(). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it.

Esempio 1. Dynamicly refiltering a stream

<?php
/* Open a test file for reading and writing */
$fp = fopen("test.txt", "rw");

$rot13_filter = stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);
fwrite($fp, "This is ");
stream_filter_remove($rot13_filter);
fwrite($fp, "a test\n");

rewind($fp);
fpassthru($fp);
fclose($fp);

/* Expected Output
   ---------------

Guvf vf a test

 */
?>

See also stream_filter_register(), stream_filter_append(), and stream_filter_prepend().

stream_get_contents

(PHP 5)

stream_get_contents -- Reads remainder of a stream into a string

Description

string stream_get_contents ( resource handle [, int maxlength [, int offset]] )

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

Elenco dei parametri

handle (resource)

A stream resource (e.g. returned from fopen())

maxlength (integer)

The maximum bytes to read. Defaults to -1 (read all the remaining buffer).

offset (integer)

Seek to the specified offset before reading. Added in PHP 5.1.0.

Valori restituiti

Returns a string, or FALSE on failure.

Esempi

Esempio 1. stream_get_contents() example

<?php

if ($stream = fopen('http://www.example.com', 'r')) {
    // print all the page starting at the offset 10
    echo stream_get_contents($stream, -1, 10);

    fclose($stream);
}


if ($stream = fopen('http://www.example.net', 'r')) {
    // print the first 5 bytes
    echo stream_get_contents($stream, 5);

    fclose($stream);
}

?>

Vedere anche:

fgets()
fread()
fpassthru()

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

stream_get_filters

(PHP 5)

stream_get_filters -- Retrieve list of registered filters

Description

array stream_get_filters ( void )

Returns an indexed array containing the name of all stream filters available on the running system.

Esempio 1. Using stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

Output will be similar to the following. Note: there may be more or fewer filters in your version of PHP.

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

See also stream_filter_register(), and stream_get_wrappers().

stream_get_line

(PHP 5)

stream_get_line -- Gets line from stream resource up to a given delimiter

Description

string stream_get_line ( resource handle, int length [, string ending] )

Returns a string of up to length bytes read from the file pointed to by handle. Reading ends when length bytes have been read, when the string specified by ending is found (which is not included in the return value), or on EOF (whichever comes first).

If an error occurs, returns FALSE.

This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.

See also fread(), fgets(), and fgetc().

stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5)

stream_get_meta_data -- Retrieves header/meta data from streams/file pointers

Description

array stream_get_meta_data ( resource stream )

Returns information about an existing stream. The stream can be any stream created by fopen(), fsockopen() and pfsockopen(). The result array contains the following items:

  • timed_out (bool) - TRUE if the stream timed out while waiting for data on the last call to fread() or fgets().

  • blocked (bool) - TRUE if the stream is in blocking IO mode. See stream_set_blocking().

  • eof (bool) - TRUE if the stream has reached end-of-file. Note that for socket streams this member can be TRUE even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

  • unread_bytes (int) - the number of bytes currently contained in the PHP's own internal buffer.

    Nota: You shouldn't use this value in a script.

The following items were added in PHP 4.3:

  • stream_type (string) - a label describing the underlying implementation of the stream.

  • wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Appendice M for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Appendice M for more information about wrappers and their wrapper data.

  • filters (array) - and array containing the names of any filters that have been stacked onto this stream. Documentation on filters can be found in the Filters appendix.

Nota: This function was introduced in PHP 4.3, but prior to this version, socket_get_status() could be used to retrieve the first four items, for socket based streams only.

In PHP 4.3 and later, socket_get_status() is an alias for this function.

Nota: This function does NOT work on sockets created by the Socket extension.

The following items were added in PHP 5.0:

  • mode (string) - the type of access required for this stream (see Table 1 of the fopen() reference)

  • seekable (bool) - whether the current stream can be seeked.

  • uri (string) - the URI/filename associated with this stream.

stream_get_transports

(PHP 5)

stream_get_transports -- Retrieve list of registered socket transports

Description

array stream_get_transports ( void )

Returns an indexed array containing the name of all socket transports available on the running system.

Esempio 1. Using stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

Output will be similar to the following. Note: there may be more or fewer transports in your version of PHP.

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

See also stream_get_filters(), and stream_get_wrappers().

stream_get_wrappers

(PHP 5)

stream_get_wrappers -- Retrieve list of registered streams

Description

array stream_get_wrappers ( void )

Returns an indexed array containing the name of all stream wrappers available on the running system.

Esempio 1. stream_get_wrappers() example

<?php
print_r(stream_get_wrappers());
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Esempio 2. Checking for the existence of a stream wrapper

<?php
// check for the existence of the bzip2 stream wrapper
if (in_array('compress.bzip2', stream_get_wrappers())) {
    echo 'compress.bzip2:// support enabled.';
} else {
    echo 'compress.bzip2:// support not enabled.';
}
?>

See also stream_wrapper_register().

stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5)

stream_register_wrapper -- Alias of stream_wrapper_register()

Description

This function is an alias of stream_wrapper_register(). This function is included for compatability with PHP 4.3.0 and PHP 4.3.1 only. stream_wrapper_register() should be used instead.

stream_select

(PHP 4 >= 4.3.0, PHP 5)

stream_select -- Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

Description

int stream_select ( array &read, array &write, array &except, int tv_sec [, int tv_usec] )

The stream_select() function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the socket_select() function except in that it acts on streams.

The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

The streams listed in the write array will be watched to see if a write will not block.

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Nota: When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

The tv_sec and tv_usec together form the timeout parameter, tv_sec specifies the number of seconds while tv_usec the number of microseconds. The timeout is an upper bound on the amount of time that stream_select() will wait before it returns. If tv_sec and tv_usec are both set to 0, stream_select() will not wait for data - instead it will return immediately, indicating the current status of the streams. If tv_sec is NULL stream_select() can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).

On success stream_select() returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).

Avvertimento

Using a timeout value of 0 allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time.

It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least 200000 microseconds will help reduce the CPU usage of your script.

Remember that the timeout value is the maximum time that will elapse; stream_select() will return as soon as the requested streams are ready for use.

You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:
<?php
/* Prepare the read array */
$read = array($stream1, $stream2);

if (false === ($num_changed_streams = stream_select($read, $write = NULL, $except = NULL, 0))) {
    /* Error handling */
} elseif ($num_changed_streams > 0) {
    /* At least on one of the streams something interesting happened */
}
?>

Nota: Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:
<?php
stream_select($r, $w, $e = NULL, 0);
?>

Nota: Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:
<?php
if (false === stream_select($r, $w, $e = NULL, 0)) {
    echo "stream_select() failed\n";
}
?>

Nota: If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

Nota: Windows compatibility: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.

See also stream_set_blocking().

stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5)

stream_set_blocking -- Set blocking/non-blocking mode on a stream

Description

bool stream_set_blocking ( resource stream, int mode )

If mode is 0, the given stream will be switched to non-blocking mode, and if 1, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

Nota: Prior to PHP 4.3, this function only worked on socket based streams. Since PHP 4.3, this function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

See also stream_select().

stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5)

stream_set_timeout -- Set timeout period on a stream

Description

bool stream_set_timeout ( resource stream, int seconds [, int microseconds] )

Sets the timeout value on stream, expressed in the sum of seconds and microseconds. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.

Esempio 1. stream_set_timeout() example

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {

    fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);

    $info = stream_get_meta_data($fp);
    fclose($fp);

    if ($info['timed_out']) {
        echo 'Connection timed out!';
    } else {
        echo $res;
    }

}
?>

Nota: As of PHP 4.3, this function can (potentially) work on any kind of stream. In PHP 4.3, socket based streams are still the only kind supported in the PHP core, although streams from other extensions may support this function.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

See also fsockopen() and fopen().

stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5)

stream_set_write_buffer -- Sets file buffering on the given stream

Description

int stream_set_write_buffer ( resource stream, int buffer )

Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. stream_set_write_buffer() sets the buffering for write operations on the given filepointer stream to buffer bytes. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

The function returns 0 on success, or EOF if the request cannot be honored.

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

Esempio 1. stream_set_write_buffer() example

<?php
$fp = fopen($file, "w");
if ($fp) {
  stream_set_write_buffer($fp, 0);
  fwrite($fp, $output);
  fclose($fp);
}
?>

See also fopen() and fwrite().

stream_socket_accept

(PHP 5)

stream_socket_accept --  Accept a connection on a socket created by stream_socket_server()

Description

resource stream_socket_accept ( resource server_socket [, float timeout [, string &peername]] )

Accept a connection on a socket previously created by stream_socket_server(). If timeout is specified, the default socket accept timeout will be overridden with the time specified in seconds. The name (address) of the client which connected will be passed back in peername if included and available from the selected transport.

peername can also be determined later using stream_socket_get_name().

If the call fails, it will return FALSE.

Avvertimento

This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

See also stream_socket_server(), stream_socket_get_name(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fwrite(), fclose(), feof(), and the Curl extension.

stream_socket_client

(PHP 5)

stream_socket_client --  Open Internet or Unix domain socket connection

Description

resource stream_socket_client ( string remote_socket [, int &errno [, string &errstr [, float timeout [, int flags [, resource context]]]]] )

Initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem. The optional timeout can be used to set a timeout in seconds for the connect system call. flags is a bitmask field which may be set to any combination of connection flags. Currently the selection of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

Nota: If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to stream_socket_client() only applies while connecting the socket.

stream_socket_client() returns a stream resource which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()).

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See Appendice O for a list of built in transports.

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Esempio 1. stream_socket_client() Example

<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?>
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

Esempio 2. Using UDP connection

<?php
$fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Avvertimento

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Nota: Nella specifica numerica degli indirizzi IPv6 (es. fe80::1) occorre racchiudere l'IP tra parentesi quadre. Ad esempio, tcp://[fe80::1]:80.

See also stream_socket_server(), stream_set_blocking(), stream_set_timeout(), stream_select(), fgets(), fgetss(), fwrite(), fclose(), feof(), and the Curl extension.

stream_socket_enable_crypto

(PHP 5 >= 5.1.0RC1)

stream_socket_enable_crypto --  Turns encryption on/off on an already connected socket

Description

mixed stream_socket_enable_crypto ( resource stream, bool enable [, int crypto_type [, resource session_stream]] )

When called with the crypto_type parameter, stream_socket_enable_crypto() will setup encryption on the stream using the specified method.

Valid values for crypto_type

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT

  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT

  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT

  • STREAM_CRYPTO_METHOD_TLS_CLIENT

  • STREAM_CRYPTO_METHOD_SSLv2_SERVER

  • STREAM_CRYPTO_METHOD_SSLv3_SERVER

  • STREAM_CRYPTO_METHOD_SSLv23_SERVER

  • STREAM_CRYPTO_METHOD_TLS_SERVER

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.

If this stream should be seeded with settings from an already established crypto enabled stream, pass that stream's resource variable in the fourth parameter.

Returns TRUE on success, FALSE if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).

Esempio 1. stream_socket_enable_crypto() Example

<?php
$fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30);
if (!$fp) {
  die("Unable to connect: $errstr ($errno)");
}
/* Turn on encryption for login phase */
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp, "USER god\r\n");
fwrite($fp, "PASS secret\r\n");
/* Turn off encryption for the rest */
stream_socket_enable_crypto($fp, false);
while ($motd = fgets($fp)) {
  echo $motd;
}
fclose($fp);
?>

Riferimento C, OpenSSL Functions, and Appendice O

stream_socket_get_name

(PHP 5)

stream_socket_get_name -- Retrieve the name of the local or remote sockets

Description

string stream_socket_get_name ( resource handle, bool want_peer )

Returns the local or remote name of a given socket connection. If want_peer is set to TRUE the remote socket name will be returned, if it is set to FALSE the local socket name will be returned.

See also stream_socket_accept().

stream_socket_pair

(PHP 5 >= 5.1.0RC1)

stream_socket_pair --  Creates a pair of connected, indistinguishable socket streams

Descrizione

array stream_socket_pair ( int domain, int type, int protocol )

stream_socket_pair() creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication).

Elenco dei parametri

domain

The protocol family to be used: STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX

type

The type of communication to be used: STREAM_SOCK_DGRAM, STREAM_SOCK_RAW, STREAM_SOCK_RDM, STREAM_SOCK_SEQPACKET or STREAM_SOCK_STREAM

protocol

The protocol to be used: STREAM_IPPROTO_ICMP, STREAM_IPPROTO_IP, STREAM_IPPROTO_RAW, STREAM_IPPROTO_TCP or STREAM_IPPROTO_UDP

Nota: Please consult the Streams constant list for further details on each constant.

Valori restituiti

Returns an array with the two socket resources on success, or FALSE on failure.

Esempi

Esempio 1. A stream_socket_pair() example

This example shows the basic usage of stream_socket_pair() in Inter-Process Comunication.

<?php

$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid     = pcntl_fork();

if ($pid == -1) {
     die('could not fork');

} else if ($pid) {
     /* parent */
    fclose($sockets[0]);

    fwrite($sockets[1], "child PID: $pid\n");
    echo fgets($sockets[1]);

    fclose($sockets[1]);

} else {
    /* child */
    fclose($sockets[1]);

    fwrite($sockets[0], "message from child\n");
    echo fgets($sockets[0]);

    fclose($sockets[0]);
}

?>

Il precedente esempio visualizzerà qualcosa simile a:

child PID: 1378
message from child

stream_socket_recvfrom

(PHP 5)

stream_socket_recvfrom -- Receives data from a socket, connected or not

Description

string stream_socket_recvfrom ( resource socket, int length [, int flags [, string &address]] )

The function stream_socket_recvfrom() accepts data from a remote socket up to length bytes. If address is provided it will be populated with the address of the remote socket.

The value of flags can be any combination of the following:

Tabella 1. possible values for flags

STREAM_OOB Process OOB (out-of-band) data.
STREAM_PEEK Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

Esempio 1. stream_socket_recvfrom() Example

<?php
/* Open a server socket to port 1234 on localhost */
$server = stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket = stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't comsume it. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n";

/* Get the exact same packet again, but remove it from the buffer this time. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n";

/* Close it up */
fclose($socket);
fclose($server);
?>

Nota: If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).

See also stream_socket_sendto(), stream_socket_client(), and stream_socket_server().

stream_socket_sendto

(PHP 5)

stream_socket_sendto -- Sends a message to a socket, whether it is connected or not

Description

int stream_socket_sendto ( resource socket, string data [, int flags [, string address]] )

The function stream_socket_sendto() sends the data specified by data through the socket specified by socket. The address specified when the socket stream was created will be used unless an alternate address is specified in address.

The value of flags can be any combination of the following:

Tabella 1. possible values for flags

STREAM_OOB Process OOB (out-of-band) data.

Esempio 1. stream_socket_sendto() Example

<?php
/* Open a socket to port 1234 on localhost */
$socket = stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket, "Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket, "Out of Band data.", STREAM_OOB);

/* Close it up */
fclose($socket);
?>

See also stream_socket_recvfrom(), stream_socket_client(), and stream_socket_server().

stream_socket_server

(PHP 5)

stream_socket_server --  Create an Internet or Unix domain server socket

Description

resource stream_socket_server ( string local_socket [, int &errno [, string &errstr [, int flags [, resource context]]]] )

Creates a stream or datagram socket on the specified local_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem. flags is a bitmask field which may be set to any combination of socket creation flags. The default value of flags is STREAM_SERVER_BIND | STREAM_SERVER_LISTEN.

Nota: For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See Appendice O for a list of bulitin transports.

Esempio 1. Using TCP server sockets

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
    fclose($conn);
  }
  fclose($socket);
}
?>

The example below shows how to act as a time server which can respond to time queries as shown in an example on stream_socket_client().

Nota: Most systems require root access to create a server socket on a port below 1024.

Esempio 2. Using UDP server sockets

<?php
$socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
    die("$errstr ($errno)");
}

do {
    $pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
    echo "$peer\n";
    stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);

?>

Nota: Nella specifica numerica degli indirizzi IPv6 (es. fe80::1) occorre racchiudere l'IP tra parentesi quadre. Ad esempio, tcp://[fe80::1]:80.

See also stream_socket_client(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fwrite(), fclose(), feof(), and the Curl extension.

stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5)

stream_wrapper_register -- Register a URL wrapper implemented as a PHP class

Description

bool stream_wrapper_register ( string protocol, string classname )

stream_wrapper_register() allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

To implement a wrapper, you need to define a class with a number of member functions, as defined below. When someone fopens your stream, PHP will create an instance of classname and then call methods on that instance. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

Nota: As of PHP 5.0.0 the instance of classname will be populated with a context property referencing a Context Resource which may be accessed with stream_context_get_options(). If no context was passed to the stream creation function, context will be set to NULL.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

bool stream_open ( string path, string mode, int options, string opened_path )

This method is called immediately after your stream object is created. path specifies the URL that was passed to fopen() and that this object is expected to retrieve. You can use parse_url() to break it apart.

mode is the mode used to open the file, as detailed for fopen(). You are responsible for checking that mode is valid for the path requested.

options holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

FlagDescription
STREAM_USE_PATHIf path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORSIf this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

If the path is opened successfully, and STREAM_USE_PATH is set in options, you should set opened_path to the full path of the file/resource that was actually opened.

If the requested resource was opened successfully, you should return TRUE, otherwise you should return FALSE

void stream_close ( void )

This method is called when the stream is closed, using fclose(). You must release any resources that were locked or allocated by the stream.

string stream_read ( int count )

This method is called in response to fread() and fgets() calls on the stream. You must return up-to count bytes of data from the current read/write position as a string. If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string. You must also update the read/write position of the stream by the number of bytes that were successfully read.

int stream_write ( string data )

This method is called in response to fwrite() calls on the stream. You should store data into the underlying storage used by your stream. If there is not enough room, try to store as many bytes as possible. You should return the number of bytes that were successfully stored in the stream, or 0 if none could be stored. You must also update the read/write position of the stream by the number of bytes that were successfully written.

bool stream_eof ( void )

This method is called in response to feof() calls on the stream. You should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.

int stream_tell ( void )

This method is called in response to ftell() calls on the stream. You should return the current read/write position of the stream.

bool stream_seek ( int offset, int whence )

This method is called in response to fseek() calls on the stream. You should update the read/write position of the stream according to offset and whence. See fseek() for more information about these parameters. Return TRUE if the position was updated, FALSE otherwise.

bool stream_flush ( void )

This method is called in response to fflush() calls on the stream. If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now. Return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

array stream_stat ( void )

This method is called in response to fstat() calls on the stream and should return an array containing the same values as appropriate for the stream.

bool unlink ( string path )

This method is called in response to unlink() calls on URL paths associated with the wrapper and should attempt to delete the item specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support unlinking.

Nota: Userspace wrapper unlink method is not supported prior to PHP 5.0.0.

bool rename ( string path_from, string path_to )

This method is called in response to rename() calls on URL paths associated with the wrapper and should attempt to rename the item specified by path_from to the specification given by path_to. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support renaming.

Nota: Userspace wrapper rename method is not supported prior to PHP 5.0.0.

bool mkdir ( string path, int mode, int options )

This method is called in response to mkdir() calls on URL paths associated with the wrapper and should attempt to create the directory specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support creating directories. Posible values for options include STREAM_REPORT_ERRORS and STREAM_MKDIR_RECURSIVE.

Nota: Userspace wrapper mkdir method is not supported prior to PHP 5.0.0.

bool rmdir ( string path, int options )

This method is called in response to rmdir() calls on URL paths associated with the wrapper and should attempt to remove the directory specified by path. It should return TRUE on success or FALSE on failure. In order for the appropriate error message to be returned, do not define this method if your wrapper does not support removing directories. Possible values for options include STREAM_REPORT_ERRORS.

Nota: Userspace wrapper rmdir method is not supported prior to PHP 5.0.0.

bool dir_opendir ( string path, int options )

This method is called immediately when your stream object is created for examining directory contents with opendir(). path specifies the URL that was passed to opendir() and that this object is expected to explore. You can use parse_url() to break it apart.

array url_stat ( string path, int flags )

This method is called in response to stat() calls on the URL paths associated with the wrapper and should return as many elements in common with the system function as possible. Unknown or unavailable values should be set to a rational value (usually 0).

flags holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

FlagDescription
STREAM_URL_STAT_LINK For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIETIf this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

string dir_readdir ( void )

This method is called in response to readdir() and should return a string representing the next filename in the location opened by dir_opendir().

bool dir_rewinddir ( void )

This method is called in response to rewinddir() and should reset the output generated by dir_readdir(). i.e.: The next call to dir_readdir() should return the first entry in the location returned by dir_opendir().

bool dir_closedir ( void )

This method is called in response to closedir(). You should release any resources which were locked or allocated during the opening and use of the directory stream.

The example below implements a var:// protocol handler that allows read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the URL "var://foo" will read/write data to/from $GLOBALS["foo"].

Esempio 1. A Stream for reading/writing global variables

<?php

class VariableStream {
    var $position;
    var $varname;
   
    function stream_open($path, $mode, $options, &$opened_path) 
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;
        
        return true;
    }

    function stream_read($count) 
    {
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_write($data) 
    {
        $left = substr($GLOBALS[$this->varname], 0, $this->position);
        $right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
        $GLOBALS[$this->varname] = $left . $data . $right;
        $this->position += strlen($data);
        return strlen($data);
    }

    function stream_tell() 
    {
        return $this->position;
    }

    function stream_eof() 
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

    function stream_seek($offset, $whence) 
    {
        switch ($whence) {
            case SEEK_SET:
                if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
                     $this->position = $offset;
                     return true;
                } else {
                     return false;
                }
                break;
                
            case SEEK_CUR:
                if ($offset >= 0) {
                     $this->position += $offset;
                     return true;
                } else {
                     return false;
                }
                break;
                
            case SEEK_END:
                if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
                     $this->position = strlen($GLOBALS[$this->varname]) + $offset;
                     return true;
                } else {
                     return false;
                }
                break;
                
            default:
                return false;
        }
    }
}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";
    
$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

?>

stream_wrapper_restore

(PHP 5 >= 5.1.0RC1)

stream_wrapper_restore -- Restores a previously unregistered built-in wrapper

Description

bool stream_wrapper_restore ( string protocol )

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

stream_wrapper_unregister

(PHP 5 >= 5.1.0RC1)

stream_wrapper_unregister -- Unregister a URL wrapper

Description

bool stream_wrapper_unregister ( string protocol )

stream_wrapper_unregister() allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().

CXLV. Stringhe

Introduzione

Queste funzioni permettono di manipolare le stringhe in vari modi. Ulteriori funzioni specializzate possono essere trovate nel capitolo dedicato alle espressioni regolari e nel capitolo trattamento degli URL.

Per dettagli su come si comportano le stringhe, in particolare a riguardo l'uso degli apici singoli, doppi apici, e sequenze di escape, vedere il paragrafo Stringhe nel capitolo Tipi del manuale.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Costanti predefinite

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.

CRYPT_SALT_LENGTH integer

CRYPT_STD_DES integer

CRYPT_EXT_DES integer

CRYPT_MD5 integer

CRYPT_BLOWFISH integer

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)


Vedere anche:

Per funzioni più potenti nel gestire e manipolare le stringhe vedere anche i capitoli Funzioni per espressioni regolari POSIX e Funzioni per espressioni regolari compatibili Perl.

Sommario
addcslashes -- Esegue il quoting di una stringa con gli slash nello stile del C
addslashes -- Esegue il quoting di una stringa con gli slash '/'
bin2hex --  Converte i dati binari nella rappresentazione esadecimale
chop -- Alias di di rtrim()
chr -- Restituisce un carattere specifico
chunk_split -- Divide una stringa in segmento più piccoli
convert_cyr_string --  Converte da un set di caratteri Cirillico ad un'altro
convert_uudecode --  Decodifica una stringa codificata con uuencode
convert_uuencode --  Codifica uuencode di una stringa
count_chars --  Restituisce informazioni sui caratteri usati in una stringa
crc32 -- Calcola il crc32 polinomiale di una stringa
crypt -- Criptazione di una stringa a senso unico (hashing)
echo -- Visualizza una o più stringhe
explode -- Suddivide una stringa
fprintf -- Scrive una stringa formattata in uno stream
get_html_translation_table --  Restituisce la tabella di decodifica utilizzata da htmlspecialchars() e htmlentities()
hebrev --  Converte il testo logico Ebraico in testo visuale
hebrevc --  Converte il testo logico Ebraico in testo visuale con conversione del carattere di 'a capo'
html_entity_decode --  Converte le entità HTML nei corrispondenti caratteri
htmlentities --  Converte tutti i possibili caratteri in entità HTML
htmlspecialchars_decode --  Convert special HTML entities back to characters
htmlspecialchars --  Converte i caratteri speciali in entità HTML
implode -- Unisce gli elementi di una matrice in una stringa
join -- Alias di di implode()
levenshtein --  Calcola la distanza Levenshtein tra due stringhe
localeconv -- Ottiene informazioni sul formato numerico
ltrim --  Rimuove gli spazi (o altri caratteri) dall'inizio di una stringa
md5_file -- Calcola l'hash md5 del file dato
md5 -- Calcola il valore md5 di una stringa
metaphone -- Calcola la chiave metaphone di una stringa
money_format -- Formattazione di un numero come stringa monetaria
nl_langinfo --  Ricava informazioni sulla lingua e le impostazioni locali
nl2br --  Inserisce il tag HTML di 'a capo' prima di tutti i caratteri di 'a capo' della stringa
number_format -- Formatta un numero con i grupppi delle migliaia
ord -- Restituisce il valore ASCII di un carattere
parse_str -- Suddivide una stringa in variabili
print -- Visualizza una stringa
printf -- Visualizza una stringa formattata
quoted_printable_decode --  Converte una stringa 'quoted-printable' in una stringa a 8 bit
quotemeta -- Quota i meta caratteri
rtrim --  Rimuove gli spazi (ed altri caratteri) dalla fine della stringa
setlocale -- Imposta i parametri di localizzazione
sha1_file -- Calcola l'hash sha1 di un file
sha1 -- Calcola l'hash sha1 di una stringa
similar_text --  Calcola la similitudine tra due stringhe
soundex -- Calcola la chiave soundex di una data stringa
sprintf -- Restituisce una stringa formattata
sscanf --  Analizza l'input da una string in base al formato
str_ireplace --  Versione insensibile alle miuscole/minuscole di str_replace()
str_pad --  Riempie una stringa con un'altra stringa portando la prima ad una lunghezza pre-determinata
str_repeat -- Ripete una stringa
str_replace --  Sostituisce tutte le occorrenze della stringa cercata con la stringa di sostituzione
str_rot13 -- Esegue la trasformazione rot13 di una stringa
str_shuffle -- Mischia una stringa in modo casuale
str_split --  Converte una stringa in una matrice
str_word_count --  Restituisce informazioni sulle parole utilizzate in una stringa
strcasecmp --  Confronto non sensibile alle maiuscole e sicuro con i dati binari
strchr -- Alias di strstr()
strcmp -- Confronto tra stringhe affidabile con dati binari
strcoll -- Confronto tra stringhe basato sulle impostazioni locali
strcspn --  Trova la lunghezza del segmento iniziale che non soddisfa una maschera
strip_tags -- Rimuove i tag HTML e PHP da una stringa
stripcslashes --  Rimuove gli slash aggiunti con addcslashes()
stripos --  Trova la prima occorrenza in una stringa senza distinzione tra maiuscole e minuscole
stripslashes --  Rimuove gli slash aggiunti con addslashes()
stristr --  Versione insensibile alle maiuscole/minuscole di strstr()
strlen -- Restituisce la lunghezza di una stringa
strnatcasecmp --  Versione insensibile alle maiuscole/minuscole di confronto tra stringhe tramite l'algoritmo dell"ordine naturale"
strnatcmp --  Confronto tra stringhe con l'algoritmo dell' "ordine naturale"
strncasecmp --  Confronto sicuro con i testi binari, insensibile alle lettere maiuscole/minuscole sui primi n caratteri
strncmp --  Confronto tra stringhe sui primi n caratteri, sicuro con i dati binari
strpbrk --  Ricerca in una stringa uno qualsiasi dei caratteri di un dato set
strpos --  Trova la posizione della prima occorrenza di una stringa
strrchr --  Trova l'ultima occorrenza di un carattere in una stringa
strrev -- Inverte una stringa
strripos --  Trova la posizione dell'ultima occorrenza di una stringa in un'altra indipendentemente dalle lettere minuscole/maiusole
strrpos --  Trova la posizione dell'ultima occorrenza di un carattere in una stringa
strspn --  Trova la lunghezza di un testo che corrisponde alla maschera data
strstr -- Trova la prima occorrenza di una stringa
strtok -- Suddivide una stringa in token
strtolower -- Converte in minuscolo una stringa
strtoupper -- Converte in maiuscolo una stringa
strtr -- Traduce certi caratteri
substr_compare --  Confronto tra due stringhe a partire da una data posizione per n caratteri, sicuro con i dati binari e, opzionalmente, senza distinguere tra lettere maiuscole e minuscole
substr_count -- Conta il numero di occorrenze di un segmento di stringa
substr_replace -- Sostuisce una porzione di testo
substr -- Restituisce parte di una stringa
trim -- Rimuove gli spazi (ed altri caratteri) all'inizio e alla fine di un testo
ucfirst -- Converte in maiuscolo il primo carattere del testo
ucwords --  Converte in maiuscolo il primo carattere di ogni parola di una stringa
vfprintf -- Scrive una stringa formatta in un flusso
vprintf -- Visualizza una stringa formattata
vsprintf -- Restituisce una stringa formattata
wordwrap --  Divide una stringa ad un certo numero di caratteri utilizzando il carattere di divisione

addcslashes

(PHP 4, PHP 5)

addcslashes -- Esegue il quoting di una stringa con gli slash nello stile del C

Descrizione

string addcslashes ( string str, string charlist )

La funzione restituisce una stringa con il carattere di backslash '\' anteposto ai caratteri che sono indicati nel parametro charlist. La funzione inserisce il carattere di escape nello stile C in caso di \n, \r ecc., in caso di caratteri con codifica ASCII minore di 32 o superiore a 126 si applica la conversione nella rappresentazione ottale.

Occorre prestare attenzione se si imposta di anteporre il carattere di escape ai caratteri 0, a, b, f, n, r, t e v. Questi saranno convertiti in \0, \a, \b, \f, \n, \r, \t e \v. In PHP \0 (NULL), \r (carriage return), \n (newline) e \t (tab) sono sequenze di escape predefinite, anche in C tutte queste sono sequenze di escape predefinite.

Valorizzare il parametro charlist con "\0..\37", significa che si vuole inserire il carattere di escape davanti ai caratteri la cui codifica ASCII è comprese tra 0 e 31.

Esempio 1. Esempio di uso di addcslashes()

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

Quando si definisca una sequenza di caratteri nel parametro charlist occorre essere consapevoli di quali caratteri sono compresi nel range.

<?php
echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// Inserisce l'escape davanti a tutti i caratteri maiuscoli e minuscoli
// ... ma anche [\]^_` i tab, line
// feeds, carriage returns, etc.
?>

Inoltre, se il primo carattere di un range ha una codifica ASCII maggiore del secondo, il range non sarà applicato. Soltanto il primo, i punti, e l'ultimo carattere avrà la sequenza di escape. Utilizzare la funzione ord() per ottenere la codifica ASCII di un carattere.

<?php
echo addcslashes("zoo['.']", 'z..A');
// output:  \zoo['\.']
?>

Vedere anche stripcslashes(), stripslashes(), htmlspecialchars() e quotemeta().

addslashes

(PHP 3, PHP 4, PHP 5)

addslashes -- Esegue il quoting di una stringa con gli slash '/'

Descrizione

string addslashes ( string str )

La funzione restituisce una stringa con il carattere di backslah '\' anteposto ai caratteri che richiedono il quoting nelle query dei database. Questi caratteri sono: apici singoli ('), doppi apici ("), backslash (\) e NUL (il byte NULL).

Un esempio di utilizzo di addslashes() è dato dal caso in cui si inserisce dei dati in un database. Ad esempio, per inserire il nome O'reilly in un database, occorre anteporre il carattere di escape. Molti database eseguono questo compito con il carattere \, quindi il nostro esempio diventerebbe O\'reilly. Questo serve solo per inserire i dati nel database, il carattere in più \ non sarà inserito. Impostando la direttiva PHP magic_quotes_sybase a on si indica che ' deve essere preceduto da un'altro '.

La direttiva PHP magic_quotes_gpc è impostata a on per default, ed in pratica esegue addslashes() su tutti i dati GET, POST, e COOKIE. Non utilizzare addslashes() su stringhe che hanno già il carattere di escape per via del parametro magic_quotes_gpc altrimenti si ottiene un doppio escape. La funzione get_magic_quotes_gpc() può aiutare nella verifica di questa situazione.

Esempio 1. Esempio di uso di addslashes()

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

Vedere anche stripslashes(), htmlspecialchars(), quotemeta() e get_magic_quotes_gpc().

bin2hex

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

bin2hex --  Converte i dati binari nella rappresentazione esadecimale

Descrizione

string bin2hex ( string str )

La funzione restituisce una stringa ASCII contenente la rappresentazione esadecimale del parametro str. La conversione viene eseguita byte per byte considerando prima il semi-byte più significativo.

Vedere anche pack() e unpack().

chop

(PHP 3, PHP 4, PHP 5)

chop -- Alias di di rtrim()

Descrizione

This function is an alias of: rtrim().

Nota: chop() è differente rispetto alla omonima funzione di Perl chop(), la quale rimuove l'ultimo carattere della stringa.

chr

(PHP 3, PHP 4, PHP 5)

chr -- Restituisce un carattere specifico

Descrizione

string chr ( int ascii )

La funzione restituisce una stringa di un carattere contenente il carattere indicato come codifica ASCII nel parametro ascii.

Esempio 1. Esempio di uso di chr()

<?php
$str = "La stringa termina con un escape: ";
$str .= chr(27); /* aggiunge il carattere di escape al termine di $str */

/* Spesso è più pratico */

$str = sprintf("The string ends in escape: %c", 27);
?>

A questo link http://www.asciitable.com si può trovare una tavola delle codifiche ASCII.

Questa funzione è complementare rispetto a ord(). Vedere anche sprintf() con la stringa di formato %c.

chunk_split

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

chunk_split -- Divide una stringa in segmento più piccoli

Descrizione

string chunk_split ( string body [, int chunklen [, string end]] )

Questa funzione può essere utilizzata per suddividere una stringa in segmenti più ridotti, per possono essere utili, ad esempio, nel convertire l'output della funzione base64_encode() in modo da aderire alle specifiche indicate nella RFC 2045. La funzione inserisce end (il default è "\r\n") ad ogni chunklen caratteri (default è 76). La funzione restituisce una nuova stringa lasciando inalterata la stringa originale.

Esempio 1. Esempio di uso di chunk_split()

<?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?>

Vedere anche str_split(), explode(), split(), wordwrap() e RFC 2045.

convert_cyr_string

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

convert_cyr_string --  Converte da un set di caratteri Cirillico ad un'altro

Descrizione

string convert_cyr_string ( string str, string from, string to )

Questa funzione restituisce la stringa data convertita da un set di caratteri Cirillico ad un altro. I parametri from e to rappresentano il set di caratteri Cirillici di origine e di destinazione. I tipi supportati sono:

  • k - koi8-r

  • w - windows-1251

  • i - iso8859-5

  • a - x-cp866

  • d - x-cp866

  • m - x-mac-cyrillic

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

convert_uudecode

(PHP 5)

convert_uudecode --  Decodifica una stringa codificata con uuencode

Descrizione

string convert_uudecode ( string data )

La funzione convert_uudecode() decodifica una stringa codificata con uuencode.

Esempio 1. Esempio di uso di convert_uudecode()

<?php
/* Can you imagine what this will print? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

Vedere anche convert_uuencode().

convert_uuencode

(PHP 5)

convert_uuencode --  Codifica uuencode di una stringa

Descrizione

string convert_uuencode ( string data )

convert_uuencode() codifica una trsinga usando l'algoritmo uuencode.

L'algoritmo uuencode codifica tutte le stringhe (comprese quelle binarie) in caratteri stampabili, rendendole sicure per la trasmissione via rete. I dati così codificati hanno una dimensione del 35% superiore all'originale.

Esempio 1. Esempio di uso di convert_uuencode()

<?php
$some_string = "test\ntext text\r\n";
echo convert_uuencode($some_string);
?>

Vedere anche convert_uudecode() e base64_encode().

count_chars

(PHP 4, PHP 5)

count_chars --  Restituisce informazioni sui caratteri usati in una stringa

Descrizione

mixed count_chars ( string string [, int mode] )

La funzione conta il numero di occorrenze di ogni carattere (0..255) nella stringa string e li restituisce in vari modi. Il parametro opzionale mode ha come default 0. In base alle impostazioni di mode la funzione count_chars() restituisce:

  • 0 - una matrice in cui ogni carattere (come codifica ASCII) è la chiave e la sua frequenza il valore.

  • 1 - come lo 0 ma saranno restituiti solo i caratteri con frequenza maggiore di zero.

  • 2 - come lo 0 ma saranno restituiti solo i caratteri con frequenza uguale a zero.

  • 3 - la funzione restituisce una stringa con tutti i caratteri utilizzati.

  • 4 - la funzione restituisce una stringa con tutti i caratteri non utilizzati.

Esempio 1. Esempio di uso di count_chars()

<?php

$data = "Two Ts and one F.";

$result = count_chars($data, 0);

for ($i=0; $i < count($result); $i++) {
   if ($result[$i] != 0)
       echo "Vi sono $result[$i] istanze di \"" , chr($i) , "\" nella stringa.\n";
}

?>

Questo esempio visualizzerà:

Vi sono 4 istanze di " " nella stringa. 
Vi sono 1 istanze di "." nella stringa. 
Vi sono 1 istanze di "F" nella stringa. 
Vi sono 2 istanze di "T" nella stringa. 
Vi sono 1 istanze di "a" nella stringa. 
Vi sono 1 istanze di "d" nella stringa. 
Vi sono 1 istanze di "e" nella stringa. 
Vi sono 2 istanze di "n" nella stringa. 
Vi sono 2 istanze di "o" nella stringa. 
Vi sono 1 istanze di "s" nella stringa. 
Vi sono 1 istanze di "w" nella stringa.

Vedere anche strpos() e substr_count().

crc32

(PHP 4 >= 4.0.1, PHP 5)

crc32 -- Calcola il crc32 polinomiale di una stringa

Descrizione

int crc32 ( string str )

La funzione calcola il checksum lungo 32 bit della stringa str. Solitamente questo viene utilizzato per validare i dati trasmessi.

Poiché il tipo intero del PHP è segnato, è diversi checksum crc32 hanno risultati negativi, occorre utilizzare il formato "%u" di sprintf() o di printf() per ottenere una rappresentazione stringa di un checksum crc32 privo di segno.

Questo secondo esempio mostra come visualizzare un checksum convertito con la funzione printf():

Esempio 1. Visualizzazione di un checksum crc32

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

Vedere anche md5() e sha1().

crypt

(PHP 3, PHP 4, PHP 5)

crypt -- Criptazione di una stringa a senso unico (hashing)

Descrizione

string crypt ( string str [, string salt] )

La funzione crypt() restituisce una stringa criptata tramite l'algoritmo standard di crittografia di UNIX basato sul DES o su algoritmo alternativi disponibili sul sistema. I parametri sono la stringa che deve essere crittografata, e un parametro opzionale da usarsi come base per la crittografia. Vedere le pagine Unix relative alla funzione cript per maggiori dettagli.

Se il parametro salt non viene fornito, il PHP ne genererà uno casuale ad ogni chiamata.

Alcuni sistemi operativi supportano più di un tipo di cifratura. Infatti in alcuni casi lo standard basato sul DES viene sostituito da un algoritmo basato su MD5. Il tipo di crittografia da utilizzare viene attivato tramite il parametro salt. Al momento dell'installazione il PHP cerca di determinare le caratteristiche della funzione crypt e accetterà salt per altri tipi di funzioni. Se il parametro salt non viene passato, il PHP genererà, per default, una chiave di due caratteri a meno che il sistema di cifratura di default del sistema non sia MD5, in questo caso si genererà una chiave casuale compatibile con MD5. Il PHP imposta una costante chiamata CRYPT_SALT_LENGTH dalla quale si può sapere se sul sistema si può utilizzare una chiave di due caratteri o la chiave più lunga di 12 caratteri.

Se si usa la chiave generata, bisogna fare attenzione che questa viene generata una sola volta. Se si chiama la funzione ricorsivamente, si possono avere dei problemi di formato e di sicurezza.

La crittografia basa sullo standard DES restituisce la chiave come primi due caratteri dell'output. Inoltre utilizza solo i primi 8 caratteri del parametro str, pertanto stringhe più lunghe che inizino con i medesimi otto caratteri, creeranno il medesimo risultato (se si utilizza la medesima chiave).

Sui sistemi nei quali la funzione cript() supporta più tipi di crittografia, si imposteranno le seguenti costanti a 0 o a 1 in base al tipo disponibile.

  • CRYPT_STD_DES - Standard basato su DES con chiave di due caratteri

  • CRYPT_EXT_DES - Estensione basato su DES con chiave di nove caratteri

  • CRYPT_MD5 - Crittografia basata su MD5 con 12 caratteri di chiave inizianti con $1$

  • CRYPT_BLOWFISH - Crittografia Blowfish con 16 caratteri di chiave inizianti con $2$ oppure $2a$

Nota: Non esiste una funzione di decriptazione, poiché crypt() è un algoritmo ad una via.

Esempio 1. Esempio di uso di crypt()

<?php
$password = crypt("My1sTpassword"); // let salt be generated

/* Si dovrebbe passare l'intero risultato di crypt() come chiave di confronto
   della password per evitare problemi con differenti algoritmi di hash. (Come detto prima
   lo standard basato su DES usa chiavi di 2 caratteri,
   mentre lo standard basato su MD5 ne usa 12). */
if (crypt($user_input, $password) == $password) {
   echo "Password verified!";
}
?>

Esempio 2. Utilizzo di crypt() con htpasswd

<?php
// Set the password
$password = 'mypassword';
 
// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>

Esempio 3. Uso dei diversi tipi di criptazione

<?php
if (CRYPT_STD_DES == 1) {
    echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}
 
if (CRYPT_EXT_DES == 1) {
    echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}
 
if (CRYPT_MD5 == 1) {
    echo 'MD5:          ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}
 
if (CRYPT_BLOWFISH == 1) {
    echo 'Blowfish:     ' . crypt('rasmuslerdorf', '$2a$07$rasmuslerd...........$') . "\n";
}
?>

Il precedente esempio visualizzerà qualcosa simile a:

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2a$07$rasmuslerd............nIdrcHdxcUxWomQX9j6kvERCFjTg7Ra

Vedere anche md5() e il modulo Mcrypt.

echo

(PHP 3, PHP 4, PHP 5)

echo -- Visualizza una o più stringhe

Descrizione

void echo ( string arg1 [, string ...] )

Visualizza tutti i parametri.

echo() in realtà non è una funzione (è un costrutto del linguaggio) pertanto non richiede l'uso di parametri. Infatti, se si vuole passare più di un parametro, non bisogna racchiuderli tra parentesi.

Esempio 1. Esempi di uso di echo()

<?php
echo "Hello World";

echo "This spans
multiple lines. The newlines will be 
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

echo "Escaping characters is done \"Like this\".";

// Si possono utilizzare variabili all'interno dei parametri di echo
$foo = "foobar";
$bar = "barbaz";

echo "foo is $foo"; // foo is foobar

// Si possono utilizzare anche delle matrici
$bar = array("value" => "foo");

echo "this is {$bar['value']} !"; // this is foo !

// Utilizzando gli apici singoli viene visualizzato il nome della variabile, non il valore
echo 'foo is $foo'; // foo is $foo

// Se non vi sono altri caratteri, si può visualizzare soltanto il contenuto delle variabili
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Alcuni programmatori preferiscono passare i parametri come sequenza di stringhe concatenate.
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

echo <<<END
Questo esempio utilizza la sintassi "here document"
per visualizzare più linee oltre al contenuto di $variable
Notare che il terminatore del testo richiede
anche il punto e virgola, senza alcun spazio aggiuntivo!
END;

// Poichè echo non è una funzione la seguente riga non è valida.
($some_var) ? echo 'true' : echo 'false';

// Tuttavia la seguente funziona
($some_var) ? print('true'): print('false'); // print è una funzione
echo $some_var ? 'true': 'false'; // altra versione dell'istruzione
?>

echo() ha una sintassi alternativa abbreviata in cui si può fare seguire alle tag di apertura il segno di uguale. Questa sintassi abbreviata funziona solo se il parametro di configurazione short_open_tag è abilitato.

I have <?=$foo?> foo.

Per una breve discussione sulle differenze tra print() e echo(), vedere FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

Vedere anche print(), printf() e flush().

explode

(PHP 3, PHP 4, PHP 5)

explode -- Suddivide una stringa

Descrizione

array explode ( string separator, string string [, int limit] )

Questa funzione restituisce una matrice di stringhe, ciascuna delle quali è una parte di string ottenuta dividendo la stringa originale utilizzando separator come separatore di stringa. Se si imposta limit la matrice restituita conterrà al massimo limit elementi di cui l'ultimo conterrà la parte restante di string.

Se il parametro separator è impostato ad una stringa vuota (""), la funzione explode() restituirà FALSE. Se separator contiene caratteri non presenti in string, allora explode() restituirà una matrice contenente string.

Se il parametro limit è negativo, sono restituiti tutti i componenti tranne gli ultimi limit elementi. Questa caratteristica è stata inserita in PHP 5.1.0.

Sebbene implode() può, per ragioni storiche, accettare i parametri in entrambi gli ordini, explode() non può. Occorre accertarsi che il parametro separator sia antecedente al parametro string.

Nota: Il parametro limit è stato aggiunto dalla versione 4.0.1

Esempio 1. Esempi di uso di explode()

<?php
// Esempio 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Esempio 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Esempio 2. Esempi del parametro limit

<?php
$str = 'one|two|three|four';
 
// limite positivo
print_r(explode('|', $str, 2));
	 
// negativo (dal PHP 5.1)
print_r(explode('|', $str, -1));
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche preg_split(), spliti(), split(), strtok() e implode().

fprintf

(PHP 5)

fprintf -- Scrive una stringa formattata in uno stream

Descrizione

int fprintf ( resource handle, string format [, mixed args [, mixed ...]] )

La funzione scrive una stringa formattata in base al parametro format nello stream indicato dal parametro handle. I valori per il parametro format sono descritti nella documentazione della funzione sprintf().

Restituisce la lunghezza della stringa prodotta.

Vedere anche: printf(), sprintf(), sscanf(), fscanf(), vsprintf() e number_format().

Esempi

Esempio 1. fprintf(): interi completati con zero

<?php
if (!($fp = fopen('date.txt', 'w')))
    return;
 
fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// Scrive la data in formato ISO nel file date.txt
?>

Esempio 2. fprintf(): formattazione della moneta

<?php
if (!($fp = fopen('currency.txt', 'w')))
    return;

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$len = fprintf($fp, '%01.2f', $money);
// scrive "123.10" nel file currency.txt
 
echo "wrote $len bytes to currency.txt";
// utilizza il valore restituito da fprintf per stabilire quanti byte sono stati scritti
?>

get_html_translation_table

(PHP 4, PHP 5)

get_html_translation_table --  Restituisce la tabella di decodifica utilizzata da htmlspecialchars() e htmlentities()

Descrizione

array get_html_translation_table ( [int table [, int quote_style]] )

La funzione get_html_translation_table() restituisce la tabella di decodifica utilizzata dalle funzioni htmlspecialchars() e htmlentities().

Esistono due nuove costanti (HTML_ENTITIES, HTML_SPECIALCHARS) che permettono di indicare quale tabella sid esidera. Inoltre nelle funzioni htmlspecialchars() e htmlentities(), opzionalmente, si può specificare il quote_style con cui si lavora. Il default è ENT_COMPAT. Vedere la descrizione di queste modalità in htmlspecialchars().

Esempio 1. Esempio della tabella di decodifica

<?php
$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo & <Frau> & Krämer";
$encoded = strtr($str, $trans);
?>
La variabile $encoded ora contiene: "Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer".

Un'altro utilizzo interessante di questa funzione è dato, in combinazione con array_flip(), dalla possibilità di cambiare direzione alla decodifica.

<?php
$trans = array_flip($trans);
$original = strtr($encoded, $trans);
?>

Il contenuto $original sarà: "Hallo & <Frau> & Krämer".

Vedere anche: htmlspecialchars(), htmlentities(), strtr() e array_flip().

hebrev

(PHP 3, PHP 4, PHP 5)

hebrev --  Converte il testo logico Ebraico in testo visuale

Descrizione

string hebrev ( string hebrew_text [, int max_chars_per_line] )

Il parametro opzionale max_chars_per_line indica il numero massimo di caratteri per linea che saranno restituiti in output. La funzione tenta di evitare di spezzare le parole.

Vedere anche hebrevc()

hebrevc

(PHP 3, PHP 4, PHP 5)

hebrevc --  Converte il testo logico Ebraico in testo visuale con conversione del carattere di 'a capo'

Descrizione

string hebrevc ( string hebrew_text [, int max_chars_per_line] )

Questa funzione è simile a hebrev() con la differenza che converte il carattere di 'a capo' (\n) in "<br>\n". Il parametro opzionale max_chars_per_line indica il numero massimo di caratteri per linea che saranno restituiti. La funzione tenta di evitare di spezzare le parole.

Vedere anche hebrev()

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5)

html_entity_decode --  Converte le entità HTML nei corrispondenti caratteri

Descrizione

string html_entity_decode ( string string [, int quote_style [, string charset]] )

La funzione html_entity_decode() è l'opposto di htmlentities() converte tutte le entità HTML presenti nel parametro string nel corrispondente carattere.

Il secondo parametro, quote_style, opzionale, indica cosa occorre fare per gli apici 'singoli' e "doppi". Sono possibili tre scelte indicate da tre costanti con default ENT_COMPAT:

Tabella 1. Costanti disponibili per quote_style

Nome della costanteDescrizione
ENT_COMPATConverte gli apici doppi e lascia inalterati gli apici singoli.
ENT_QUOTESConverte sia gli apici doppi sia gli apici singoli.
ENT_NOQUOTESLascia entrambi i tipi di apici inalterati.

Per il terzo parametro opzionale, charset, si utilizza come default il set di caratteri ISO-8859-1. Questo parametro indica quale set di caratteri utilizzare per la conversione.

Elenco dei set di caratteri supportati dal PHP 4.3.0 e successivi.

Tabella 2. set di caratteri supportati

Set di caratteriAliasDescrizione
ISO-8859-1ISO8859-1 Western European, Latin-1
ISO-8859-15ISO8859-15 Western European, Latin-9. Con in più il simbolo dell'Euro e i caratteri francesi e finnici mancanti in Latin-1(ISO-8859-1).
UTF-8  Set ASCII compatibile con il set multi-byte Unicode su 8-bit.
cp866ibm866, 866 Set di caratteri cirillico specifico del Dos. Supportato dalla 4.3.2.
cp1251Windows-1251, win-1251, 1251 Set di caratteri cirillico specifico di Windows, Supportato dalla 4.3.2.
cp1252Windows-1252, 1252 Set di caratteri specifico di Windows per l'Europa occidentale.
KOI8-Rkoi8-ru, koi8r Russo. Supportato dalla 4.3.2.
BIG5950 Cinese tradizionale, usato principalmente a Taiwan.
GB2312936 Cinese semplificato, set di caratteri nazionale standard.
BIG5-HKSCS  Big5 con estensioni per Hong Kong, cinese tradizionale.
Shift_JISSJIS, 932 Giapponese.
EUC-JPEUCJP Giapponese.

Nota: Ogni altro set di caratteri non è riconosciuto e sarà sostituito con con il set ISO-8859-1.

Esempio 1. Decodifica delle entità HTML

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now


// Per utilizzatori di versioni di PHP antecedenti alla 4.3.0:
function unhtmlentities($string) 
{
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
}

$c = unhtmlentities($a);

echo $c; // I'll "walk" the <b>dog</b> now

?>

Nota: Ci si può chiedere come mai la sequenza trim(html_entity_decode('&nbsp;')); non produca una stringa vuota; questo accade perchè l'intità '&nbsp;' non corrisponde al codice ASCII 32 (che verrebbe rimosso da trim()), ma, nella codifica di default ISO-8859-1, corrisponde al carattere ASCII 160 (0xa0).

Vedere anche htmlentities(), htmlspecialchars(), get_html_translation_table(), and urldecode().

htmlentities

(PHP 3, PHP 4, PHP 5)

htmlentities --  Converte tutti i possibili caratteri in entità HTML

Descrizione

string htmlentities ( string string [, int quote_style [, string charset]] )

Questa funzione è identica a htmlspecialchars() tranne che htmlentities() converte tutti i caratteri che hanno una corrispettiva entità HTML.

Come per la funzione htmlspecialchars(), il secondo parametro opzionale quote_style indica cosa occorre fare per gli apici 'singoli' e "doppi". Sono possibili tre scelte indicate da tre costanti con default ENT_COMPAT:

Tabella 1. Costanti disponibili per quote_style

Nome della costanteDescrizione
ENT_COMPATConverte gli apici doppi e lascia inalterati gli apici singoli.
ENT_QUOTESConverte sia gli apici doppi sia gli apici singoli.
ENT_NOQUOTESLascia entrambi i tipi di apici inalterati.

Il suupporto per il parametro quote è stato introdotto in PHP 4.0.3.

Come per la funzione htmlspecialchars(), questa ha un terzo parametro charset, opzionale, che definisce quale set di caratteri utilizzare per la conversione. Il supporto per questo parametro è stato aggiunto in PHP 4.1.0. Attualmente per default si utilizza il set ISO-8859-1.

Elenco dei set di caratteri supportati dal PHP 4.3.0 e successivi.

Tabella 2. set di caratteri supportati

Set di caratteriAliasDescrizione
ISO-8859-1ISO8859-1 Western European, Latin-1
ISO-8859-15ISO8859-15 Western European, Latin-9. Con in più il simbolo dell'Euro e i caratteri francesi e finnici mancanti in Latin-1(ISO-8859-1).
UTF-8  Set ASCII compatibile con il set multi-byte Unicode su 8-bit.
cp866ibm866, 866 Set di caratteri cirillico specifico del Dos. Supportato dalla 4.3.2.
cp1251Windows-1251, win-1251, 1251 Set di caratteri cirillico specifico di Windows, Supportato dalla 4.3.2.
cp1252Windows-1252, 1252 Set di caratteri specifico di Windows per l'Europa occidentale.
KOI8-Rkoi8-ru, koi8r Russo. Supportato dalla 4.3.2.
BIG5950 Cinese tradizionale, usato principalmente a Taiwan.
GB2312936 Cinese semplificato, set di caratteri nazionale standard.
BIG5-HKSCS  Big5 con estensioni per Hong Kong, cinese tradizionale.
Shift_JISSJIS, 932 Giapponese.
EUC-JPEUCJP Giapponese.

Nota: Ogni altro set di caratteri non è riconosciuto e sarà sostituito con con il set ISO-8859-1.

Se si deve esere una decodifica (un giro al contrario) occorre utilizzare la funzione html_entity_decode().

Esempio 1. Un esempio di htmlentities()

<?php
$str = "A 'quote' is <b>bold</b>";

// Visualizza: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Visualizza: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

Vedere anche html_entity_decode(), get_html_translation_table(), htmlspecialchars(), nl2br() e urlencode().

htmlspecialchars_decode

(PHP 5 >= 5.1.0RC1)

htmlspecialchars_decode --  Convert special HTML entities back to characters

Descrizione

string htmlspecialchars_decode ( string string [, int quote_style] )

This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.

The converted entities are: &amp;, &quot; (when ENT_NOQUOTES is not set), &#039; (when ENT_QUOTES is set), &lt; and &gt;.

Elenco dei parametri

string

The string to decode

quote_style

The quote style. One of the following constants:

Tabella 1. quote_style constants

Constant NameDescription
ENT_COMPATWill convert double-quotes and leave single-quotes alone (default)
ENT_QUOTESWill convert both double and single quotes
ENT_NOQUOTESWill leave both double and single quotes unconverted

Valori restituiti

Returns the decoded string.

Esempi

Esempio 1. A htmlspecialchars_decode() example

<?php
$str = '<p>this -&gt; &quot;</p>';

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

Il precedente esempio visualizzerà:

<p>this -> "</p>
<p>this -> &quot;</p>

htmlspecialchars

(PHP 3, PHP 4, PHP 5)

htmlspecialchars --  Converte i caratteri speciali in entità HTML

Descrizione

string htmlspecialchars ( string string [, int quote_style [, string charset]] )

Alcuni caratteri hanno significati particolari in HTML, e, per questo, devono essere rappresentati tramite entità HTML, se devono mantenere il proprio significato. Questa funzione restituisce restituisce una stringa con la conversione di alcuni di questi caratteri; la conversione svolta non è sempre valida nell'ambito della programmazione web. Se occorre l'utilizzo di tutte le entità HTML, utilizzare htmlentities().

Questa funzione è utile nel prevenire la presenza di marcatori HTML negli input utente, tipo nei forum o nei guest book. Il secondo parametro quote_style, opzionale, indica alla funzione come comportarsi con gli apici singoli e doppi. La modalità di default è, ENT_COMPAT; questa modalità è compatibile con il passato e traduce solo gli apici doppi lasciando inalterati gli apici singoli. Se si imposta ENT_QUOTES, entrambi i tipi di apici, singoli e doppi, sono convertiti in entità e, infine, se si utilizza ENT_NOQUOTES ne gli apici singoli ne gli apici doppi sono convertiti in entità.

La conversioni applicate sono:

  • '&' (e commerciale) diventa '&amp;'

  • '"' (doppio apice) diventa '&quot;' con ENT_NOQUOTES is not set.

  • ''' (singolo apice) diventa '&#039;' soltanto con l'impostazione di ENT_QUOTES.

  • '<' (minore) diventa '&lt;'

  • '>' (maggiore) diventa '&gt;'

Esempio 1. Esempio di uso di htmlspecialchars()

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Occorre notare che questa funzione non converte null'altro oltre ai caratteri elencati in precedenza. Per la conversione di tutte le entità fare riferimento a htmlentities(). Il secondo parametro è stato inserito in PHP 3.0.17 e 4.0.3.

Il terzo parametro charset indica quale set di caratteri utilizzare nella conversione. Il set di caratteri di default è ISO-8859-1. Questo terzo parametro è stato aggiunto in PHP 4.1.0.

Elenco dei set di caratteri supportati dal PHP 4.3.0 e successivi.

Tabella 1. set di caratteri supportati

Set di caratteriAliasDescrizione
ISO-8859-1ISO8859-1 Western European, Latin-1
ISO-8859-15ISO8859-15 Western European, Latin-9. Con in più il simbolo dell'Euro e i caratteri francesi e finnici mancanti in Latin-1(ISO-8859-1).
UTF-8  Set ASCII compatibile con il set multi-byte Unicode su 8-bit.
cp866ibm866, 866 Set di caratteri cirillico specifico del Dos. Supportato dalla 4.3.2.
cp1251Windows-1251, win-1251, 1251 Set di caratteri cirillico specifico di Windows, Supportato dalla 4.3.2.
cp1252Windows-1252, 1252 Set di caratteri specifico di Windows per l'Europa occidentale.
KOI8-Rkoi8-ru, koi8r Russo. Supportato dalla 4.3.2.
BIG5950 Cinese tradizionale, usato principalmente a Taiwan.
GB2312936 Cinese semplificato, set di caratteri nazionale standard.
BIG5-HKSCS  Big5 con estensioni per Hong Kong, cinese tradizionale.
Shift_JISSJIS, 932 Giapponese.
EUC-JPEUCJP Giapponese.

Nota: Ogni altro set di caratteri non è riconosciuto e sarà sostituito con con il set ISO-8859-1.

Vedere anche get_html_translation_table(), strip_tags(), htmlentities() e nl2br().

implode

(PHP 3, PHP 4, PHP 5)

implode -- Unisce gli elementi di una matrice in una stringa

Descrizione

string implode ( string glue, array pieces )

Restituisce una stringa contenente tutti gli elementi di una matrice nel medesimo ordine, inserendo il parametro glue tra un elemento e l'altro.

Esempio 1. Esempio di uso di implode()

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?>

Nota: La funzione implode(), per ragioni storiche, può accettare i propri parametri in entrambi gli ordini. Tuttavia per mantenere la consistenza con explode(), ed avere meno confusione, utilizzare i parametri nell'ordine documentato.

Nota: Dal PHP 4.3.0, il parametro glue di implode() è opzionale e come default utilizza una stringa vuota (''). Questo non è l'utilizzo preferenziale di implode(). Si suggerisce di utilizzare sempre il secondo parametro per compatibilità con le vecchie versioni.

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche explode() e split().

join

(PHP 3, PHP 4, PHP 5)

join -- Alias di di implode()

Descrizione

This function is an alias of: implode().

levenshtein

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.1, PHP 5)

levenshtein --  Calcola la distanza Levenshtein tra due stringhe

Descrizione

int levenshtein ( string str1, string str2 [, int cost_ins [, int cost_rep, int cost_del]] )

Questa funzione restituisce la distanza Levenshtein tra due stringhe o -1 se uno degli argomenti è più lungo del limite di 255 caratteri.

La distanza Levenshtein è definita come il numero minimo di caratteri da sostituire, inserire o cancellare per trasformare str1 in str2. La complessità dell'algoritmo è O(m*n), dove n e m sono rispettivamente la lunghezza di str1 e di str2 (valore piuttosto buono se confrontato con similar_text(), che è O(max(n,m)**3), ma comunque costoso).

Nella sua versione più semplice la funzione richiede come parametri due stringhe e calcola il numero di caratteri da inserire, sostituire o rimuovere necessari a trasformare str1 in str2.

La seconda variante utilizza tre parametri addizionali che definiscono il costo delle operazioni di inserimento, sostituzione e di cancellazione. Questa versione è più generale e adattabile della precedente, ma non è altrettanto efficiente.

Esempio 1. Esempio di uso di levenshtein()

<?php
// input parola errata
$input = 'carrrot';
 
// matrice di parole con cui verificare
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');
 
// non ancora trovata la distanza più breve
$shortest = -1;
 
// loop su tutte le parole per trovare la più simile
foreach ($words as $word) {
 
    // calcola la distanza tra la parola di input
    // e la corrente
    $lev = levenshtein($input, $word);
 
    // è la parola esatta?
    if ($lev == 0) {
 
        // la più simile è questa
        $closest = $word;
        $shortest = 0;
 
        // esce dal loop, l'abbiamo trovata
        break;
    }
 
    // se la distanza è inferiore rispetto alla precendete più corta
    // o non ne abbiamo ancora trovata una
    if ($lev <= $shortest || $shortest < 0) {
        // imposta la parola più simile e la distanza più breve
        $closest  = $word;
        $shortest = $lev;
    }
}
 
echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}
 
?>

Il precedente esempio visualizzerà:

Input word: carrrot
Did you mean: carrot?

Vedere anche soundex(), similar_text() e metaphone().

localeconv

(PHP 4 >= 4.0.5, PHP 5)

localeconv -- Ottiene informazioni sul formato numerico

Descrizione

array localeconv ( void )

La funzione restituisce un array associativo contenente le configurazioni locali per il formato numerico e monetario.

La funzione localeconv() restituisce i dati in base alle configurazioni locali come impostate da setlocale(). L'array associativo restituito contiene i seguenti campi:

ElementoDescrizione
decimal_pointCarattere per il punto decimale
thousands_sepSeparatore delle migliaia
groupingArray contenente i gruppi numerici
int_curr_symbolSimbolo internazionale della divisa (i.e. USD)
currency_symbolSimbolo della divisa locale (i.e. $)
mon_decimal_pointCarattere per il punto decimale nella moneta
mon_thousands_sepSeparatore delle migliaia nella moneta
mon_groupingArray contenente i gruppi monetari
positive_signSegno per i valori positivi
negative_signSegno per i valori negativi
int_frac_digitsNumero di caratteri frazionali internazionali
frac_digitsNumero di caratteri frazionali locali
p_cs_precedes TRUE se il simbolo della divisa precede i valori positivi, FALSE se segue tali valori
p_sep_by_space TRUE se uno spazio separa il simbolo della divisa dai valori positivi FALSE in caso contrario
n_cs_precedes TRUE se il simbolo della divisa precede i valori negativi, FALSE se segue tali valori
n_sep_by_space TRUE se uno spazio separa il simbolo della divisa dai valori negativi, FALSE in caso contrario
p_sign_posn

0 Parentesi attorno alla quantità ed al simbolo della divisa
1 Il segno precede la quantità ed al simbolo della divisa
2 Il segno segue la quantità ed al simbolo della divisa
3 Il segno precede immediatamente il simbolo della divisa
4 Il segno segue immediatamente il simbolo della divisa

n_sign_posn

0 Parentesi attorno alla quantità ed al simbolo della divisa
1 Il segno precede la quantità ed al simbolo della divisa
2 Il segno segue la quantità ed al simbolo della divisa
3 Il segno precede immediatamente il simbolo della divisa
4 Il segno segue immediatamente il simbolo della divisa

I campi di raggruppamento contengono matrici che definiscono il modo con cui i numeri dovrebbero essere raggruppati. Ad esempio, i campi di raggruppamento per il formato en_US, contengono due elementi con i valori 3 e 3. L'indice più alto indica quanto è distinta il gruppo di sinistra. Se un elemento della matrice è uguale a CHAR_MAX, non vi sono più gruppi. Se nella matrice vi è un elemento a 0, occorre utilizzare l'elemento precedente.

Esempio 1. Esempio di uso di localeconv()

<?php
setlocale(LC_ALL, "en_US");

$locale_info = localeconv();

echo "<pre>\n";
echo "--------------------------------------------\n";
echo "  Informazioni sulla configurazione monetaria locale:  \n";
echo "--------------------------------------------\n\n";

echo "int_curr_symbol:   {$locale_info["int_curr_symbol"]}\n";
echo "currency_symbol:   {$locale_info["currency_symbol"]}\n";
echo "mon_decimal_point: {$locale_info["mon_decimal_point"]}\n";
echo "mon_thousands_sep: {$locale_info["mon_thousands_sep"]}\n";
echo "positive_sign:     {$locale_info["positive_sign"]}\n";
echo "negative_sign:     {$locale_info["negative_sign"]}\n";
echo "int_frac_digits:   {$locale_info["int_frac_digits"]}\n";
echo "frac_digits:       {$locale_info["frac_digits"]}\n";
echo "p_cs_precedes:     {$locale_info["p_cs_precedes"]}\n";
echo "p_sep_by_space:    {$locale_info["p_sep_by_space"]}\n";
echo "n_cs_precedes:     {$locale_info["n_cs_precedes"]}\n";
echo "n_sep_by_space:    {$locale_info["n_sep_by_space"]}\n";
echo "p_sign_posn:       {$locale_info["p_sign_posn"]}\n";
echo "n_sign_posn:       {$locale_info["n_sign_posn"]}\n";
echo "</pre>\n";
?>

E' presente una costante, CHAR_MAX, per gli utilizzi descritti in precedenza.

Vedere anche setlocale().

ltrim

(PHP 3, PHP 4, PHP 5)

ltrim --  Rimuove gli spazi (o altri caratteri) dall'inizio di una stringa

Descrizione

string ltrim ( string str [, string charlist] )

Nota: Il secondo parametro è stato aggiunto nella versione 4.1.0 di PHP.

Questa funzione restituisce la stringa str a cui sono stati rimossi gli spazi iniziali. Senza la specifica del secondo parametro ltrim() rimuoverà i seguenti caratteri:

  • " " (ASCII 32 (0x20)), spazio ordinario.

  • "\t" (ASCII 9 (0x09)), tab.

  • "\n" (ASCII 10 (0x0A)), newline (line feed).

  • "\r" (ASCII 13 (0x0D)), carriage return.

  • "\0" (ASCII 0 (0x00)), il byte NUL.

  • "\x0B" (ASCII 11 (0x0B)), il tab verticale.

Si può anche specificare i caratteri che si desidera rimuovere, indicandoli nel parametro charlist. Quest'ultimo è costituito da un semplice elenco di caratteri da rimuovere. Con .. si può specificare un range di caratteri.

Esempio 1. Esempio di uso di ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = ltrim($text);
// $trimmed = "These are a few words :) ...  "
$trimmed = ltrim($text, " \t.");
// $trimmed = "These are a few words :) ...  "
$clean = ltrim($binary, "\x00..\x1F");
// rimuove i caratteri di controllo ASCII dall'inizio di $binary 
// (from 0 to 31 inclusive)

?>

Vedere anche trim() and rtrim().

md5_file

(PHP 4 >= 4.2.0, PHP 5)

md5_file -- Calcola l'hash md5 del file dato

Descrizione

string md5_file ( string filename [, bool raw_output] )

Calcola l'hash md5 del file filename utilizzando l' RSA Data Security, Inc. MD5 Message-Digest Algorithm, e lo restituisce. L'hash prodotto è un numero esadecimale di 32 caratteri. Se il secondo parametro raw_output è impostato a TRUE, il valore md5 è restituito nel formato binario raw con una lunghezza di 16 caratteri.

Nota: Il parametro opzionale raw_output è stato aggiunto in PHP 5.0.0, e come default vale FALSE

Questa funzione ha il medesimo scopo dell'utilità di linea di comando md5sum.

Vedere anche md5(), crc32() e sha1_file().

md5

(PHP 3, PHP 4, PHP 5)

md5 -- Calcola il valore md5 di una stringa

Descrizione

string md5 ( string str [, bool raw_output] )

Calcola il valore md5 della stringa str utilizzando il RSA Data Security, Inc. MD5 Message-Digest Algorithm, e restituisce tale valore. L'hash prodotto è un numero esadecimale di 32 caratteri. Se il secondo parametro raw_output è impostato a TRUE, il valore md5 è restituito nel formato binario raw con una lunghezza di 16 caratteri.

Nota: Il parametro opzionale raw_output è stato aggiunto in PHP 5.0.0, e come default vale FALSE

Esempio 1. Esempio di uso di md5()

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
    exit;
}
?>

Vedere anche crc32(), md5_file() e sha1().

metaphone

(PHP 4, PHP 5)

metaphone -- Calcola la chiave metaphone di una stringa

Descrizione

string metaphone ( string str [, int phones] )

Calcola la chiave metaphone di str.

In modo simile a soundex() la funzione crea la medesima chiave per parole con il medesimo suono. Questa funzione è più accurata che soundex() poiché conosce le regole di base della pronuncia inglese. Le chiavi metaphone generate hanno lunghezza variabile.

La chiave Metaphone è stata sviluppata da Lawrence Philips <lphilips at verity dot com>. Viene descritta in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

money_format

(PHP 4 >= 4.3.0, PHP 5)

money_format -- Formattazione di un numero come stringa monetaria

Descrizione

string money_format ( string format, float number )

money_format() restituisce una versione formattata di number. Questa funzione è un'interfaccia alla funzione C strfmon(), con la differenza che questa funzione converte un solo numero alla volta.

Nota: La funzione money_format() esiste solo se il sistema suppporta strfmon. Ad esempio, Windows non lo supporta perciò la funzione money_format() non è definita su Windows.

LA specifica del formato consiste nella seguente sequenza:

  • un carattere %

  • un flag opzionale flags

  • la lunghezza del campo, opzionale

  • la precisione a sinistra, opzionale

  • la precisione a destra, opzionale

  • un carattere di conversione, obbligatorio

Flag. Si possono utilizzare uno o più dei seguenti flag:

=f

Il carattere = seguito da un singolo carattere (singolo byte) f è utilizzato come carattere di riempimento numerico. Il carattere di default è lo spazio.

^

Disabilita l'utilizzo del raggruppamento dei caratetrei (come definito nelle impostazioni locali).

+ oppure (

Specifica lo stile di formattazione per i numeri positivi e negativi. Se si utilizza +, sarà utilizzato l'equivalente valore locale per + e -. Se si utilizza (, i valori negativi saranno racchiusi tra parentesi. Se non si da specifica, il default è +.

!

Sopprime il simbolo della moneta nella stringa di output.

-

Se presente, rende tutti i campi giustificati a sinistra (riempiti a a destra), il default prevede i campi allineati a destra (riempiti a sinistra).

Dimensioni del campo.

w

Una stringa numerica che specifica la lunghezza minima del campo. Il campo sarà allineato a destra a meno di non avere impostato il flag -. Il valore di default è 0 (zero).

Precisione a sinistra.

#n

Sono attesi un numero massimo di (n) numeri a sinistra del carattere decimale (es. il punto decimale). Solitamente si utilizza per mantenere allineato l'output nella medesima colonna, utilizzando il carattere di riempimento, se il numero delle cifre è inferiore a n. Se il numero delle cifre è superiore a n, questa specifica viene ignorata.

Se il raggruppamento delle cifre non è soppresso tramite ^, saranno inseriti i separatori di raggruppamento prima dei caratteri di riempimento (se presenti). I separatori di gruppo non saranno applicati ai caratteri di riempimento, anche se il carattere di riempimento è un numero.

Per garantire l'allineamento, ogni carattere che, nella stringa formattata, appare prima o dopo il numero, tipo il simbolo della moneta o il segno, viene riempito con gli spazi necessari affinché la corrispondente stringa risultante da un valore positivo o negativo abbia la medesima lunghezza.

Precisione di destra .

.p

Un punto seguito da un numero di cifre (p) dopo il carattere decimale. Se il valore di p è 0 (zero), il carattere decimale e le cifre alla sua destra saranno omesse. Se non vi è indicazione della precisione a destra, il default sarà preso della impostazioni locali. L'importo sarà arrontondato alle cifre decimali richieste prima di essere formattato.

Caratteri di conversione .

i

Il numero sarà formattato in base alle impostazioni internazionali locali (es. le impostazioni locali USA: USD 1,234.56).

n

Il numero sarà formattato in base alle locali impostazioni nazionali di moneta (es. per de_DE: DM1.234,56).

%

Restituisce il carattere %.

Nota: La categoria LC_MONETARY delle impostazioni locali influisce sul comportamento di questa funzione. Utilizzare setlocale() per impostare il default appropriato prima di utilizzare questa funzione.

I caratteri prima e dopo la stringa di formattazione saranno restituiti immutati.

Esempio 1. Esempio di uso di money_format()

Per illustrare il funzionamento della funzione utilizzeremo diversi formati di impostazioni locali.

<?php

$number = 1234.56;

// stampa nel formato internazionale per l'impostazione  en_US 
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";  
// USD 1,234.56

// Fromato italiano con 2 cifre decimali`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// L. 1.234,56

// Numeri negativi
$number = -1234.5672;

// Formato nazionale US, Utilizzo di () per i numeri negativi
// e 10 cifre di precisione a sinistra
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($        1,234.57)

// Simile al precente con 2 cifre di precisione a destra
// e '*' come carattere di riempimento
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)
    
// Giustificazione a sinistra, con 14 posizioni di lunghezza, 8 cifre di 
// precisione a sinistra, 2 di precisione a destra, senza carattere di raggruppamento
// e utilizzando l'impostazione locale de_DE.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// DEM 1234,56****

// Qualche carattere prima e dopo la specifica di formattazione
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is  GBP 1,234.56 (after a 10% discount)

?>

Vedere anche setlocale(), number_format(),sprintf(), printf() e sscanf().

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5)

nl_langinfo --  Ricava informazioni sulla lingua e le impostazioni locali

Descrizione

string nl_langinfo ( int item )

La funzione nl_langinfo() viene utilizzata per accedere agli elementi delle impostazioni locali. Diversamente da localeconv(), che restituisce tutti gli elementi, nl_langinfo() permette di scegliere l'elemento specifico.

Se il parametro item non è valido, la funzione restituisce FALSE.

Il parametro item può essere un numero intero od il nome della costante indicante l'elemento. Di seguito viene riportata la lista dei nomi per item con le rispettive descrizioni. Alcune di quest costanti possono non essere definite in alcune impostazioni locali.

Tabella 1. Costanti di nl_langinfo

CostanteDescrizione
Costanti per la categoria LC_TIME
ABDAY_(1-7)Nome abbreviato dell'n-esimo giorno della settimana.
DAY_(1-7)Nome dell'n-esimo giorno della settimana (DAY_1 = domenica).
ABMON_(1-12)Nome abbreviato dell'n-esimo mese dell'anno.
MON_(1-12)Nome dell'n-esimo mese dell'anno.
AM_STRStringa per ante meridiano.
PM_STRStringa per pomeridiano.
D_T_FMTStringa di formato che può essere usata con strftime() per rappresentare la data e l'ora.
D_FMTStringa di formato che può essere usata con strftime() per rappresentare la data.
T_FMTStringa di formato che può essere usata con strftime() per rappresentare l'ora.
T_FMT_AMPMStringa di formato che può essere usata con strftime() per rappresentare la data e l'ora nel formato a 12 ore con ante/post meridiano.
ERAEra alternativa.
ERA_YEARFormato dell'anno nell'era alternativa.
ERA_D_T_FMTFormato di data e ora nell'era alternativa (la stringa può essere usata con strftime()).
ERA_D_FMTFormato della data nell'era alternativa (la stringa può essere usata con strftime()).
ERA_T_FMTFormato dell'ora nell'era alternativa (la stringa può essere usata con strftime()).
Costanti per la categoria LC_MONETARY
INT_CURR_SYMBOLSimbolo internazionale della divisa.
CURRENCY_SYMBOLSimobolo locale della moneta.
CRNCYSTRStesso valore di CURRENCY_SYMBOL.
MON_DECIMAL_POINTCarattere separatore delle cifre decimali.
MON_THOUSANDS_SEPSeparatore delle migliaia (gruppi di tre cifre).
MON_GROUPINGCome l'elemento di raggruppamento.
POSITIVE_SIGNSegno per i valori positivi.
NEGATIVE_SIGNSegno per i valori negativi.
INT_FRAC_DIGITSNumero di cifre frazionarie internazionale.
FRAC_DIGITSNumero di cifre frazionarie locale.
P_CS_PRECEDESResituisce 1 se CURRENCY_SYMBOL precede un valore positivo.
P_SEP_BY_SPACEResituisce 1 se uno spazio separa CURRENCY_SYMBOL da un valore positivo.
N_CS_PRECEDESResituisce 1 se CURRENCY_SYMBOL precede un valore negativo.
N_SEP_BY_SPACEResituisce 1 se uno spazio separa CURRENCY_SYMBOL da un valore negativo.
P_SIGN_POSN

  • Restituisce 0 se le parentesi circondano il valore ed il simbolo di moneta.

  • Restituisce 1 se il segno precede il valore ed il simbolo di moneta.

  • Restituisce 2 se il segno segue il valore ed il simbolo di moneta.

  • Restituisce 3 se il segno precede immediatamente il simbolo di moneta.

  • Restituisce 4 se il segno segue immediatamente il simbolo di moneta.

N_SIGN_POSN
Costanti per la categoria LC_NUMERIC
DECIMAL_POINTCarattere separatore delle cifre decimali.
RADIXCHARCome DECIMAL_POINT.
THOUSANDS_SEPSeparatore delle migliaia (gruppi di tre cifre).
THOUSEPCome THOUSANDS_SEP.
GROUPING 
Costanti per la categoria LC_MESSAGES
YESEXPRStringa regex per il riconoscimento di 'si'.
NOEXPRStringa regex per il riconoscimento di 'no'.
YESSTRTesto da visualizzare per 'si'.
NOSTRTesto da visualizzare per 'no'.
Costanti per la categoria LC_CTYPE
CODESETRestituisce una stringa con il nome della codifica dei caratteri.

Nota: Questa funzione non è implementata su piattaforme Windows

Vedere anche setlocale() e localeconv().

nl2br

(PHP 3, PHP 4, PHP 5)

nl2br --  Inserisce il tag HTML di 'a capo' prima di tutti i caratteri di 'a capo' della stringa

Descrizione

string nl2br ( string string )

Restituisce la stringa string con '<br />' inserito prima di tutti i newline.

Nota: A partire dal PHP 4.0.5, nl2br() è conforme a XHTML. Tutte le versioni precedenti alla 4.0.5 restituiscono la string con '<br>' invece di '<br />' inserito prima degli 'a capo'.

Esempio 1. Esempio di uso di nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

this will output :

foo isn't<br />
 bar

Vedere anche htmlspecialchars(), htmlentities(), wordwrap() e str_replace().

number_format

(PHP 3, PHP 4, PHP 5)

number_format -- Formatta un numero con i grupppi delle migliaia

Descrizione

string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] )

La funzione number_format() restituisce una versione formattata di number. Questa funzione accetta uno, due, o quattro parametri (non tre).

Se si specifica soltanto un parametro, il number sarà formattato senza decimali, ma con la virgola (",") per suddividere le migliaia.

Se sono specdificati due parametri, il number sarà formattato con tante cifre decimali quanto indicato in decimals, precedute dal punto ("."), e con la virgola (",") come separatore delle migliaia.

Se sono indicati tutti i quattro parametri, il number sarà formattato con decimals cifre decimali, identificate dal carattere dec_point anziché dal punto (".") e con thousands_sep, invece della virgola (",") come separatore delle migliaia.

Sarà utilizzato solo il primo carattere di thousands_sep. Ad esempio, se si indica foo come thousands_sep per il numero 1000, la funzione number_format() restituirà 1f000.

Esempio 1. Esempio di uso di number_format()

Ad esempio, la notazione francese solitamente utilizza due decimali, la virgola (',') come separatore decimale, e lo spazio (' ') come separatore delle migliaia. Questo può essere ottenuto con:

<?php

$number = 1234.56;

// Notazione inglese (default)
$english_format_number = number_format($number);
// 1,235

// Notazione francese
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// notazione inglese senza separatore delle migliaia
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

Vedere anche sprintf(), printf() e sscanf().

ord

(PHP 3, PHP 4, PHP 5)

ord -- Restituisce il valore ASCII di un carattere

Descrizione

int ord ( string string )

Restituisce il valore ASCII del primo carattere di string. Questa è la funzione complementare di chr().

Esempio 1. Esempio di uso di ord()

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

Qui si può reperire la tabella ASCII: http://www.asciitable.com.

Vedere anche chr().

parse_str

(PHP 3, PHP 4, PHP 5)

parse_str -- Suddivide una stringa in variabili

Descrizione

void parse_str ( string str [, array arr] )

Suddivide la stringa str come se fosse una stringa di query passata via URL ed imposta le variabili con visibilità locale. Se si indica il secondo parametro arr, la variabili sono memorizzate come elementi della matrice arr.

Nota: Il supporto per il secondo parametro, opzionale, è stato aggiunto in PHP 4.0.3.

Nota: Per avere la QUERY_STRING corrente occorre utilizzare la variabile $_SERVER['QUERY_STRING']. Inoltre è opportuno leggere la sezione sulle variabili esterne al PHP.

Nota: L'impostazione magic_quotes_gpc influisce sull'output di questa funzione, poichè parse_str() utilizza lo stesso meccanismo che usa il PHP per compilare le variabili $_GET, $_POST, ecc.

Esempio 1. Esempio di uso di parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

Vedere anche parse_url(), pathinfo(), get_magic_quotes_gpc() e urldecode().

print

(PHP 3, PHP 4, PHP 5)

print -- Visualizza una stringa

Descrizione

int print ( string arg )

Visualizza arg. Restituisce sempre 1,

In realtà print() non è una funzione (è un costrutto del linguaggio) pertanto non sono richieste le parentesi per la lista degli argomenti.

Esempio 1. Esempio di uso di print()

<?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be 
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

print "escaping characters is done \"Like this\".";

// Si possono usare variabili all'interno di istruzioni print
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// Si possono usare le matrici
$bar = array("value" => "foo");

print "this is {$bar['value']} !"; // this is foo !

// Utilizzando l'apice singolo sarà visualizzato il nome della variabile e non il contenuto
print 'foo is $foo'; // foo is $foo

// Se non si usa altri caratteri, si può semplicemente visualizzare il contenuto della variabile
print $foo;          // foobar

print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?>

Per breve discussione tra print() e echo(), vedere la pagina di FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

Vedere anche echo(), printf(), e flush().

printf

(PHP 3, PHP 4, PHP 5)

printf -- Visualizza una stringa formattata

Descrizione

int printf ( string format [, mixed args [, mixed ...]] )

Produce un output formattato secondo le specifiche del parametro format, che viene descritto nella documentazione di sprintf().

Restituisce la lunghezza della stringa visualizzata.

Vedere anche print(), sprintf(), vprintf(), sscanf(), fscanf() e flush().

quoted_printable_decode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

quoted_printable_decode --  Converte una stringa 'quoted-printable' in una stringa a 8 bit

Descrizione

string quoted_printable_decode ( string str )

Questa funzione restituisce una stringa a 8 bit corrispondente alla codifica della stringa 'quoted-printable' ( in base a RFC2045, sezione 6.7, e non RFC2821, sezione 4.5.2, punti addizionali non sono rimossi dall'inizio della linea). Questa funzione è simile a imap_qprint(), tranne che quest'ultima richiede il modulo IMAP per essere utilizzata.

quotemeta

(PHP 3, PHP 4, PHP 5)

quotemeta -- Quota i meta caratteri

Descrizione

string quotemeta ( string str )

Restituisce una versione di str con il carattere backslash (\) davanti ai seguenti caratteri:
. \ + * ? [ ^ ] ( $ )

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche addslashes(), htmlentities(), htmlspecialchars(), nl2br() e stripslashes().

rtrim

(PHP 3, PHP 4, PHP 5)

rtrim --  Rimuove gli spazi (ed altri caratteri) dalla fine della stringa

Descrizione

string rtrim ( string str [, string charlist] )

Nota: Il secondo parametro è stato aggiunto nella versione 4.1.0 di PHP.

Questa funzione restituisce la stringa str a cui sono stati rimossi gli spazi finali. Senza la specifica del secondo parametro rtrim() rimuoverà i seguenti caratteri:

  • " " (ASCII 32 (0x20)), spazio ordinario.

  • "\t" (ASCII 9 (0x09)), tab.

  • "\n" (ASCII 10 (0x0A)), newline (line feed).

  • "\r" (ASCII 13 (0x0D)), carriage return.

  • "\0" (ASCII 0 (0x00)), il byte NUL.

  • "\x0B" (ASCII 11 (0x0B)), il tab verticale.

Si può anche specificare i caratteri che si desidera rimuovere, indicandoli nel parametro charlist. Quest'ultimo è costituito da un semplice elenco di caratteri da rimuovere. Con .. si può specificare un range di caratteri.

Esempio 1. Esempio di uso di rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$trimmed = rtrim($text);
// $trimmed = "\t\tThese are a few words :) ..."
$trimmed = rtrim($text, " \t.");
// $trimmed = "\t\tThese are a few words :)"
$clean = rtrim($binary, "\x00..\x1F");
// rimuove i caratteri di controllo ASCII dalla fine di $binary 
// (from 0 to 31 inclusive)

?>

Vedere anche trim() e ltrim().

setlocale

(PHP 3, PHP 4, PHP 5)

setlocale -- Imposta i parametri di localizzazione

Descrizione

string setlocale ( mixed category, string locale [, string ...] )

string setlocale ( mixed category, array locale )

Il parametro category è una costante (o stringa) che indica la categoria di parametri coinvolta nelle impostazioni locali:

  • LC_ALL la somma di tutte le seguenti categorie

  • LC_COLLATE per i confronti di stringhe, vedere strcoll()

  • LC_CTYPE per la classificazione dei caratteri e le conversioni, ad esempio strtoupper()

  • LC_MONETARY per localeconv()

  • LC_NUMERIC per il separatore decimale (vedere anche localeconv())

  • LC_TIMEper la formattazione di data e orario con strftime()

Nota: Dalla versione 4.2.0 di PHP il passaggio di category come stringa è deprecato; piuttosto utilizzare le precedenti costanti. Passare quelle costanti come stringa (all'interno di apici) darà come risultato un warning.

Se il parametro locale è NULL oppure una stringa vuota "", i nomi locali saranno impostati dai valori delle omonime variabili d'ambiente, oppure da "LANG".

Se il parametro locale vale "0", le impostazioni localizzate non vengono toccate, ma vengono restituiti i valori correnti.

Se il parametro locale è una matrice oppure è seguito da parametri addizionali, allora si tenterà di impostare ciascun elemento, o parametro, fino a quando non si ha successo. Questo è utile se l'impostazione locale è nota sotto differenti nomi in sistemi differenti oppure per prevedere più casistiche qualora alcune non fossero disponibili.

Nota: Il passaggio di molteplici impostazioni non è possibile prima di PHP 4.3.0.

La funzione restituisce le nuove impostazioni locali, oppure FALSE se la funzionalità di localizzazione non è implementata sul sistema, se l'impostazione richiesta non esiste, oppure se il nome della categoria non è valida. Un nome di categoria non valido genera anche un warning. I nomi delle categoria possono essere trovati nella RFC 1766 e ISO 639. Differenti sistemi hanno differenti schemi di denominazione delle impostazioni locali.

Nota: Il valore restituito da setlocale() dipende dal sistema su cui gira il PHP. La funzione restituisce fedelmente quello che la funzione di sistema restituisce.

Suggerimento: Gli utenti di Windows potranno trovare informazioni utili per il parametro locale sul sito MSDN di Microsoft. Le stringhe di linguaggio supportate possono essere trovate in http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp e le stringhe identificanti i paesi/regioni alla pagina http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp. I sistemi Windows supportano la codifica a tre lettere ISO 3166-Alpha-3 per identificare i paesi/regioni ISO 3166-Alpha-3, tale codifica può essere reperita nel sito . .

Esempio 1. Esempi di uso di setlocale()

<?php
/* Impostazioni locali in tedesco */
setlocale(LC_ALL, 'nl_NL');

/* Visualizza: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* tenta i differenti nomi possibili per le impostazioni tedesche, dal PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Esempio 2. Esempio di uso di setlocale() perWindows

<?php
/* Impostazioni locali in tedesco */
setlocale(LC_ALL, 'nld_nld');

/* Visualizza: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* tenta i differenti nomi possibili per le impostazioni tedesche, dal PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>

sha1_file

(PHP 4 >= 4.3.0, PHP 5)

sha1_file -- Calcola l'hash sha1 di un file

Descrizione

string sha1_file ( string filename [, bool raw_output] )

Calcola l'hash sha1 di filename usando il US Secure Hash Algorithm 1, e restituisce l'hash. L'hash è un numero esadecimale di 40 caratteri.

Elenco dei parametri

filename

Il nome del file

raw_output

Quando è impostato a TRUE, l'hash sha1 è restituito in formato binario con una lunghezza di 20 caratteri. Per default vale FALSE.

Valori restituiti

Restituisce una stringa se ha successo, FALSE negli altri casi.

Log delle modifiche

VersioneDescrizione
5.0.0 Aggiunto il parametro raw_output.
5.1.0 Modificata la funzione per utilizzare lr API streams. Ciò significa che si può utlizzare la funzione con i vari warppers, tipo sha1_file('http://example.com/..')

sha1

(PHP 4 >= 4.3.0, PHP 5)

sha1 -- Calcola l'hash sha1 di una stringa

Descrizione

string sha1 ( string str [, bool raw_output] )

Calcola l'hash sha1 di str usando il US Secure Hash Algorithm 1, e restituisce l'hash. L'hash è un numero esadecimale di 40 caratteri. Se il parametro opzionale raw_output è impostato a TRUE, allora l'hash sha1 è restituito in formato binario con una lunghezza di 20 caratteri.

Nota: Il parametro opzionale raw_output è stato aggiunto in PHP 5.0.0 ed ha come default FALSE

Esempio 1. Esempio di uso di sha1()

<?php
$str = 'apple';
                     
if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
    exit;
}
?>

Vedere anche sha1_file(), crc32() e md5()

similar_text

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

similar_text --  Calcola la similitudine tra due stringhe

Descrizione

int similar_text ( string first, string second [, float &percent] )

Questa funzione calcola la similitudine tra due stringhe come descritto in Oliver [1993]. Attenzione che questa implementazione non utilizza lo stack come nel psuedo codice di Oliver, ma utilizza chiamate ricorsive che possono o non possono velocizzare l'intero processo. Occorre anche rilevare che la complessità di questo algoritmo è O(N**3) dove N è la lunghezza della stringa più lunga.

Passando per riferimento il terzo argomento, similar_text() la funzione calcolerà la similitudine in percentuale. La funzione restituisce il numero di caratteri corrispondenti in entrambe le stringhe.

Vedere anche levenshtein() e soundex().

soundex

(PHP 3, PHP 4, PHP 5)

soundex -- Calcola la chiave soundex di una data stringa

Descrizione

string soundex ( string str )

Calcola la chiave soundex di str.

Le chiavi soundex hanno la caratteristica di essere simili per parole con pronuncia similare, e pertanto possono essere utilizzate per semplificare le ricerche in archivi nei casi in cui si conosce la pronuncia ma non la sillabazione. Questa funzione soundex restituisce una stringa di 4 caratteri di cui il primo è una lettera.

Questa particolare funzione soundex è stata descritta da Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

Esempio 1. Esempio di uso di Soundex

<?php
soundex("Euler")       == soundex("Ellery");    // E460
soundex("Gauss")       == soundex("Ghosh");     // G200
soundex("Hilbert")     == soundex("Heilbronn"); // H416
soundex("Knuth")       == soundex("Kant");      // K530
soundex("Lloyd")       == soundex("Ladd");      // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?>

Vedere anche levenshtein(), metaphone() e similar_text().

sprintf

(PHP 3, PHP 4, PHP 5)

sprintf -- Restituisce una stringa formattata

Descrizione

string sprintf ( string format [, mixed args [, mixed ...]] )

La funzione restituisce una stringa formattata in base al parametro format.

La stringa di formato è composta da 0 o più direttive: i caratteri ordinari (escluso il %) sono copiati direttamente nel risultato, mentre le specifiche di conversione, scaricano il proprio parametro. Queste note si applicano alle funzioni fprintf(), sprintf() e printf().

Ciascun parametro di conversione consiste nel segno percento (%), seguito da uno più dei seguenti elementi nell'ordine si ha:

  1. Un parametro opzionale di specifica del segno che forza la presenza del segno (- oppure +) in caso di numero. Per default, si usa soltanto il segno - se il numero è negativo. Questo parametro forza i numeri positiva ad avere il segno +, ed è stato aggiunto in PHP 4.3.0.

  2. Un parametro opzionale per la specifica del riempimento che indica quale carattere sarà utilizzato per completare la stringa risultante in modo da raggiungere la dimensione richiesta. Questo può essere uno spazio oppure uno 0 (il carattere zero). Per default si completa con spazi. Un carattere di riempimento alternativo può essere indicato anteponendo a questo l'apice singolo ('). Vedere gli esempi seguenti.

  3. Un parametro opzionale per la specifica dell'allineamento che indica se la stringa risultante debba essere giustificata a destra o a sinistra. Per default le stringhe sono giustificate a destra; il carattere - forza la giustificazione a sinistra.

  4. Un parametro numerico opzionale per la specifica della dimensione che indica di quanti caratteri (come minimo) debba essere lunga la stringa.

  5. Un parametro opzionale per indicare la precisione per indicare quante cifre decimali debbano essere visualizzate per i numeri in virgola mobile. Quando si usa questo parametro in una stringa si impone come una sorta di punto di cutoff, esso imposta un limite alla lunghezza della stringa.

  6. Una specifica di tipo che indica il tipo di dati dell'argomento. I possibili tipi sono:

    % - il carattere percento. Nessun argomento è richiesto.
    b - l'argomento è trattato come un intero e sarà presentato come numero binario.
    c - l'argomento è trattato come un intero e sarà presentato come carattere ASCII del valore corrispondente.
    d - l'argomento è trattato come un intero e sarà presentato come un numero decimale con segno.
    e - l'argomento è reso con notazione scientifica (ad esempio 1.2e+2).
    u - l'argomento è trattato come un intero e sarà presentato come un numero decimale senza segno.
    f - l'argomento è trattato come un float e sarà presentato come un numero in virgola mobile (influenzato dalle impostazioni locali).
    F - l'argomento è trattato come un numero float, e sarà presentato come un numero in virgola mobile (non influenzato dalle impostazioni locali). Disponibile da PHP 4.3.10 e PHP 5.0.3.
    o - l'argomento è trattato come un intero e sarà presentato come un numero ottale.
    s - l'argomento sarà trattato e presentato come una stringa.
    x - l'argomento sarà trattato come un intero e presentato in forma esadecimale (con le lettere in minuscolo).
    X - l'argomento è trattato come un intero e sarà presentato come un numero esadecimale (con le lettere maiuscole).

A partire dal PHP 4.0.6 la stringa di formato supporta lo scambio dei parametri. Eccone un esempio:

Esempio 1. Scambio dei parametri

<?php
$format = "There are %d monkeys in the %s";
printf($format, $num, $location);
?>
Questo esempio visualizza: "There are 5 monkeys in the tree". Ma supponiamo di volere creare una stringa di formato in file a parte, perchè vogliamo rendere la procedura internazionale; e pertanto riscriviamo l'esempio come:

Esempio 2. Scambio dei parametri

<?php
$format = "The %s contains %d monkeys";
printf($format, $num, $location);
?>
Ora abbiamo un problema. L'ordine dei segnaposto nella stringa di formato non coincide con l'ordine dei parametri. Si vorrebbe potere lasciare inalterato il codice e potere indicare a quale parametro si riferisce il segnaposto. Ciò può essere fatto modificando la stringa di formato come:

Esempio 3. Scambio dei parametri

<?php
$format = "The %2\$s contains %1\$d monkeys";
printf($format, $num, $location);
?>
Un beneficio aggiuntivo è che si possono ripetere i segnaposto senza dovere ripetere i parametri. Ad esempio:

Esempio 4. Scambio di parametri

<?php
$format = "The %2\$s contains %1\$d monkeys.
           That's a nice %2\$s full of %1\$d monkeys.";
printf($format, $num, $location);
?>

Vedere anche printf(), sscanf(), fscanf(), vsprintf() e number_format().

Esempi

Esempio 5. Esempi di uso di printf()

<?php
$n =  43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// attenzione che i doppi %%, visualizzano il carattere '%' 
printf("%%b = '%b'\n", $n); // rappresentazione binaria
printf("%%c = '%c'\n", $c); // visualizza un carattere ASCII, coma la funzione chr()
printf("%%d = '%d'\n", $n); // rappresentazione di un intero standard
printf("%%e = '%e'\n", $n); // notazione scientifica
printf("%%u = '%u'\n", $n); // rappresentazione di un intero positivo privo di segno
printf("%%u = '%u'\n", $u); // rappresentazione di un intero negativo privo di segno
printf("%%f = '%f'\n", $n); // rappresentazine in virgola mobile
printf("%%o = '%o'\n", $n); // rappresentazione ottale
printf("%%s = '%s'\n", $n); // stringa
printf("%%x = '%x'\n", $n); // rappresentazione esadecimale (minuscolo)
printf("%%X = '%X'\n", $n); // rappresentazione esadecimale (maiuscolo)
printf("%%+d = '%+d'\n", $n); // indicazione del segno su un intero positivo
printf("%%+d = '%+d'\n", $u); // indicazione del segno su un intero negativo
?>

L'output di questo programma sarà:

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Esempio 6. printf(): specifiche di stringa

<?php
$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n",      $s); // output standard di stringa
printf("[%10s]\n",    $s); // accostamento a destra con spazi
printf("[%-10s]\n",   $s); // accostamento a sinistra con spazi
printf("[%010s]\n",   $s); // completamento con zero funziona anche con le stringhe
printf("[%'#10s]\n",  $s); // utilizza il carattere di riempimento  '#'
printf("[%10.10s]\n", $t); // accostamento a sinistra con taglio a 10 caratteri
?>

L'output di questo programma sarà:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Esempio 7. sprintf(): interi completati con zeri

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Esempio 8. sprintf(): formattazione della moneta

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money visualizzerà "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted visualizzerà "123.10"
?>

Esempio 9. sprintf(): notazione scientifica

<?php
$number = 362525200;

echo sprintf("%.3e", $number); // visualizza 3.63e+8
?>

sscanf

(PHP 4 >= 4.0.1, PHP 5)

sscanf --  Analizza l'input da una string in base al formato

Descrizione

mixed sscanf ( string str, string format [, mixed &...] )

La funzione sscanf() è la versione di input di printf(). sscanf() legge dalla stringa str e ne interpreta il contenuto basandosi sul parametro format, che viene descritto nella documentazione di sprintf(). Se vengono passati soltanto due parametri, i valori ricavati sono restituiti in una matrice. Altrimenti, se viene fornito il terzo parametro, la funzione restituire il numero dei valori assegnati. Il terzo parametro deve essere passato per riferimento.

Qualsiasi tipo di spazio nella stringa di formato identifica il corrispondente spazio nella stringa di input. Ciò significa che anche i tab \t nella stringa di formato possono identificare un carattere di spazio nella stringa di input.

Esempio 1. Esempio di uso di sscanf()

<?php
// getting the serial number
$serial = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?>
Se viene fornito il terzo parametro, la funzione restituire il numero dei valori assegnati.

Esempio 2. sscanf() - utilizzo del parametro opzionale

<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";
?>

Vedere anche fscanf(), printf() e sprintf().

str_ireplace

(PHP 5)

str_ireplace --  Versione insensibile alle miuscole/minuscole di str_replace()

Descrizione

mixed str_ireplace ( mixed search, mixed replace, mixed subject [, int &count] )

Questa funzione restituisce una stringa od una matrice con tutte le occorrenze di search in subject (non distinguendo tra maiuscole e minuscole) sostituite con il valore replace Se non occorrono particolari regole di sostituzione si dovrebbe utilizzare questa funzione anziché eregi_replace() o preg_replace() con il parametro i.

Se il parametro subject è una matrice, allora la ricerca e la sostituzione viene eseguita su ogni elemento di subject, ed il valore restituito è pure quello una matrice.

Se search e replace sono matrici, allora str_ireplace() prende i valori da ciascuna matrice e li utilizza per fare la ricerca e la sostituzione in subject. Se replace ha meno valori di search, allora si utilizza una stringa vuota per sostituire i valori mancanti. Se search è una matrice e replace è una stringa; allora questa stringa viene utilizzata per sostituire ogni valore di search.

Esempio 1. Esempio di uso di str_ireplace()

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
?>

Questa funzione è sicura con i dati binari.

Nota: Dal PHP 5.0.0 il numero dei testi trovati e sostituiti sarà restituito in count che deve essere passato per riferimento. Prima del PHP 5.0.0 questo parametro non è disponibile.

Vedere anche: str_replace(), ereg_replace(), preg_replace() e strtr().

str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_pad --  Riempie una stringa con un'altra stringa portando la prima ad una lunghezza pre-determinata

Descrizione

string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]] )

Questa funzione restituisce la stringa input riempita per una data lunghezza a sinistra, a destra, o in entrambi i lati. Se il parametro opzionale pad_string non viene passato, l' input viene completato con spazi, altrimenti viene completato con i caratteri di pad_string fino al limite.

Il parametro pad_type, opzionale, può valere STR_PAD_RIGHT, STR_PAD_LEFT, oppure STR_PAD_BOTH. Se non si indica pad_type lo si assume pari a STR_PAD_RIGHT.

Se il valore di pad_length è negativo oppure minore della stringa di input, non si ha nessun completamento.

Esempio 1. Esempio di uso di str_pad()

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

Nota: Il parametro pad_string può essere troncato se il numero di caratteri necessari al completamento non può essere diviso per la lunghezza di pad_string.

str_repeat

(PHP 4, PHP 5)

str_repeat -- Ripete una stringa

Descrizione

string str_repeat ( string input, int multiplier )

Restituisce il parametro input_str ripetuto tante volte quanto indicato in multiplier. multiplier deve essere maggiore o uguale a 0. Se multiplier è impostato a zero, la funzione restituisce una stringa vuota.

Esempio 1. Esempio di uso di str_repeat()

<?php
echo str_repeat("-=", 10);
?>

Il precedente esempio visualizzerà:

-=-=-=-=-=-=-=-=-=-=

Vedere anche for, str_pad() e substr_count().

str_replace

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

str_replace --  Sostituisce tutte le occorrenze della stringa cercata con la stringa di sostituzione

Descrizione

mixed str_replace ( mixed search, mixed replace, mixed subject [, int &count] )

Questa funzione restituisce una stringa, od una matrice, con tutte le occorrenze di search nella stringa subject sostituite con il valore del parametro replace. Se non occorrono particolari capacità di sostituzione (tipo le espressioni regolari), si dovrebbe utilizzare questa funzione invece di ereg_replace() o preg_replace().

Dal PHP 4.0.5, ogni parametro di str_replace() può essere una matrice.

Avvertimento

Nelle versioni di PHP antecedenti la 4.3.3 esisteva un errore quando si utilizzano le matrici per search e replace che faceva ignorare gli indici vuoti di search avanzando il puntatore interno di replace, questo è stato corretto dal PHP 4.3.3, ogni script che si basava su questo errore, per potere simulare il comportamento originale, dovrebbe rimuovere gli elementi vuoti prima di richiamare questa funzione.

Se subject è una matrice, allora la ricerca e la sostituzione sono eseguite su ogni elemento di subject, ed il valore restituito è pure una matrice.

Se search e replace sono matrici, allora str_replace() prende i valori da ciascuna matrice e li usa per svolgere la ricerca e la sostituzione in subject. Se replace ha meno valori di search, allora si utilizzeranno delle stringhe vuote per completare i rimanenti valori da sostituire. Se search è una matrice e replace è una stringa, allora questa stringa di sostituzione sarà utilizzata per ogni valore di search. Il contrario non avrebbe senso.

Esempio 1. Esempi di uso di str_replace()

<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// Use of the count parameter is available as of PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Nota: Dal PHP 5.0.0 il numero di stringhe trovate e e sostituite, sarà restituito nel parametro, passato per riferimento, count. Nelle versioni antecedenti al PHP 5.0.0 questo parametro non è disponibile.

Vedere anche: str_ireplace(), substr_replace(), ereg_replace(), preg_replace() e strtr().

str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 -- Esegue la trasformazione rot13 di una stringa

Descrizione

string str_rot13 ( string str )

Questa funzione esegue la codifica ROT13 della stringa str e restituisce la stringa risultante. La codifica ROT, semplicemente, sposta ogni lettera di 13 posizioni nell'alfabeto, e lascia immutati i caratteri non alfabetici. La codifica e la decodifica sono eseguiti dalla stessa funzione, passando alla funzione una stringa codificata, questa restituirà la stringa originaria.

Esempio 1. Esempio di uso di str_rot13()

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

Nota: Il comportamento di questa funzione era errato fino al PHP 4.3.0. nelle versioni precedenti a questa, veniva modificato anche il parametro str se veniva passato per riferimento.

str_shuffle

(PHP 4 >= 4.3.0, PHP 5)

str_shuffle -- Mischia una stringa in modo casuale

Descrizione

string str_shuffle ( string str )

str_shuffle() mischia una stringa. Viene generata una di tute le possibili permutazioni.

Esempio 1. Esempio di uso di str_shuffle()

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

Vedere anche: shuffle() e rand().

str_split

(PHP 5)

str_split --  Converte una stringa in una matrice

Descrizione

array str_split ( string string [, int split_length] )

Converte una stringa in una matrice. Se viene passato il parametro opzionale split_length, la matrice restituita sarà composta da segmenti, ciascuno della lunghezza di split_length caratteri, in caso contrario ciascun segmento sarà lungo un carattere.

FALSE è restituito se split_length è minore di 1. Se split_length supera la lunghezza di string, sarà restituita l'intera stringa come primo (ed unico) elemento della matrice.

Esempio 1. Esempi di uso di str_split()

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

L'output potrà essere:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo 
    [2] => Fri
    [3] => end
)

Esempio 2. Esempi relativi a str_split()

<?php

$str = "Hello Friend";

echo $str{0};  // H
echo $str{8};  // i

// Creates: array('H','e','l','l','o',' ','F','r','i','e','n','d')
$arr1 = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

?>

Vedere anche: chunk_split(), preg_split(), split(), count_chars(), str_word_count() e for.

str_word_count

(PHP 4 >= 4.3.0, PHP 5)

str_word_count --  Restituisce informazioni sulle parole utilizzate in una stringa

Descrizione

mixed str_word_count ( string string [, int format [, string charlist]] )

Conta il numero di parole presenti in string. Se non viene indicato il parametro opzionale format, allora la funzione restituirà un intero indicante il numero di parole trovate. Nel caso in cui sia specificato format, la funzione restituisce una matrice il cui contenuto dipende dal parametro format. I possibili valori per format ed i rispettivi output sono elencati di seguito.

Per gli scopi di questa funzione 'parola' è definita come testo dipendente dalle impostazioni locali, contenente caratteri alfabetici, che può contenere, ma non cominciare, con i caratteri "'" and "-".

Elenco dei parametri

string

La stringa

format

Indica il tipo di valore restituito dalla funzione. Le attuali impostazioni ammesse per il parametro sono:

  • 0 - restituisce il numero di parole trovate

  • 1 - restituisce una matrice contenente tutte le parole trovate all'interno di string.

  • 2 - restituisce una matrice associativa, in cui le chiavi sono la posizione numerica della parola in string ed il valore è la parola stessa.

charlist

Lista di caratteri addizionali da considerare come 'parole'

Valori restituiti

Restituisce un intero od una matrice in base al valore di format.

Log delle modifiche

VersioneDescrizione
5.1.0 Aggiunto il parametro charlist

Esempi

Esempio 1. Esempio di uso di str_word_count()

<?php

$str = "Hello fri3nd, you're
       looking          good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo str_word_count($str);

?>

Il precedente esempio visualizzerà:

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

strcasecmp

(PHP 3 >= 3.0.2, PHP 4, PHP 5)

strcasecmp --  Confronto non sensibile alle maiuscole e sicuro con i dati binari

Descrizione

int strcasecmp ( string str1, string str2 )

Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.

Esempio 1. Esempio di uso di strcasecmp()

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

Vedere anche ereg(), strcmp(), substr(), stristr(), strncasecmp() e strstr().

strchr

(PHP 3, PHP 4, PHP 5)

strchr -- Alias di strstr()

Descrizione

This function is an alias of: strstr().

strcmp

(PHP 3, PHP 4, PHP 5)

strcmp -- Confronto tra stringhe affidabile con dati binari

Descrizione

int strcmp ( string str1, string str2 )

Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.

Attenzione: il confronto tiene conto delle lettere maiuscole e minuscole.

Vedere anche ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp() e strstr().

strcoll

(PHP 4 >= 4.0.5, PHP 5)

strcoll -- Confronto tra stringhe basato sulle impostazioni locali

Descrizione

int strcoll ( string str1, string str2 )

Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali. strcoll() utilizza le impostazioni locali per il confronto. Se le impostazioni locali sono conformi al C o a POSIX, allora la funzione è equivalente a strcmp().

Attenzione. questo confronto distingue tra maiuscole e minuscole, e, diversamente da strcmp() non è affidabile con i dati binari.

Nota: strcoll() è stato aggiunto in PHP 4.0.5, ma sui sistemi win32 non è stato abilitato fino alla versione 4.2.3.

Vedere anche ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr() e setlocale().

strcspn

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

strcspn --  Trova la lunghezza del segmento iniziale che non soddisfa una maschera

Descrizione

int strcspn ( string str1, string str2 [, int inizio [, int lunghezza]] )

Restituisce la lunghezza del segmento iniziale di str1 che non contiene nessuno dei caratteri specificati in str2.

Dal PHP 4.3.0, strcspn() accetta due parametri interi, opzionali, che possono essere utilizzati per definire la posizione di inizio e la lunghezza della stringa da esaminare.

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche strspn().

strip_tags

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

strip_tags -- Rimuove i tag HTML e PHP da una stringa

Descrizione

string strip_tags ( string str [, string allowable_tags] )

Questa funzione tenga di restituire una stringa priva dei tag HTML e PHP partendo dalla stringa str. La funzione utilizza la stessa macchina a stati di rimozione dei tag utilizzata per la funzione fgetss().

Si può utilizzare il secondo parametro, opzionale, per indicare quale tag ignorare.

Nota: allowable_tags è stato aggiunto in PHP 3.0.13 e PHP 4.0b3.

Dal PHP 4.3.0, sono rimossi anche i commenti HTML. Questo comportamento è da programma e non può essere modificato tramite allowable_tags.

Avvertimento

Poiché strip_tags() non valida il testo HTML, tag parziali, o interrotti possono portare alla rimozione di più testo di quanto atteso.

Avvertimento

Questa funzione non modifica alcun attributo sui tag che sono abilitati tramite allowable_tags, incluso lo style e l'attributo onmouseover che possono essere sfruttati da utenti malevoli quando pubblicano testi che saranno visualizzati da altri utenti.

Esempio 1. Esempio di uso di strip_tags()

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);

echo "\n";
// allow <p>
echo strip_tags($text, '<p>');
?>

Il precedente esempio visualizzerà:

Test paragraph. Other text
<p>Test paragraph.</p> Other text

La funzione strip_tags() è sicura con i contenuti binari dal PHP 5.0.0

Vedere anche htmlspecialchars().

stripcslashes

(PHP 4, PHP 5)

stripcslashes --  Rimuove gli slash aggiunti con addcslashes()

Descrizione

string stripcslashes ( string str )

Rimuove i backslash da una stringa. Riconosce i caratteri C \n, \r ..., le rappresentazioni ottali e esadecimali.

Vedere anche addcslashes().

stripos

(PHP 5)

stripos --  Trova la prima occorrenza in una stringa senza distinzione tra maiuscole e minuscole

Descrizione

int stripos ( string haystack, string needle [, int offset] )

Restituisce la posizione numerica della prima occorrenza di needle nella stringa haystack. Differentemente da strpos(), stripos() non distingue tra maiuscole e minuscole.

Occorre rilevare che needle può essere una stringa di uno o più caratteri.

Se needle non viene trovato, stripos() restituirà boolean 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.

Esempio 1. Esempi di uso di stripos()

<?php
$findme    = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// No, 'a' non è certamente in 'xyz'
if ($pos1 === false) {
    echo "The string '$findme' was not found in the string '$mystring1'";
}

// Notate l'uso di ===.  Semplicemente == non avrebbe funzionato come atteso
// perchè la posizione di  'a' è nel carattere 0 (il primo).
if ($pos2 !== false) {
    echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>

Se needle non è una stringa, sarà convertito in un intero e utilizzato come valore ordinale di un carattere.

Il parametro opzionale offset permette di indicare da quale carattere di haystack iniziare la ricerca. La posizione restituita sarà relativa all'inizio di haystack.

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche strpos(), strrpos(), strrchr(), substr(), stristr(), strstr(), strripos() e str_ireplace().

stripslashes

(PHP 3, PHP 4, PHP 5)

stripslashes --  Rimuove gli slash aggiunti con addslashes()

Descrizione

string stripslashes ( string str )

Rimuove i backslash da una stringa. (\' diventa ' e così via.) I doppi backslash (\\) sono ridotti ad un singolo backslash (\).

Un esempio di uso di stripslashes() è dato dall'opzione PHP magic_quotes_gpc che, quando è impostata a on (come è per default), e non siinseriscono questi dati in una procedura (tipo in un database) che richiede il carattere di escape. Ad esempio, se si visualizza dati da un form HTML.

Esempio 1. Esempio di uso di stripslashes()

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

Nota: La funzione stripslashes() non è ricorsiva Se si desidera utilizzare questa funzione su una matrice multi-dimensionale, occorre utilizzare una funzione ricorsiva.

Esempio 2. Esempio di utilizzo di stripslashes() su una matrice

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);
 
    return $value;
}
 
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
 
// Output
print_r($array);
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )
 
)

Per maggiori dettagli su "magic quotes", vedere get_magic_quotes_gpc().

Vedere anche addslashes() e get_magic_quotes_gpc().

stristr

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

stristr --  Versione insensibile alle maiuscole/minuscole di strstr()

Descrizione

string stristr ( string haystack, string needle )

Restituisce il contenuto di haystack dalla prima occorrenza di needle fino alla fine. needle e haystack sono esaminati senza distinguere tra lettere maiuscole e minuscole.

Se needle non viene trovato, la funzione restituisce FALSE.

Se needle non è una stringa, viene convertito in un intero e si utilizza il valore ordinale del carattere.

Esempio 1. Esempio di uso di stristr()

<?php
  $email = 'USER@EXAMPLE.com';
  echo stristr($email, 'e');
// outputs ER@EXAMPLE.com
?>

Esempio 2. Verifica se una stringa esiste o meno

<?php
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" not found in string';
  }
// outputs: "earth" not found in string
?>

Esempio 3. Utilizzo di un dato non stringa da cercare

<?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche strstr(), strrchr(), substr() e ereg().

strlen

(PHP 3, PHP 4, PHP 5)

strlen -- Restituisce la lunghezza di una stringa

Descrizione

int strlen ( string string )

Restituisce la lunghezza della stringa string.

Esempio 1. Esempio di uso di strlen()

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Vedere anche count() e mb_strlen().

strnatcasecmp

(PHP 4, PHP 5)

strnatcasecmp --  Versione insensibile alle maiuscole/minuscole di confronto tra stringhe tramite l'algoritmo dell"ordine naturale"

Descrizione

int strnatcasecmp ( string str1, string str2 )

Questa funzione implementa un algoritmo di confronto che ordina le stringhe alfa-numeriche nel modo in cui lo farebbe un uomo. Il comportamento di questa funzione è simile a strnatcmp(), tranne che il confronto non distingue tra le lettere maiuscole e minuscole. Per maggiori informazioni vedere: Martin Pool's Natural Order String Comparison page.

Al pari delle altre funzioni di confronto tra stringhe, questa restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.

Vedere anche ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcmp() e strstr().

strnatcmp

(PHP 4, PHP 5)

strnatcmp --  Confronto tra stringhe con l'algoritmo dell' "ordine naturale"

Descrizione

int strnatcmp ( string str1, string str2 )

Questa funzione implementa un algoritmo di confronto che ordina le stringhe alfa-numeriche nel modo con cui lo avrebbe fatto un uomo, questo è detto "ordinamento naturale". Un esempio della differenza tra questo algoritmo e quello solito dei computer (utilizzato da strcmp()) è illustrato di seguito:

<?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>

Il precedente codice visualizzerà:

Standard string comparison
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order string comparison
Array
(
    [0] => img1.png
    [1] => img2.png
    [2] => img10.png
    [3] => img12.png
)

Per maggiori informazioni vedere: Martin Pool's Natural Order String Comparison page.

Al pari delle altre funzioni di confronto tra stringhe, questa restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.

Nota questo confronto distingue tra lettere maiuscole e minuscole.

Vedere anche ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() e natcasesort().

strncasecmp

(PHP 4 >= 4.0.2, PHP 5)

strncasecmp --  Confronto sicuro con i testi binari, insensibile alle lettere maiuscole/minuscole sui primi n caratteri

Descrizione

int strncasecmp ( string str1, string str2, int len )

Questa funzione è simile a strcasecmp(), con la differenza che si può indicare il numero dei caratteri (len) per ciascuna stringa che possono essere utilizzati per il confronto.

Restituisce < 0 if str1 se è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.

Vedere anche ereg(), strcasecmp(), strcmp(), substr(), stristr() e strstr().

strncmp

(PHP 4, PHP 5)

strncmp --  Confronto tra stringhe sui primi n caratteri, sicuro con i dati binari

Descrizione

int strncmp ( string str1, string str2, int len )

Questa funzione è simile a strcmp(), con la differenza che si può specificare il limite superiore del numero di caratteri (len) per ciascuna stringa, da utilizzare per il confronto.

Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.

Nota: questo confronto distingue tra lettere minuscole e maiuscole.

Vedere anche ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp() e strstr().

strpbrk

(PHP 5)

strpbrk --  Ricerca in una stringa uno qualsiasi dei caratteri di un dato set

Descrizione

string strpbrk ( string haystack, string char_list )

strpbrk() cerca nella stringa haystack i caratteri indicati in char_list, e restituisce una stringa a partire dal carattere trovato (oppure FALSE se non ve ne sono).

Nota: char_list distingue tra maiuscole e minuscole.

Esempio 1. Esempio di uso di strpbrk()

<?php

$text = 'This is a Simple text.';

// visualizza "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// visualizza "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

strpos

(PHP 3, PHP 4, PHP 5)

strpos --  Trova la posizione della prima occorrenza di una stringa

Descrizione

int strpos ( string haystack, mixed needle [, int offset] )

Restituisce la posizione numerica della prima occorrenza di needle nella stringa haystack. Differentemente rispetto a strrpos(), questa funzione considera tutta la stringa needle, e, quindi, cercherà tutta la stringa.

Se needle non viene trovato strpos() restituirà boolean 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.

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Esempio 1. Esempio di uso di strpos()

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Notate l'uso di ===.  Il == non avrebbe risposto come atteso
// poichè la posizione di 'a' è nel primo carattere.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}

// Ricerca di un carattere ignorando qualsiasi cosa prima di offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

Se needle non è una stringa, viene convertito in un intero e utilizzato come valore ordinale di un carattere.

Il parametro opzionale offset permette di indicare da quale carattere in haystack iniziare la ricerca. La posizione restituita è, comunque, relativa all'inizio di haystack.

Vedere anche strrpos(), stripos(), strripos(), strrchr(), substr(), stristr() e strstr().

strrchr

(PHP 3, PHP 4, PHP 5)

strrchr --  Trova l'ultima occorrenza di un carattere in una stringa

Descrizione

string strrchr ( string haystack, string needle )

Questa funzione restituisce la porzione di haystack che inizia dall'ultima occorrenza di needle e finisce al termine di haystack.

Restituisce FALSE se needle non viene trovato.

Se needle contiene più di un carattere, in PHP 4 si utilizza solo il primo. Questo comportamento è differente rispetto a strchr().

Se needle non è una stringa, viene convertito in un intero e utilizzato come valore ordinale di un carattere.

Esempio 1. Esempio di uso di strrchr()

<?php
// L'ultima directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// ottiene qualsiasi cosa dopo l'ultimo newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

strrchr() è affidabile con i dati binari dal PHP 4.3.0

Vedere anche strstr(), substr() e stristr().

strrev

(PHP 3, PHP 4, PHP 5)

strrev -- Inverte una stringa

Descrizione

string strrev ( string string )

Restituisce la stringa string invertita.

Esempio 1. Invertire una stringa con strrev()

<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

strripos

(PHP 5)

strripos --  Trova la posizione dell'ultima occorrenza di una stringa in un'altra indipendentemente dalle lettere minuscole/maiusole

Descrizione

int strripos ( string haystack, string needle [, int offset] )

Restituisce la posizione numerica dell'ultima occorrenza di needle nella stringa haystack. Differentemente da strrpos(), strripos() non distingue tra lettere maiuscole minuscole. Attenzione che le posizioni della stringa partono da 0 e non da 1.

Notare anche che needle può essere una stringa di uno o più caratteri.

Se needle non è reperito, la funzione restituisce 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.

Esempio 1. Un semplice esempio di strripos()

<?php
$haystack = 'ababcd';
$needle   = 'aB';

$pos      = strripos($haystack, $needle);

if ($pos === false) {
    echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
    echo "Congratulations!\n";
    echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
?>

Output:

Congratulations!
   We found the last (aB) in (ababcd) at position (2)

Il parametro offset può indicare la posizione da cui cominciare la ricerca nella stringa.

Offset negativi inizieranno la ricerca alla posizione offset dall'inizio della stringa.

Vedere anche: strrpos(), strrchr(), substr(), stripos() e stristr().

strrpos

(PHP 3, PHP 4, PHP 5)

strrpos --  Trova la posizione dell'ultima occorrenza di un carattere in una stringa

Descrizione

int strrpos ( string haystack, string needle [, int offset] )

Restituisce la posizione numerica dell'ultima occorrenza di needle nella stringa haystack. Fare attenzione che needle, in PHP 4, può essere solo un singolo carattere. Se si passa una stringa, verrà utilizzato solo il primo carattere.

Se needle non viene trovato, la funzione restituisce FALSE.

Si può facilmente confondere i valori restituiti "per carattere alla posizione 0" e per "carattere non trovato". Ecco come rilevare la differenza:

<?php

// in PHP 4.0b3 e successivi:
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

// nelle versioni precedenti alla 4.0b3:
$pos = strrpos($mystring, "b");
if (is_bool($pos) && !$pos) {
    // not found...
}
?>

Se needle non è una stringa, viene convertito in un intero, e usato come valore ordinale di un carattere.

Nota: Dal PHP 5.0.0 offset può essere indicato per indicare di iniziare la ricerca nella stringa da una posizione di caratteri arbitraria. Valori negativi fermeranno la ricerca ad un punto arbitrario prima della fine della stringa.

Nota: Il parametro needle può essere una stringa di uno o più caratteri a partire dal PHP 5.0.0.

Vedere anche: strpos(), strripos(), strrchr(), substr(), stristr() e strstr().

strspn

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

strspn --  Trova la lunghezza di un testo che corrisponde alla maschera data

Descrizione

int strspn ( string str1, string str2 [, int start [, int length]] )

Restituisce la lunghezza di un segmento di str1 che contiene completamente i caratteri presenti in str2.

Il seguente codice:

<?php
$var = strspn("42 is the answer, what is the question ...", "1234567890");
?>

assegnerà 2 a $var, poichè la stringa "42" è il più lungo segmento contenente i caratteri da "1234567890".

Dal PHP 4.3.0, strspn() accetta altri due parametri interi opzionali: start che può essere usato per indicare la posizione di inizio da cui cercare, e length per indicare la lunghezza della stringa da esaminare.

<?php
echo strspn("foo", "o", 1, 2); // 2
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche strcspn().

strstr

(PHP 3, PHP 4, PHP 5)

strstr -- Trova la prima occorrenza di una stringa

Descrizione

string strstr ( string haystack, string needle )

Restituisce la parte della stringa haystack dalla prima occorrenza di needle fino alla fine di haystack.

Se non si trova needle, restituisce FALSE.

Se needle non è una stringa, il parametro viene convertito in un intero e utilizzato come valore ordinale di un carattere.

Nota: Questa funzione distingue tra maiuscole e minuscole. Per una versione che non abbia questa distinzione guardare stristr().

Esempio 1. Esempio di uso di strstr()

<?php
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>

Nota: Se si desidera soltanto determinare se una particolare stringa è presente in haystack, utilizzare la più veloce e meno costosa in termini di memoria strpos().

strstr() è sicura con i dati binari dal PHP 4.3.0

Vedere anche: ereg(), preg_match(), stristr(), strpos(), strrchr() e substr().

strtok

(PHP 3, PHP 4, PHP 5)

strtok -- Suddivide una stringa in token

Descrizione

string strtok ( string str, string token )

strtok() suddivide la stringa(str) in piccole stringhe (tokens), in cui ciascun token è delimitato dal carattere indicato in token. Perciò, se si ha la stringa "This is an example string" la si può dividere nelle singole parole utilizzando come separatore lo spazio.

Esempio 1. Esempio di uso di strtok()

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");
while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

Soltanto la prima chiamata a strtok() utilizza il parametro stringa. Ogni chiamata successiva richiede solo il carattere da utilizzare, poichè la funzione tiene traccia di dove è arrivata nella stringa corrente. Per ripartire da capo o iniziare con una nuova stringa ri-chiamare strtok() con il parametro stringa. Nota: si possono mettere più caratteri come separatori di stringhe. Il testo iniziale verrà suddiviso quando viene trovato uno qualsiasi di questi caratteri. Attenzione che soltanto la prima chiamata di strtok userà l'argomento stringa.

Il comportamento su segmenti vuoti è cambiato dal PHP 4.1.0. La vecchia versione restituiva una stringa vuota, mentre la nuova, più correttamente, salta quella parte di stringa:

Esempio 2. Vecchio comportamento di strtok()

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(0) ""
    string(9) "something"

Esempio 3. Nuovo comportamento di strtok()

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(9) "something"
    bool(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.

Vedere anche: split() e explode().

strtolower

(PHP 3, PHP 4, PHP 5)

strtolower -- Converte in minuscolo una stringa

Descrizione

string strtolower ( string str )

La funzione restituisce la stringa string con tutti i caratteri alfabetici convertiti in minuscolo.

Nota: i caratteri 'alfabetici' sono determinati in base alle impostazioni locali. Ciò significa, ad esempio, che nelle impostazioni locali di default del "C", il carattere umlaut-A (Ä) non sarà convertito.

Esempio 1. Esempio di uso di strtolower()

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche: strtoupper(), ucfirst(), ucwords() e mb_strtolower().

strtoupper

(PHP 3, PHP 4, PHP 5)

strtoupper -- Converte in maiuscolo una stringa

Descrizione

string strtoupper ( string string )

Restituisce la stringa string con i caratteri alfabetici convertiti in maiuscolo.

Nota: i caratteri 'alfabetici' sono determinati in base alle impostazioni locali. Ciò significa, ad esempio, che nelle impostazioni locali di default del "C", il carattere umlaut-A (Ä) non sarà convertito.

Esempio 1. Esempio di uso di strtoupper()

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche: strtolower(), ucfirst(), ucwords() e mb_strtoupper().

strtr

(PHP 3, PHP 4, PHP 5)

strtr -- Traduce certi caratteri

Descrizione

string strtr ( string str, string from, string to )

string strtr ( string str, array replace_pairs )

Questa funzione restituisce una copia di str, traducendo tutti i caratteri di from al corrispondente carattere indicato in to.

Se from e to hanno lunghezze differenti, i caratteri in più presenti nella stringa più lunga saranno ignorati.

Esempio 1. Esempio di uso di strtr()

<?php
$addr = strtr($addr, "äåö", "aao");
?>

strtr() può essere eseguita con solo due argomenti. Se viene chiamata con due parametri si comporta in modo nuovo: from deve essere un matrice che contiene le coppie stringa -> stringa da sostituire nella stringa sorgente. strtr() cercherà sempre prima di incrociare il testo più lungo e *NON* tenterà di sostituire parti su cui ha già lavorato.

Esempio 2. Esempio di uso di strtr() con due parametri

<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

Questo visualizzerà:

hello all, I said hi

Nota: I parametri opzionali to e from sono stati aggiunti in PHP 4.0.0

Vedere anche ereg_replace().

substr_compare

(PHP 5)

substr_compare --  Confronto tra due stringhe a partire da una data posizione per n caratteri, sicuro con i dati binari e, opzionalmente, senza distinguere tra lettere maiuscole e minuscole

Descrizione

int substr_compare ( string main_str, string str, int offset [, int length [, bool case_insensitivity]] )

La funzione substr_compare() confronta main_str dalla posizione offset con la stringa str per length caratteri di lunghezza.

Restituisce < 0 se main_str dalla posizione offset è minore di str, > 0 se è maggiore di str, e 0 se sono uguali. Se length è uguale o maggiore della lunghezza di main_str ed è impostato il parametro length, substr_compare() visualizza un warning e restituisce FALSE.

Se case_insensitivity è TRUE, il confronto non distingue tra lettere maiuscole e minuscole.

Esempio 1. Esempio di uso di substr_compare()

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

substr_count

(PHP 4, PHP 5)

substr_count -- Conta il numero di occorrenze di un segmento di stringa

Descrizione

int substr_count ( string haystack, string needle )

substr_count() restituisce il numero di volte in cui la stringa needle compare in haystack. Fare attenzione che needle distingue tra lettere maiuscole e minuscole.

Esempio 1. Esempio di uso di substr_count()

<?php
echo substr_count("This is a test", "is"); // prints out 2
?>

Vedere anche count_chars(), strpos(), substr() e strstr().

substr_replace

(PHP 4, PHP 5)

substr_replace -- Sostuisce una porzione di testo

Descrizione

string substr_replace ( string string, string replacement, int start [, int length] )

La funzione substr_replace() sostituisce una copia di string delimitata dai parametri start e (opzionalmente) length con il testo indicato in replacement. Viene restituito il testo risultante.

Se start è positivo, la sostituzione inizierà palla posizione start di string.

Se start è negativo, la sostituzione inizierà da start caratteri dalla fine di string.

Se è indicato il parametro length ed è positivo, indica il numero di caratteri del testo string che devono essere sostituiti. Se questo parametro è negativo, indica il numero di caratteri dalla fine di string a cui fermarsi nella sostituzione. Se non viene indicato, si utilizzerà il default strlen( string ); ad esempio si finirà la sostituzione alla fine di string.

Esempio 1. Esempio di uso di substr_replace()

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* Questi due esempi sostituiscono tutte le occorrenze di $var con 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Inserisce 'bob' a destra all'inizio di $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* Nei successivi due esempi si sostituisce 'MNRPQR' in $var con 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Cancella 'MNRPQR' da $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche str_replace() e substr().

substr

(PHP 3, PHP 4, PHP 5)

substr -- Restituisce parte di una stringa

Descrizione

string substr ( string string, int start [, int length] )

La funzione substr() restituisce la porzione di string indicata dai parametri start e length.

Se start non è negativo, la stringa restituita inizierà dalla posizione start di string, partendo da zero. Ad esempio, nella stringa 'abcdef', il carattere alla posizione 0 è 'a', il carattere alla posizione 2 è 'c', e così via.

Esempio 1. Esempi di base di substr()

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accedere al singolo carattere
//  tramite le parentesi graffe è un'altra possibilità
$string = 'abcdef';
echo $string{0};                 // a
echo $string{3};                 // d
echo $string{strlen($string)-1}; // f
?>

Se start è negativo, la stringa restituita inizierà dal carattere start dalla fine di string.

Esempio 2. Utilizzo di valori negativi di start

<?php
$rest = substr("abcdef", -1);    // restituisce "f"
$rest = substr("abcdef", -2);    // restituisce "ef"
$rest = substr("abcdef", -3, 1); // restituisce "d"
?>

Se length è indicato ed è positivo, la stringa restituita conterrà almeno length caratteri partendo da start (in base alla lunghezza di string). Se string è minore o uguale a start, la funzione restituisce FALSE

Se length è indicato ed è negativo, allora saranno omessi length caratteri dalla fine di string (dopo avere calcolato la posizione iniziale, nel caso in cui start sia negativo). Se start indica una posizione successiva a questo troncamento, la funzione restituirà una stringa vuota.

Esempio 3. Utilizzo di valori negativi per length

<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns ""
$rest = substr("abcdef", -3, -1); // returns "de"
?>

Vedere anche strrchr(), substr_replace(), ereg(), trim(), mb_substr() e wordwrap().

trim

(PHP 3, PHP 4, PHP 5)

trim -- Rimuove gli spazi (ed altri caratteri) all'inizio e alla fine di un testo

Descrizione

string trim ( string str [, string charlist] )

Questa funzione restituisce il parametro str privo degli spazi iniziali e finali. Senza la specifica del secondo parametro, trim() rimuoverà questi caratteri:

  • " " (ASCII 32 (0x20)), spazio.

  • "\t" (ASCII 9 (0x09)), il carattere tab.

  • "\n" (ASCII 10 (0x0A)), il new line (line feed).

  • "\r" (ASCII 13 (0x0D)), il carriage return.

  • "\0" (ASCII 0 (0x00)), il byte NUL.

  • "\x0B" (ASCII 11 (0x0B)), il tab verticale.

Elenco dei parametri

str

La stringa che deve essere troncata.

charlist

Opzionale, Si può, inoltre, specificare quali caratteri si desidera rimuovere elencandoli in charlist. Questo parametro è un semplice elenco dei caratteri da rimuovere. Con .. si può indicare un range di caratteri.

Valori restituiti

La stringa troncata.

Log delle modifiche

VersioneDescrizione
4.1.0 E' stato aggiunto il parametro opzionale charlist.

Esempi

Esempio 1. Esempio di uso di trim()

<?php

$text = "\t\tThese are a few words :) ...  ";

echo trim($text);           // "These are a few words :) ..."
echo trim($text, " \t.");   // "These are a few words :)"

// rimuove i caratteri di controllo ASCII all'inizio ed alla fine di $binary
// (da 0 a 31 compresi)
$clean = trim($binary, "\x00..\x1F");

?>

Esempio 2. Trimming array values with trim()

<?php
function trim_value(&$value) 
{ 
	$value = trim($value); 
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

Il precedente esempio visualizzerà:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana "
  [2]=>
  string(11) " cranberry "
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(9) "cranberry"
}

Vedere anche:

ltrim()
rtrim()

ucfirst

(PHP 3, PHP 4, PHP 5)

ucfirst -- Converte in maiuscolo il primo carattere del testo

Descrizione

string ucfirst ( string str )

Restituisce un testo in cui il primo carattere di str è maiuscolo, se si tratta di una carattere alfabetico.

Attenzione che i 'caratteri alfabetici' sono determinati dalle impostazioni locali. Ad esempio nelle impostazioni locali "C" di default, caratteri tipo ä non saranno convertiti.

Esempio 1. Esempio di uso di ucfirst()

<?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

Vedere anche strtolower(), strtoupper() e ucwords().

ucwords

(PHP 3 >= 3.0.3, PHP 4, PHP 5)

ucwords --  Converte in maiuscolo il primo carattere di ogni parola di una stringa

Descrizione

string ucwords ( string str )

Restituisce un testo in cui la lettera iniziale di ogni parola è convertita in maiuscolo, se il carattere è alfabetico.

Definizione di parola: sequenza di caratteri immediatamente seguita da un carattere di delimitazione (i delimitatori sono: spazio, form-feed, newline, carriage return, tab orizzontale e tab verticale).

Esempio 1. Esempio di uso di ucwords()

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World! 

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

Vedere anche strtoupper(), strtolower() e ucfirst().

vfprintf

(PHP 5)

vfprintf -- Scrive una stringa formatta in un flusso

Descrizione

int vfprintf ( resource handle, string format, array args )

Scrive la stringa prodotta in base a format sul flusso indicato da handle. format è descritto nella documentazione di sprintf().

La funzione agisce come fprintf() ma accetta una matrice di argomenti, piuttosto che un numero variabile di argomenti.

Restituisce la lunghezza della stringa prodotta.

Vedere anche printf(), sprintf(), sscanf(), fscanf(), vsprintf() e number_format().

Esempio

Esempio 1. vfprintf(): interi completati con zero

<?php
if (!($fp = fopen('date.txt', 'w')))
    return;

vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// will write the formatted ISO date to date.txt
?>

vprintf

(PHP 4 >= 4.1.0, PHP 5)

vprintf -- Visualizza una stringa formattata

Descrizione

int vprintf ( string format, array args )

Visualizza i valori di una matrice come stringa formattata in base a format (che è descritto nella documentazione di sprintf()).

Agisce come printf() ma accetta una matrice di argomenti, piuttosto che un numero variabile di argomenti.

Restituisce la lunghezza della stringa prodotta.

Vedere anche printf(), sprintf(), e vsprintf()

vsprintf

(PHP 4 >= 4.1.0, PHP 5)

vsprintf -- Restituisce una stringa formattata

Descrizione

string vsprintf ( string format, array args )

Restituisce i valori di una matrice come testo formattato in base a format (descritto nella documentazione di sprintf()).

Agisce come sprintf() ma accetta una matrice di argomenti, piuttosto che un numero variabile di argomenti.

Vedere anche sprintf() e vprintf()

wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap --  Divide una stringa ad un certo numero di caratteri utilizzando il carattere di divisione

Descrizione

string wordwrap ( string str [, int width [, string break [, bool cut]]] )

Restituisce una stringa con str suddivisa alla colonna indicata dal parametro opzionale width. La linea è interrotta utilizzando il parametro opzionale break.

wordwrap() interrompe automaticamente la stringa alla colonna 75 ed utilizza come carattere di interruzione '\n' (newline), se non sono dati width e break

Se il parametro cut è impostato a 1, la stringa è sempre interrotta alla lunghezza indicata. Pertanto se una parola supera la larghezza data, questa verrà interrotta. (Vedere il secondo esempio).

Nota: Il parametro opzionale cut è stato aggiunto in PHP 4.0.3

Esempio 1. Esempio di uso di wordwrap()

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

Questo esempio visualizza:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Esempio 2. Esempio di uso di wordwrap()

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", 1);

echo "$newtext\n";
?>

Questo esempio visualizza:

A very
long
wooooooo
ooooord.

Vedere anche nl2br() e chunk_split().

CXLVI. Shockwave Flash Functions

Introduzione

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Nota: SWF support was added in PHP 4 RC2.

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.


Requisiti

You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.


Installazione

Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

MOD_COLOR (integer)

MOD_MATRIX (integer)

TYPE_PUSHBUTTON (integer)

TYPE_MENUBUTTON (integer)

BSHitTest (float)

BSDown (float)

BSOver (float)

BSUp (float)

OverDowntoIdle (integer)

IdletoOverDown (integer)

OutDowntoIdle (integer)

OutDowntoOverDown (integer)

OverDowntoOutDown (integer)

OverUptoOverDown (integer)

OverUptoIdle (integer)

IdletoOverUp (integer)

ButtonEnter (integer)

ButtonExit (integer)

MenuEnter (integer)

MenuExit (integer)


Esempi

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Esempio 1. SWF example

<?php
swf_openfile("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2(-100, 100, -100, 100);
swf_defineline(1, -70, 0, 70, 0, .2);
swf_definerect(4, 60, -10, 70, 0, 0);
swf_definerect(5, -60, 0, -70, 10, 0);
swf_addcolor(0, 0, 0, 0);

swf_definefont(10, "Mod");
swf_fontsize(5);
swf_fontslant(10);
swf_definetext(11, "This be Flash wit PHP!", 1);

swf_pushmatrix();
swf_translate(-50, 80, 0);
swf_placeobject(11, 60);
swf_popmatrix();

for ($i = 0; $i < 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix();
    swf_scale(1-($p*.9), 1, 1);
    swf_rotate(60*$p, 'z');
    swf_translate(20+20*$p, $p/1.5, 0);
    swf_rotate(270*$p,  'z');
    swf_addcolor($p, 0, $p/1.2, -$p);
    swf_placeobject(1, 50);
    swf_placeobject(4, 50);
    swf_placeobject(5, 50);
    swf_popmatrix();
    swf_showframe();
}

for ($i = 0; $i < 30; $i++) {
    swf_removeobject(50);
    if (($i%4) == 0) {
        swf_showframe();
    }
}

swf_startdoaction();
swf_actionstop();
swf_enddoaction();

swf_closefile();
?>

Sommario
swf_actiongeturl -- Get a URL from a Shockwave Flash movie
swf_actiongotoframe -- Play a frame and then stop
swf_actiongotolabel --  Display a frame with the specified label
swf_actionnextframe -- Go forward one frame
swf_actionplay --  Start playing the flash movie from the current frame
swf_actionprevframe -- Go backwards one frame
swf_actionsettarget -- Set the context for actions
swf_actionstop --  Stop playing the flash movie at the current frame
swf_actiontogglequality --  Toggle between low and high quality
swf_actionwaitforframe --  Skip actions if a frame has not been loaded
swf_addbuttonrecord --  Controls location, appearance and active area of the current button
swf_addcolor --  Set the global add color to the rgba value specified
swf_closefile -- Close the current Shockwave Flash file
swf_definebitmap -- Define a bitmap
swf_definefont --  Defines a font
swf_defineline -- Define a line
swf_definepoly --  Define a polygon
swf_definerect -- Define a rectangle
swf_definetext -- Define a text string
swf_endbutton --  End the definition of the current button
swf_enddoaction -- End the current action
swf_endshape --  Completes the definition of the current shape
swf_endsymbol -- End the definition of a symbol
swf_fontsize -- Change the font size
swf_fontslant -- Set the font slant
swf_fonttracking -- Set the current font tracking
swf_getbitmapinfo -- Get information about a bitmap
swf_getfontinfo --  The height in pixels of a capital A and a lowercase x
swf_getframe -- Get the frame number of the current frame
swf_labelframe -- Label the current frame
swf_lookat -- Define a viewing transformation
swf_modifyobject -- Modify an object
swf_mulcolor --  Sets the global multiply color to the rgba value specified
swf_nextid -- Returns the next free object id
swf_oncondition --  Describe a transition used to trigger an action list
swf_openfile -- Open a new Shockwave Flash file
swf_ortho2 --  Defines 2D orthographic mapping of user coordinates onto the current viewport
swf_ortho --  Defines an orthographic mapping of user coordinates onto the current viewport
swf_perspective --  Define a perspective projection transformation
swf_placeobject -- Place an object onto the screen
swf_polarview --  Define the viewer's position with polar coordinates
swf_popmatrix --  Restore a previous transformation matrix
swf_posround --  Enables or Disables the rounding of the translation when objects are placed or moved
swf_pushmatrix --  Push the current transformation matrix back unto the stack
swf_removeobject -- Remove an object
swf_rotate -- Rotate the current transformation
swf_scale -- Scale the current transformation
swf_setfont -- Change the current font
swf_setframe -- Switch to a specified frame
swf_shapearc -- Draw a circular arc
swf_shapecurveto3 -- Draw a cubic bezier curve
swf_shapecurveto --  Draw a quadratic bezier curve between two points
swf_shapefillbitmapclip --  Set current fill mode to clipped bitmap
swf_shapefillbitmaptile --  Set current fill mode to tiled bitmap
swf_shapefilloff -- Turns off filling
swf_shapefillsolid --  Set the current fill style to the specified color
swf_shapelinesolid -- Set the current line style
swf_shapelineto -- Draw a line
swf_shapemoveto -- Move the current position
swf_showframe -- Display the current frame
swf_startbutton -- Start the definition of a button
swf_startdoaction --  Start a description of an action list for the current frame
swf_startshape -- Start a complex shape
swf_startsymbol -- Define a symbol
swf_textwidth -- Get the width of a string
swf_translate -- Translate the current transformations
swf_viewport -- Select an area for future drawing

swf_actiongeturl

(PHP 4, PECL)

swf_actiongeturl -- Get a URL from a Shockwave Flash movie

Description

void swf_actiongeturl ( string url, string target )

The swf_actiongeturl() function gets the URL specified by the parameter url with the target target.

swf_actiongotoframe

(PHP 4, PECL)

swf_actiongotoframe -- Play a frame and then stop

Description

void swf_actiongotoframe ( int framenumber )

The swf_actiongotoframe() function will go to the frame specified by framenumber, play it, and then stop.

swf_actiongotolabel

(PHP 4, PECL)

swf_actiongotolabel --  Display a frame with the specified label

Description

void swf_actiongotolabel ( string label )

The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.

swf_actionnextframe

(PHP 4, PECL)

swf_actionnextframe -- Go forward one frame

Description

void swf_actionnextframe ( void )

Go forward one frame.

swf_actionplay

(PHP 4, PECL)

swf_actionplay --  Start playing the flash movie from the current frame

Description

void swf_actionplay ( void )

Start playing the flash movie from the current frame.

swf_actionprevframe

(PHP 4, PECL)

swf_actionprevframe -- Go backwards one frame

Description

void swf_actionprevframe ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

swf_actionsettarget

(PHP 4, PECL)

swf_actionsettarget -- Set the context for actions

Description

void swf_actionsettarget ( string target )

The swf_actionsettarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.

swf_actionstop

(PHP 4, PECL)

swf_actionstop --  Stop playing the flash movie at the current frame

Description

void swf_actionstop ( void )

Stop playing the flash movie at the current frame.

swf_actiontogglequality

(PHP 4, PECL)

swf_actiontogglequality --  Toggle between low and high quality

Description

void swf_actiontogglequality ( void )

Toggle the flash movie between high and low quality.

swf_actionwaitforframe

(PHP 4, PECL)

swf_actionwaitforframe --  Skip actions if a frame has not been loaded

Description

void swf_actionwaitforframe ( int framenumber, int skipcount )

The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

swf_addbuttonrecord

(PHP 4, PECL)

swf_addbuttonrecord --  Controls location, appearance and active area of the current button

Description

void swf_addbuttonrecord ( int states, int shapeid, int depth )

The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.

Esempio 1. swf_addbuttonrecord() example

<?php
swf_startButton($objid, TYPE_MENUBUTTON);
swf_addButtonRecord(BSDown|BSOver, $buttonImageId, 340);
swf_onCondition(MenuEnter);
swf_actionGetUrl("http://www.example.com", "_level1");
swf_onCondition(MenuExit);
swf_actionGetUrl("", "_level1");
swf_endButton();
?>

swf_addcolor

(PHP 4, PECL)

swf_addcolor --  Set the global add color to the rgba value specified

Description

void swf_addcolor ( float r, float g, float b, float a )

The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.

Nota: The rgba values can be either positive or negative.

swf_closefile

(PHP 4, PECL)

swf_closefile -- Close the current Shockwave Flash file

Description

void swf_closefile ( [int return_file] )

Close a file that was opened by the swf_openfile() function. If the return_file parameter is set then the contents of the SWF file are returned from the function.

Esempio 1. Creating a simple flash file based on user input and outputting it and saving it in a database

<?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont(10, "Ligon-Bold");
        swf_fontsize(12);
        swf_fontslant(10);
    
    swf_definetext(11, $text, 1);
    
    swf_pushmatrix();
        swf_translate(-50, 80, 0);
        swf_placeobject(11, 60);
    swf_popmatrix();

    swf_showframe();
  
    swf_startdoaction();
        swf_actionstop();
    swf_enddoaction();

$data = swf_closefile(1);

$data ?
  swf_savedata($data) :
  die("Error could not save SWF file");

// void swf_savedata(string data)
// Save the generated file a database
// for later retrieval
function swf_savedata($data) 
{
    global $DBHOST, 
           $DBUSER,
           $DBPASS;
    
    $dbh = @mysql_connect($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query($stmt, $dbh);

    if (!$sth) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    @mysql_free_result($sth);
    @mysql_close($dbh);
}
?>

swf_definebitmap

(PHP 4, PECL)

swf_definebitmap -- Define a bitmap

Description

void swf_definebitmap ( int objid, string image_name )

The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

swf_definefont

(PHP 4, PECL)

swf_definefont --  Defines a font

Description

void swf_definefont ( int fontid, string fontname )

The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.

swf_defineline

(PHP 4, PECL)

swf_defineline -- Define a line

Description

void swf_defineline ( int objid, float x1, float y1, float x2, float y2, float width )

The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.

swf_definepoly

(PHP 4, PECL)

swf_definepoly --  Define a polygon

Description

void swf_definepoly ( int objid, array coords, int npoints, float width )

The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.

swf_definerect

(PHP 4, PECL)

swf_definerect -- Define a rectangle

Description

void swf_definerect ( int objid, float x1, float y1, float x2, float y2, float width )

The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.

swf_definetext

(PHP 4, PECL)

swf_definetext -- Define a text string

Description

void swf_definetext ( int objid, string str, int docenter )

Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

swf_endbutton

(PHP 4, PECL)

swf_endbutton --  End the definition of the current button

Description

void swf_endbutton ( void )

The swf_endbutton() function ends the definition of the current button.

swf_enddoaction

(PHP 4, PECL)

swf_enddoaction -- End the current action

Description

void swf_enddoaction ( void )

Ends the current action started by the swf_startdoaction() function.

swf_endshape

(PHP 4, PECL)

swf_endshape --  Completes the definition of the current shape

Description

void swf_endshape ( void )

The swf_endshape() completes the definition of the current shape.

swf_endsymbol

(PHP 4, PECL)

swf_endsymbol -- End the definition of a symbol

Description

void swf_endsymbol ( void )

The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.

swf_fontsize

(PHP 4, PECL)

swf_fontsize -- Change the font size

Description

void swf_fontsize ( float size )

The swf_fontsize() function changes the font size to the value given by the size parameter.

swf_fontslant

(PHP 4, PECL)

swf_fontslant -- Set the font slant

Description

void swf_fontslant ( float slant )

Set the current font slant to the angle indicated by the slant parameter. Positive values create a forward slant, negative values create a negative slant.

swf_fonttracking

(PHP 4, PECL)

swf_fonttracking -- Set the current font tracking

Description

void swf_fonttracking ( float tracking )

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

swf_getbitmapinfo

(PHP 4, PECL)

swf_getbitmapinfo -- Get information about a bitmap

Description

array swf_getbitmapinfo ( int bitmapid )

The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:

  • "size" - The size in bytes of the bitmap.

  • "width" - The width in pixels of the bitmap.

  • "height" - The height in pixels of the bitmap.

swf_getfontinfo

(PHP 4, PECL)

swf_getfontinfo --  The height in pixels of a capital A and a lowercase x

Description

array swf_getfontinfo ( void )

The swf_getfontinfo() function returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.

  • xheight - The height in pixels of a lowercase x.

swf_getframe

(PHP 4, PECL)

swf_getframe -- Get the frame number of the current frame

Description

int swf_getframe ( void )

The swf_getframe() function gets the number of the current frame.

swf_labelframe

(PHP 4, PECL)

swf_labelframe -- Label the current frame

Description

void swf_labelframe ( string name )

Label the current frame with the name given by the name parameter.

swf_lookat

(PHP 4, PECL)

swf_lookat -- Define a viewing transformation

Description

void swf_lookat ( float view_x, float view_y, float view_z, float reference_x, float reference_y, float reference_z, float twist )

The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.

swf_modifyobject

(PHP 4, PECL)

swf_modifyobject -- Modify an object

Description

void swf_modifyobject ( int depth, int how )

Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

swf_mulcolor

(PHP 4, PECL)

swf_mulcolor --  Sets the global multiply color to the rgba value specified

Description

void swf_mulcolor ( float r, float g, float b, float a )

The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.

Nota: The rgba values can be either positive or negative.

swf_nextid

(PHP 4, PECL)

swf_nextid -- Returns the next free object id

Description

int swf_nextid ( void )

The swf_nextid() function returns the next available object id.

swf_oncondition

(PHP 4, PECL)

swf_oncondition --  Describe a transition used to trigger an action list

Description

void swf_oncondition ( int transition )

The swf_oncondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • IdletoOverDown

  • OutDowntoIdle

  • MenuEnter (IdletoOverUp|IdletoOverDown)

  • MenuExit (OverUptoIdle|OverDowntoIdle)

For TYPE_PUSHBUTTON there are the following options:

  • IdletoOverUp

  • OverUptoIdle

  • OverUptoOverDown

  • OverDowntoOverUp

  • OverDowntoOutDown

  • OutDowntoOverDown

  • OutDowntoIdle

  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)

  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

swf_openfile

(PHP 4, PECL)

swf_openfile -- Open a new Shockwave Flash file

Description

void swf_openfile ( string filename, float width, float height, float framerate, float r, float g, float b )

The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.

The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).

swf_ortho2

(PHP 4, PECL)

swf_ortho2 --  Defines 2D orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho2 ( float xmin, float xmax, float ymin, float ymax )

The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective() function can be used.

swf_ortho

(PHP 4 >= 4.0.1, PECL)

swf_ortho --  Defines an orthographic mapping of user coordinates onto the current viewport

Description

void swf_ortho ( float xmin, float xmax, float ymin, float ymax, float zmin, float zmax )

The swf_ortho() function defines an orthographic mapping of user coordinates onto the current viewport.

swf_perspective

(PHP 4, PECL)

swf_perspective --  Define a perspective projection transformation

Description

void swf_perspective ( float fovy, float aspect, float near, float far )

The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.

Nota: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

swf_placeobject

(PHP 4, PECL)

swf_placeobject -- Place an object onto the screen

Description

void swf_placeobject ( int objid, int depth )

Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

Nota: Full RGBA colors are supported.

swf_polarview

(PHP 4, PECL)

swf_polarview --  Define the viewer's position with polar coordinates

Description

void swf_polarview ( float dist, float azimuth, float incidence, float twist )

The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

swf_popmatrix

(PHP 4, PECL)

swf_popmatrix --  Restore a previous transformation matrix

Description

void swf_popmatrix ( void )

The swf_popmatrix() function pushes the current transformation matrix back onto the stack.

swf_posround

(PHP 4, PECL)

swf_posround --  Enables or Disables the rounding of the translation when objects are placed or moved

Description

void swf_posround ( int round )

The swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

swf_pushmatrix

(PHP 4, PECL)

swf_pushmatrix --  Push the current transformation matrix back unto the stack

Description

void swf_pushmatrix ( void )

The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.

swf_removeobject

(PHP 4, PECL)

swf_removeobject -- Remove an object

Description

void swf_removeobject ( int depth )

Removes the object at the depth specified by depth.

swf_rotate

(PHP 4, PECL)

swf_rotate -- Rotate the current transformation

Description

void swf_rotate ( float angle, string axis )

The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).

swf_scale

(PHP 4, PECL)

swf_scale -- Scale the current transformation

Description

void swf_scale ( float x, float y, float z )

The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.

swf_setfont

(PHP 4, PECL)

swf_setfont -- Change the current font

Description

void swf_setfont ( int fontid )

The swf_setfont() sets the current font to the value given by the fontid parameter.

swf_setframe

(PHP 4, PECL)

swf_setframe -- Switch to a specified frame

Description

void swf_setframe ( int framenumber )

The swf_setframe() changes the active frame to the frame specified by framenumber.

swf_shapearc

(PHP 4, PECL)

swf_shapearc -- Draw a circular arc

Description

void swf_shapearc ( float x, float y, float r, float ang1, float ang2 )

The swf_shapearc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.

swf_shapecurveto3

(PHP 4, PECL)

swf_shapecurveto3 -- Draw a cubic bezier curve

Description

void swf_shapecurveto3 ( float x1, float y1, float x2, float y2, float x3, float y3 )

Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.

swf_shapecurveto

(PHP 4, PECL)

swf_shapecurveto --  Draw a quadratic bezier curve between two points

Description

void swf_shapecurveto ( float x1, float y1, float x2, float y2 )

The swf_shapecurveto() function draws a quadratic bezier curve from the current location, though the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters

swf_shapefillbitmapclip

(PHP 4, PECL)

swf_shapefillbitmapclip --  Set current fill mode to clipped bitmap

Description

void swf_shapefillbitmapclip ( int bitmapid )

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter.

swf_shapefillbitmaptile

(PHP 4, PECL)

swf_shapefillbitmaptile --  Set current fill mode to tiled bitmap

Description

void swf_shapefillbitmaptile ( int bitmapid )

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).

swf_shapefilloff

(PHP 4, PECL)

swf_shapefilloff -- Turns off filling

Description

void swf_shapefilloff ( void )

The swf_shapefilloff() function turns off filling for the current shape.

swf_shapefillsolid

(PHP 4, PECL)

swf_shapefillsolid --  Set the current fill style to the specified color

Description

void swf_shapefillsolid ( float r, float g, float b, float a )

The swf_shapefillsolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.

swf_shapelinesolid

(PHP 4, PECL)

swf_shapelinesolid -- Set the current line style

Description

void swf_shapelinesolid ( float r, float g, float b, float a, float width )

The swf_shapelinesolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.

swf_shapelineto

(PHP 4, PECL)

swf_shapelineto -- Draw a line

Description

void swf_shapelineto ( float x, float y )

The swf_shapelineto() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.

swf_shapemoveto

(PHP 4, PECL)

swf_shapemoveto -- Move the current position

Description

void swf_shapemoveto ( float x, float y )

The swf_shapemoveto() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.

swf_showframe

(PHP 4, PECL)

swf_showframe -- Display the current frame

Description

void swf_showframe ( void )

The swf_showframe function will output the current frame.

swf_startbutton

(PHP 4, PECL)

swf_startbutton -- Start the definition of a button

Description

void swf_startbutton ( int objid, int type )

The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

swf_startdoaction

(PHP 4, PECL)

swf_startdoaction --  Start a description of an action list for the current frame

Description

void swf_startdoaction ( void )

The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

swf_startshape

(PHP 4, PECL)

swf_startshape -- Start a complex shape

Description

void swf_startshape ( int objid )

The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.

swf_startsymbol

(PHP 4, PECL)

swf_startsymbol -- Define a symbol

Description

void swf_startsymbol ( int objid )

Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.

swf_textwidth

(PHP 4, PECL)

swf_textwidth -- Get the width of a string

Description

float swf_textwidth ( string str )

The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.

swf_translate

(PHP 4, PECL)

swf_translate -- Translate the current transformations

Description

void swf_translate ( float x, float y, float z )

The swf_translate() function translates the current transformation by the x, y, and z values given.

swf_viewport

(PHP 4, PECL)

swf_viewport -- Select an area for future drawing

Description

void swf_viewport ( float xmin, float xmax, float ymin, float ymax )

The swf_viewport() function selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.

CXLVII. Sybase Functions


Installazione

To enable Sybase-DB support configure PHP --with-sybase[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR]. DIR is the Sybase home directory, defaults to /home/sybase.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Sybase configuration options

NameDefaultChangeableChangelog
sybase.allow_persistent"1"PHP_INI_ALLAvailable since PHP 4.0.3.
sybase.max_persistent"-1"PHP_INI_ALLAvailable since PHP 4.0.3.
sybase.max_links"-1"PHP_INI_ALLAvailable since PHP 4.0.3.
sybase.interface_file "/usr/sybase/interfaces"PHP_INI_SYSTEM 
sybase.min_error_severity"10"PHP_INI_ALL 
sybase.min_message_severity"10"PHP_INI_ALL 
sybase.compatability_mode"0"PHP_INI_ALL 
magic_quotes_sybase"0"PHP_INI_ALL 

Breve descrizione dei parametri di configurazione.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

sybase.compatability_mode boolean

Compatibility mode with old versions of PHP 3.0. If on, this will cause PHP to automatically assign types to results according to their Sybase type, instead of treating them all as strings. This compatibility mode will probably not stay around forever, so try applying whatever necessary changes to your code, and turn it off.

magic_quotes_sybase boolean

If magic_quotes_sybase is on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime are enabled.

Nota: Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL's will be escaped.

Tabella 2. Sybase-CT configuration options

NameDefaultChangeableChangelog
sybct.allow_persistent"1"PHP_INI_SYSTEMAvailable since PHP 4.0.4.
sybct.max_persistent"-1"PHP_INI_SYSTEMAvailable since PHP 4.0.4.
sybct.max_links"-1"PHP_INI_SYSTEMAvailable since PHP 4.0.4.
sybct.min_server_severity"10"PHP_INI_ALLAvailable since PHP 4.0.4.
sybct.min_client_severity"10"PHP_INI_ALLAvailable since PHP 4.0.4.
sybct.hostnameNULLPHP_INI_ALLAvailable since PHP 4.0.4.
sybct.deadlock_retry_count"0"PHP_INI_ALLAvailable since PHP 4.3.0.

Breve descrizione dei parametri di configurazione.

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.login_timeout integer

The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.

sybct.timeout integer

The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when an operation times out, your script will be terminated before it can take action on failure. The default is no limit.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.

sybct.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is -1, or "forever".

Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
sybase_affected_rows -- Gets number of affected rows in last query
sybase_close -- Closes a Sybase connection
sybase_connect -- Opens a Sybase server connection
sybase_data_seek -- Moves internal row pointer
sybase_deadlock_retry_count -- Sets the deadlock retry count
sybase_fetch_array -- Fetch row as array
sybase_fetch_assoc -- Fetch a result row as an associative array
sybase_fetch_field -- Get field information from a result
sybase_fetch_object -- Fetch a row as an object
sybase_fetch_row -- Get a result row as an enumerated array
sybase_field_seek -- Sets field offset
sybase_free_result -- Frees result memory
sybase_get_last_message -- Returns the last message from the server
sybase_min_client_severity -- Sets minimum client severity
sybase_min_error_severity -- Sets minimum error severity
sybase_min_message_severity -- Sets minimum message severity
sybase_min_server_severity -- Sets minimum server severity
sybase_num_fields -- Gets the number of fields in a result set
sybase_num_rows -- Get number of rows in a result set
sybase_pconnect -- Open persistent Sybase connection
sybase_query -- Sends a Sybase query
sybase_result -- Get result data
sybase_select_db -- Selects a Sybase database
sybase_set_message_handler -- Sets the handler called when a server message is raised
sybase_unbuffered_query -- Send a Sybase query and do not block

sybase_affected_rows

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

sybase_affected_rows -- Gets number of affected rows in last query

Description

int sybase_affected_rows ( [resource link_identifier] )

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Esempio 1. Delete-Query

<?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?>

Il precedente esempio visualizzerà:

Records deleted: 10

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

See also sybase_num_rows().

sybase_close

(PHP 3, PHP 4, PHP 5)

sybase_close -- Closes a Sybase connection

Description

bool sybase_close ( [resource link_identifier] )

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier. If the link identifier isn't specified, the last opened link is assumed.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

See also sybase_connect() and sybase_pconnect().

sybase_connect

(PHP 3, PHP 4, PHP 5)

sybase_connect -- Opens a Sybase server connection

Description

resource sybase_connect ( [string servername [, string username [, string password [, string charset [, string appname]]]]] )

Returns a positive Sybase link identifier on success, or FALSE on failure.

sybase_connect() establishes a connection to a Sybase server. The servername argument has to be a valid servername that is defined in the 'interfaces' file.

In case a second call is made to sybase_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 sybase_close().

Esempio 1. sybase_connect() example

<?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>

See also sybase_pconnect() and sybase_close().

sybase_data_seek

(PHP 3, PHP 4, PHP 5)

sybase_data_seek -- Moves internal row pointer

Description

bool sybase_data_seek ( resource result_identifier, int row_number )

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.

See also sybase_fetch_row().

sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_count -- Sets the deadlock retry count

Description

void sybase_deadlock_retry_count ( int retry_count )

Using sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

Tabella 1. Values for retry_count

-1Retry forever (default)
0Do not retry
nRetry n times

sybase_fetch_array

(PHP 3, PHP 4, PHP 5)

sybase_fetch_array -- Fetch row as array

Description

array sybase_fetch_array ( resource result )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Nota: When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.

Esempio 1. Identical fieldnames

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?>

The above example would produce the following output (assuming the two tables only have each one column called "person_id"):

array(4) {
  [0]=>
  int(1)
  ["person_id"]=>
  int(1)
  [1]=>
  int(1)
  ["person_id1"]=>
  int(1)
}

See also sybase_fetch_row(), sybase_fetch_assoc() and sybase_fetch_object().

sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assoc -- Fetch a result row as an associative array

Description

array sybase_fetch_assoc ( resource result )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.

An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

See also sybase_fetch_array(), sybase_fetch_object() and sybase_fetch_row().

sybase_fetch_field

(PHP 3, PHP 4, PHP 5)

sybase_fetch_field -- Get field information from a result

Description

object sybase_fetch_field ( resource result [, int field_offset] )

Returns an object containing field information.

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.

  • column_source - the table from which the column was taken

  • max_length - maximum length of the column

  • numeric - 1 if the column is numeric

  • type - datatype of the column

See also sybase_field_seek().

sybase_fetch_object

(PHP 3, PHP 4, PHP 5)

sybase_fetch_object -- Fetch a row as an object

Description

object sybase_fetch_object ( resource result [, mixed object] )

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Use the second object to specify the type of object you want to return. If this parameter is omitted, the object will be of type stdClass.

Nota: As of PHP 4.3.0, this function will no longer return numeric object members.

Old behaviour:
object(stdclass)(3) {
  [0]=>
  string(3) "foo"
  ["foo"]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}

Esempio 1. sybase_fetch_object() return as Foo

<?php
    class Foo {
        var $foo, $bar, $baz;
    }
    
    // {...]
    $qrh= sybase_query('SELECT foo, bar, baz FROM example');
    $foo= sybase_fetch_object($qrh, 'Foo');
    $bar= sybase_fetch_object($qrh, new Foo());
    // {...]
?>

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

See also sybase_fetch_array() and sybase_fetch_row().

sybase_fetch_row

(PHP 3, PHP 4, PHP 5)

sybase_fetch_row -- Get a result row as an enumerated array

Description

array sybase_fetch_row ( resource result )

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Tabella 1. Data types

PHPSybase
stringVARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
intNUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
floatNUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULLNULL

See also sybase_fetch_array(), sybase_fetch_assoc(), sybase_fetch_object(), sybase_data_seek() and sybase_result().

sybase_field_seek

(PHP 3, PHP 4, PHP 5)

sybase_field_seek -- Sets field offset

Description

bool sybase_field_seek ( resource result, int field_offset )

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also sybase_fetch_field().

sybase_free_result

(PHP 3, PHP 4, PHP 5)

sybase_free_result -- Frees result memory

Description

bool sybase_free_result ( resource result )

sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

sybase_get_last_message

(PHP 3, PHP 4, PHP 5)

sybase_get_last_message -- Returns the last message from the server

Description

string sybase_get_last_message ( void )

sybase_get_last_message() returns the last message reported by the server.

See also sybase_min_message_severity().

sybase_min_client_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_client_severity -- Sets minimum client severity

Description

void sybase_min_client_severity ( int severity )

sybase_min_client_severity() sets the minimum client severity level.

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

See also sybase_min_server_severity().

sybase_min_error_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_error_severity -- Sets minimum error severity

Description

void sybase_min_error_severity ( int severity )

sybase_min_error_severity() sets the minimum error severity level.

Nota: This function is only available using the DB library interface to Sybase, and not the CT library.

See also sybase_min_message_severity().

sybase_min_message_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_message_severity -- Sets minimum message severity

Description

void sybase_min_message_severity ( int severity )

sybase_min_message_severity() sets the minimum message severity level.

Nota: This function is only available using the DB library interface to Sybase, and not the CT library.

See also sybase_min_error_severity().

sybase_min_server_severity

(PHP 3, PHP 4, PHP 5)

sybase_min_server_severity -- Sets minimum server severity

Description

void sybase_min_server_severity ( int severity )

sybase_min_server_severity() sets the minimum server severity level.

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

See also sybase_min_client_severity().

sybase_num_fields

(PHP 3, PHP 4, PHP 5)

sybase_num_fields -- Gets the number of fields in a result set

Description

int sybase_num_fields ( resource result )

sybase_num_fields() returns the number of fields in a result set.

See also sybase_query(), sybase_fetch_field() and sybase_num_rows().

sybase_num_rows

(PHP 3, PHP 4, PHP 5)

sybase_num_rows -- Get number of rows in a result set

Description

int sybase_num_rows ( resource result )

sybase_num_rows() returns the number of rows in a result set.

See also sybase_num_fields(), sybase_query() and sybase_fetch_row().

sybase_pconnect

(PHP 3, PHP 4, PHP 5)

sybase_pconnect -- Open persistent Sybase connection

Description

resource sybase_pconnect ( [string servername [, string username [, string password [, string charset [, string appname]]]]] )

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

sybase_pconnect() acts very much like sybase_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).

This type of links is therefore called 'persistent'.

See also sybase_connect().

sybase_query

(PHP 3, PHP 4, PHP 5)

sybase_query -- Sends a Sybase query

Description

mixed sybase_query ( string query [, resource link_identifier] )

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

See also sybase_select_db() and sybase_connect().

sybase_result

(PHP 3, PHP 4, PHP 5)

sybase_result -- Get result data

Description

string sybase_result ( resource result, int row, mixed field )

Returns the contents of the cell at the row and offset in the specified Sybase result set.

sybase_result() returns the contents of one cell from a Sybase result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives: sybase_fetch_row(), sybase_fetch_array() and sybase_fetch_object().

sybase_select_db

(PHP 3, PHP 4, PHP 5)

sybase_select_db -- Selects a Sybase database

Description

bool sybase_select_db ( string database_name [, resource link_identifier] )

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Every subsequent call to sybase_query() will be made on the active database.

See also sybase_connect(), sybase_pconnect() and sybase_query()

sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handler -- Sets the handler called when a server message is raised

Description

bool sybase_set_message_handler ( callback handler [, resource connection] )

sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

The handler expects five arguments in the following order: message number, severity, state, line number and description. The first four are integers. The last is a string. If the function returns FALSE, PHP generates an ordinary error message.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: The connection parameter was added in PHP 4.3.5.

Esempio 1. sybase_set_message_handler() callback function

<?php
    function msg_handler($msgnumber, $severity, $state, $line, $text) 
    {
        var_dump($msgnumber, $severity, $state, $line, $text);
    }
    
    sybase_set_message_handler('msg_handler');
?>

Esempio 2. sybase_set_message_handler() callback to a class

<?php
    class Sybase {
        function handler($msgnumber, $severity, $state, $line, $text) 
        {
            var_dump($msgnumber, $severity, $state, $line, $text);
        }
    }
    
    $sybase= new Sybase();
    sybase_set_message_handler(array($sybase, 'handler'));
?>

Esempio 3. sybase_set_message_handler() unhandled messages

<?php
    // Return FALSE from this function to indicate you can't handle
    // this. The error is printed out as a warning, the way you're used
    // to it if there is no handler installed.
    function msg_handler($msgnumber, $severity, $state, $line, $text) 
    {
        if (257 == $msgnumber) {
            return false;
        }
        var_dump($msgnumber, $severity, $state, $line, $text);
    }
    
    sybase_set_message_handler('msg_handler');
?>

sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_query -- Send a Sybase query and do not block

Description

resource sybase_unbuffered_query ( string query, resource link_identifier [, bool store_result] )

Returns a positive Sybase result identifier on success, or FALSE on error.

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

sybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.

sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.

Nota: If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.

The optional store_result can be FALSE to indicate the resultsets shouldn't be fetched into memory, thus minimizing memory usage which is particularly interesting with very large resultsets.

Esempio 1. sybase_unbuffered_query() example

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_unbuffered_query('select firstname, lastname from huge_table', $dbh, false);
sybase_data_seek($q, 10000);
$i = 0;

while ($row = sybase_fetch_row($q)) {
    echo $row[0], ' ', $row[1], '<br />';
    if ($i++ > 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?>

See also sybase_query().

CXLVIII. TCP Wrappers Functions

Introduzione

The TCP wrappers provides a classical unix mechanism which has been designed to check if the remote client is able to connect from the given IP address.


Installazione

Tcpwrap is currently available through PECL http://pecl.php.net/package/tcpwrap.

If PEAR is available on your *nix-like system you can use the pear installer to install the tcpwrap extension, by the following command: pear -v install tcpwrap.

You can always download the tar.gz package and install tcpwrap by hand:

Esempio 1. tcpwrap install by hand

gunzip tcpwrap-xxx.tgz
tar -xvf tcpwrap-xxx.tar
cd tcpwrap-xxx
phpize
./configure && make && make install

Sommario
tcpwrap_check -- Performs a tcpwrap check

tcpwrap_check

(PECL)

tcpwrap_check -- Performs a tcpwrap check

Descrizione

bool tcpwrap_check ( string daemon, string address [, string user [, bool nodns]] )

This function consults the /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for a client.

Elenco dei parametri

daemon

The service name.

address

The client remote address. Can be either an IP address or a domain name.

user

An optional user name.

nodns

If address looks like domain name then DNS is used to resolve it to IP address; set nodns to TRUE to avoid this.

Valori restituiti

This function returns TRUE if access should be granted, FALSE otherwise.

Esempi

Esempio 1. Deny all connections from localhost

If your /etc/hosts.deny file contains:

php: 127.0.0.1

And your code looks like:

<?php
if (!tcpwrap_check('php', $_SERVER['REMOTE_ADDR'])) {
  die('You are not welcome here');
}
?>

Vedere anche:

For more details please consult hosts_access(3) man page.

CXLIX. Tidy Functions

Introduzione

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.


Requisiti

To use Tidy, you will need libtidy installed, available on the tidy homepage http://tidy.sourceforge.net/.


Installazione

Tidy is currently available for PHP 4.3.x and PHP 5 as a PECL extension from http://pecl.php.net/package/tidy.

Nota: Tidy 1.0 is just for PHP 4.3.x, while Tidy 2.0 is just for PHP 5.

If PEAR is available on your *nix-like system you can use the pear installer to install the tidy extension, by the following command: pear -v install tidy.

You can always download the tar.gz package and install tidy by hand:

Esempio 1. tidy install by hand in PHP 4.3.x

gunzip tidy-xxx.tgz
tar -xvf tidy-xxx.tar
cd tidy-xxx
phpize
./configure && make && make install

Windows users can download the extension dll php_tidy.dll from http://snaps.php.net/win32/PECL_STABLE/.

In PHP 5 you need only to compile using the --with-tidy option.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Tidy Configuration Options

NameDefaultChangeableChangelog
tidy.default_config""PHP_INI_SYSTEMAvailable since PHP 5.0.0.
tidy.clean_output"0"PHP_INI_PERDIRAvailable since PHP 5.0.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

tidy.default_config string

Default path for tidy config file.

tidy.clean_output boolean

Turns on/off the output repairing by Tidy.

Avvertimento

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Classi predefinite

tidyNode

Metodi


Proprietà

  • value - the value of the node (e.g. the html text)

  • name - the name of the tag (e.g. html, a, etc..)

  • type - the type of the node (one of the constants above, e.g. TIDY_NODETYPE_PHP)

  • line* - the line where the node starts

  • column* - the column where the node starts

  • proprietary* - TRUE if the node refers to a proprietary tag

  • id - the ID of the tag (one of the constants above, e.g. TIDY_TAG_FRAME)

  • attribute - an array with the attributes of the current node, or NULL if there aren't any

  • child - an array with the child tidyNodes, or NULL if there aren't any

Nota: The properties marked with * are just available since PHP 5.1.0.


Costanti predefinite

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.

Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a <a href="XX">link</a> tag. Each TIDY_ATTR_XXX represents a HTML atribute. For example TIDY_ATTR_HREF would represent the href atribute in the previous example.

The following constants are defined:

Tabella 2. tidy tag constants

constant
TIDY_TAG_UNKNOWN
TIDY_TAG_A
TIDY_TAG_ABBR
TIDY_TAG_ACRONYM
TIDY_TAG_ALIGN
TIDY_TAG_APPLET
TIDY_TAG_AREA
TIDY_TAG_B
TIDY_TAG_BASE
TIDY_TAG_BASEFONT
TIDY_TAG_BDO
TIDY_TAG_BGSOUND
TIDY_TAG_BIG
TIDY_TAG_BLINK
TIDY_TAG_BLOCKQUOTE
TIDY_TAG_BODY
TIDY_TAG_BR
TIDY_TAG_BUTTON
TIDY_TAG_CAPTION
TIDY_TAG_CENTER
TIDY_TAG_CITE
TIDY_TAG_CODE
TIDY_TAG_COL
TIDY_TAG_COLGROUP
TIDY_TAG_COMMENT
TIDY_TAG_DD
TIDY_TAG_DEL
TIDY_TAG_DFN
TIDY_TAG_DIR
TIDY_TAG_DIV
TIDY_TAG_DL
TIDY_TAG_DT
TIDY_TAG_EM
TIDY_TAG_EMBED
TIDY_TAG_FIELDSET
TIDY_TAG_FONT
TIDY_TAG_FORM
TIDY_TAG_FRAME
TIDY_TAG_FRAMESET
TIDY_TAG_H1
TIDY_TAG_H2
TIDY_TAG_H3
TIDY_TAG_H4
TIDY_TAG_H5
TIDY_TAG_H6
TIDY_TAG_HEAD
TIDY_TAG_HR
TIDY_TAG_HTML
TIDY_TAG_I
TIDY_TAG_IFRAME
TIDY_TAG_ILAYER
TIDY_TAG_IMG
TIDY_TAG_INPUT
TIDY_TAG_INS
TIDY_TAG_ISINDEX
TIDY_TAG_KBD
TIDY_TAG_KEYGEN
TIDY_TAG_LABEL
TIDY_TAG_LAYER
TIDY_TAG_LEGEND
TIDY_TAG_LI
TIDY_TAG_LINK
TIDY_TAG_LISTING
TIDY_TAG_MAP
TIDY_TAG_MARQUEE
TIDY_TAG_MENU
TIDY_TAG_META
TIDY_TAG_MULTICOL
TIDY_TAG_NOBR
TIDY_TAG_NOEMBED
TIDY_TAG_NOFRAMES
TIDY_TAG_NOLAYER
TIDY_TAG_NOSAFE
TIDY_TAG_NOSCRIPT
TIDY_TAG_OBJECT
TIDY_TAG_OL
TIDY_TAG_OPTGROUP
TIDY_TAG_OPTION
TIDY_TAG_P
TIDY_TAG_PARAM
TIDY_TAG_PLAINTEXT
TIDY_TAG_PRE
TIDY_TAG_Q
TIDY_TAG_RP
TIDY_TAG_RT
TIDY_TAG_RTC
TIDY_TAG_RUBY
TIDY_TAG_S
TIDY_TAG_SAMP
TIDY_TAG_SCRIPT
TIDY_TAG_SELECT
TIDY_TAG_SERVER
TIDY_TAG_SERVLET
TIDY_TAG_SMALL
TIDY_TAG_SPACER
TIDY_TAG_SPAN
TIDY_TAG_STRIKE
TIDY_TAG_STRONG
TIDY_TAG_STYLE
TIDY_TAG_SUB
TIDY_TAG_TABLE
TIDY_TAG_TBODY
TIDY_TAG_TD
TIDY_TAG_TEXTAREA
TIDY_TAG_TFOOT
TIDY_TAG_TH
TIDY_TAG_THEAD
TIDY_TAG_TITLE
TIDY_TAG_TR
TIDY_TAG_TR
TIDY_TAG_TT
TIDY_TAG_U
TIDY_TAG_UL
TIDY_TAG_VAR
TIDY_TAG_WBR
TIDY_TAG_XMP

Tabella 3. tidy attribute constants

constant
TIDY_ATTR_UNKNOWN
TIDY_ATTR_ABBR
TIDY_ATTR_ACCEPT
TIDY_ATTR_ACCEPT_CHARSET
TIDY_ATTR_ACCESSKEY
TIDY_ATTR_ACTION
TIDY_ATTR_ADD_DATE
TIDY_ATTR_ALIGN
TIDY_ATTR_ALINK
TIDY_ATTR_ALT
TIDY_ATTR_ARCHIVE
TIDY_ATTR_AXIS
TIDY_ATTR_BACKGROUND
TIDY_ATTR_BGCOLOR
TIDY_ATTR_BGPROPERTIES
TIDY_ATTR_BORDER
TIDY_ATTR_BORDERCOLOR
TIDY_ATTR_BOTTOMMARGIN
TIDY_ATTR_CELLPADDING
TIDY_ATTR_CELLSPACING
TIDY_ATTR_CHAR
TIDY_ATTR_CHAROFF
TIDY_ATTR_CHARSET
TIDY_ATTR_CHECKED
TIDY_ATTR_CITE
TIDY_ATTR_CLASS
TIDY_ATTR_CLASSID
TIDY_ATTR_CLEAR
TIDY_ATTR_CODE
TIDY_ATTR_CODEBASE
TIDY_ATTR_CODETYPE
TIDY_ATTR_COLOR
TIDY_ATTR_COLS
TIDY_ATTR_COLSPAN
TIDY_ATTR_COMPACT
TIDY_ATTR_CONTENT
TIDY_ATTR_COORDS
TIDY_ATTR_DATA
TIDY_ATTR_DATAFLD
TIDY_ATTR_DATAPAGESIZE
TIDY_ATTR_DATASRC
TIDY_ATTR_DATETIME
TIDY_ATTR_DECLARE
TIDY_ATTR_DEFER
TIDY_ATTR_DIR
TIDY_ATTR_DISABLED
TIDY_ATTR_ENCODING
TIDY_ATTR_ENCTYPE
TIDY_ATTR_FACE
TIDY_ATTR_FOR
TIDY_ATTR_FRAME
TIDY_ATTR_FRAMEBORDER
TIDY_ATTR_FRAMESPACING
TIDY_ATTR_GRIDX
TIDY_ATTR_GRIDY
TIDY_ATTR_HEADERS
TIDY_ATTR_HEIGHT
TIDY_ATTR_HREF
TIDY_ATTR_HREFLANG
TIDY_ATTR_HSPACE
TIDY_ATTR_HTTP_EQUIV
TIDY_ATTR_ID
TIDY_ATTR_ISMAP
TIDY_ATTR_LABEL
TIDY_ATTR_LANG
TIDY_ATTR_LANGUAGE
TIDY_ATTR_LAST_MODIFIED
TIDY_ATTR_LAST_VISIT
TIDY_ATTR_LEFTMARGIN
TIDY_ATTR_LINK
TIDY_ATTR_LONGDESC
TIDY_ATTR_LOWSRC
TIDY_ATTR_MARGINHEIGHT
TIDY_ATTR_MARGINWIDTH
TIDY_ATTR_MAXLENGTH
TIDY_ATTR_MEDIA
TIDY_ATTR_METHOD
TIDY_ATTR_MULTIPLE
TIDY_ATTR_NAME
TIDY_ATTR_NOHREF
TIDY_ATTR_NORESIZE
TIDY_ATTR_NOSHADE
TIDY_ATTR_NOWRAP
TIDY_ATTR_OBJECT
TIDY_ATTR_OnAFTERUPDATE
TIDY_ATTR_OnBEFOREUNLOAD
TIDY_ATTR_OnBEFOREUPDATE
TIDY_ATTR_OnBLUR
TIDY_ATTR_OnCHANGE
TIDY_ATTR_OnCLICK
TIDY_ATTR_OnDATAAVAILABLE
TIDY_ATTR_OnDATASETCHANGED
TIDY_ATTR_OnDATASETCOMPLETE
TIDY_ATTR_OnDBLCLICK
TIDY_ATTR_OnERRORUPDATE
TIDY_ATTR_OnFOCUS
TIDY_ATTR_OnKEYDOWN
TIDY_ATTR_OnKEYPRESS
TIDY_ATTR_OnKEYUP
TIDY_ATTR_OnLOAD
TIDY_ATTR_OnMOUSEDOWN
TIDY_ATTR_OnMOUSEMOVE
TIDY_ATTR_OnMOUSEOUT
TIDY_ATTR_OnMOUSEOVER
TIDY_ATTR_OnMOUSEUP
TIDY_ATTR_OnRESET
TIDY_ATTR_OnROWENTER
TIDY_ATTR_OnROWEXIT
TIDY_ATTR_OnSELECT
TIDY_ATTR_OnSUBMIT
TIDY_ATTR_OnUNLOAD
TIDY_ATTR_PROFILE
TIDY_ATTR_PROMPT
TIDY_ATTR_RBSPAN
TIDY_ATTR_READONLY
TIDY_ATTR_REL
TIDY_ATTR_REV
TIDY_ATTR_RIGHTMARGIN
TIDY_ATTR_ROWS
TIDY_ATTR_ROWSPAN
TIDY_ATTR_RULES
TIDY_ATTR_SCHEME
TIDY_ATTR_SCOPE
TIDY_ATTR_SCROLLING
TIDY_ATTR_SELECTED
TIDY_ATTR_SHAPE
TIDY_ATTR_SHOWGRID
TIDY_ATTR_SHOWGRIDX
TIDY_ATTR_SHOWGRIDY
TIDY_ATTR_SIZE
TIDY_ATTR_SPAN
TIDY_ATTR_SRC
TIDY_ATTR_STANDBY
TIDY_ATTR_START
TIDY_ATTR_STYLE
TIDY_ATTR_SUMMARY
TIDY_ATTR_TABINDEX
TIDY_ATTR_TARGET
TIDY_ATTR_TEXT
TIDY_ATTR_TITLE
TIDY_ATTR_TOPMARGIN
TIDY_ATTR_TYPE
TIDY_ATTR_USEMAP
TIDY_ATTR_VALIGN
TIDY_ATTR_VALUE
TIDY_ATTR_VALUETYPE
TIDY_ATTR_VERSION
TIDY_ATTR_VLINK
TIDY_ATTR_VSPACE
TIDY_ATTR_WIDTH
TIDY_ATTR_WRAP
TIDY_ATTR_XML_LANG
TIDY_ATTR_XML_SPACE
TIDY_ATTR_XMLNS

Tabella 4. tidy nodetype constants

constantdescription
TIDY_NODETYPE_ROOTroot node
TIDY_NODETYPE_DOCTYPEdoctype
TIDY_NODETYPE_COMMENTHTML comment
TIDY_NODETYPE_PROCINSProcessing Instruction
TIDY_NODETYPE_TEXTText
TIDY_NODETYPE_STARTstart tag
TIDY_NODETYPE_ENDend tag
TIDY_NODETYPE_STARTENDempty tag
TIDY_NODETYPE_CDATACDATA
TIDY_NODETYPE_SECTIONXML section
TIDY_NODETYPE_ASPASP code
TIDY_NODETYPE_JSTEJSTE code
TIDY_NODETYPE_PHPPHP code
TIDY_NODETYPE_XMLDECLXML declaration


Esempi

This simple example shows basic Tidy usage.

Esempio 2. Basic Tidy usage

<?php
ob_start();
?>
<html>a html document</html>
<?
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>

Sommario
ob_tidyhandler --  ob_start callback function to repair the buffer
tidy_access_count --  Returns the Number of Tidy accessibility warnings encountered for specified document
tidy_clean_repair --  Execute configured cleanup and repair operations on parsed markup
tidy_config_count --  Returns the Number of Tidy configuration errors encountered for specified document
tidy::__construct --  Constructs a new tidy object
tidy_diagnose --  Run configured diagnostics on parsed and repaired markup
tidy_error_count --  Returns the Number of Tidy errors encountered for specified document
tidy_get_body --  Returns a tidyNode Object starting from the <body> tag of the tidy parse tree
tidy_get_config --  Get current Tidy configuration
tidy_get_error_buffer --  Return warnings and errors which occurred parsing the specified document
tidy_get_head --  Returns a tidyNode Object starting from the <head> tag of the tidy parse tree
tidy_get_html_ver --  Get the Detected HTML version for the specified document
tidy_get_html --  Returns a tidyNode Object starting from the <html> tag of the tidy parse tree
tidy_get_opt_doc --  Returns the documentation for the given option name
tidy_get_output --  Return a string representing the parsed tidy markup
tidy_get_release --  Get release date (version) for Tidy library
tidy_get_root --  Returns a tidyNode object representing the root of the tidy parse tree
tidy_get_status --  Get status of specified document
tidy_getopt --  Returns the value of the specified configuration option for the tidy document
tidy_is_xhtml --  Indicates if the document is a XHTML document
tidy_is_xml --  Indicates if the document is a generic (non HTML/XHTML) XML document
tidy_load_config --  Load an ASCII Tidy configuration file with the specified encoding
tidy_node->get_attr --  Return the attribute with the provided attribute id
tidy_node->get_nodes --  Return an array of nodes under this node with the specified id
tidy_node->next --  Returns the next sibling to this node
tidy_node->prev --  Returns the previous sibling to this node
tidy_parse_file --  Parse markup in file or URI
tidy_parse_string --  Parse a document stored in a string
tidy_repair_file --  Repair a file and return it as a string
tidy_repair_string --  Repair a string using an optionally provided configuration file
tidy_reset_config --  Restore Tidy configuration to default values
tidy_save_config --  Save current settings to named file
tidy_set_encoding --  Set the input/output character encoding for parsing markup
tidy_setopt --  Updates the configuration settings for the specified tidy document
tidy_warning_count --  Returns the Number of Tidy warnings encountered for specified document
tidyNode->hasChildren --  Returns true if this node has children
tidyNode->hasSiblings --  Returns true if this node has siblings
tidyNode->isAsp --  Returns true if this node is ASP
tidyNode->isComment --  Returns true if this node represents a comment
tidyNode->isHtml --  Returns true if this node is part of a HTML document
tidyNode->isJste --  Returns true if this node is JSTE
tidyNode->isPhp --  Returns true if this node is PHP
tidyNode->isText --  Returns true if this node represents text (no markup)

ob_tidyhandler

(PHP 5)

ob_tidyhandler --  ob_start callback function to repair the buffer

Description

string ob_tidyhandler ( string input [, int mode] )

ob_tidyhandler() is intended to be used as a callback function for ob_start() to repair the buffer.

Esempio 1. ob_tidyhandler() example

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See also ob_start().

tidy_access_count

(PHP 5)

tidy_access_count --  Returns the Number of Tidy accessibility warnings encountered for specified document

Description

int tidy_access_count ( tidy object )

tidy_access_count() returns the number of accessibility warnings found for the specified document.

Nota: Due to the design of the TidyLib, you must call tidy_diagnose() before tidy_access_count() or it will return always 0. You must also need to enable the accessibility-check option.

Esempio 1. tidy_access_count() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';


// select the accessibility check level: 1, 2 or 3
$config = array('accessibility-check' => 3);

$tidy = new tidy();
$tidy->parseString($html, $config);
$tidy->CleanRepair();

/* Never forget to call this! */
$tidy->diagnose();

echo tidy_access_count($tidy); //5

?>

See also tidy_error_count() and tidy_warning_count().

tidy_clean_repair

(PHP 5)

tidy_clean_repair --  Execute configured cleanup and repair operations on parsed markup

Description

Procedural style:

bool tidy_clean_repair ( tidy object )

Object oriented style:

bool tidy->cleanRepair ( void )

This function cleans and repairs the given tidy object.

Esempio 1. tidy_clean_repair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
tidy_clean_repair($tidy);

echo $tidy;
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See also tidy_repair_file() and tidy_repair_string().

tidy_config_count

(PHP 5)

tidy_config_count --  Returns the Number of Tidy configuration errors encountered for specified document

Description

int tidy_config_count ( tidy object )

tidy_config_count() returns the number of errors encountered in the configuration of the specified tidy object.

Esempio 1. tidy_config_count() example

<?php
$html = '<p>test</I>';

$config = array('doctype' => 'bogus');

$tidy = tidy_parse_string($html, $config);

/* This outputs 1, because 'bogus' isn't a valid doctype */
echo tidy_config_count($tidy);
?>

tidy::__construct

(no version information, might be only in CVS)

tidy::__construct --  Constructs a new tidy object

Description

tidy tidy::__construct ( [string filename [, mixed config [, string encoding [, bool use_include_path]]]] )

tidy::__construct() constructs a new tidy object.

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.

Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.

Esempio 1. tidy::__construct() example

<?php

$html = <<< HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <bt />
text</p>
</body></html>

HTML;

$tidy = new tidy;
$tidy->parseString($html);

$tidy->CleanRepair();

if ($tidy->errorBuffer) {
    echo "The following errors were detected:\n";
    echo $tidy->errorBuffer;
}

?>

Il precedente esempio visualizzerà:

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

See also tidy_parse_file() and tidy_parse_string().

tidy_diagnose

(PHP 5)

tidy_diagnose --  Run configured diagnostics on parsed and repaired markup

Description

Procedural style:

bool tidy_diagnose ( tidy object )

Object oriented style:

bool tidy->diagnose ( void )

tidy_diagnose() runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. tidy_diagnose() example

<?php

$html = <<< HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<p>paragraph</p>
HTML;

$tidy = tidy_parse_string($html);
$tidy->CleanRepair();

// note the difference between the two outputs
echo tidy_get_error_buffer($tidy) . "\n";

$tidy->diagnose();
echo tidy_get_error_buffer($tidy);

?>

Il precedente esempio visualizzerà:

line 5 column 1 - Warning: <p> isn't allowed in <head> elements
line 5 column 1 - Warning: inserting missing 'title' element

line 5 column 1 - Warning: <p> isn't allowed in <head> elements
line 5 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

See also tidy_get_error_buffer().

tidy_error_count

(PHP 5)

tidy_error_count --  Returns the Number of Tidy errors encountered for specified document

Description

int tidy_error_count ( tidy object )

tidy_error_count() returns the number of Tidy errors encountered for the specified document.

Esempio 1. tidy_error_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy->ErrorBuffer;
?>

Il precedente esempio visualizzerà:

1
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 8 - Warning: discarding unexpected </i>
line 2 column 1 - Error: <bogustag> is not recognized!
line 2 column 1 - Warning: discarding unexpected <bogustag>
line 2 column 16 - Warning: discarding unexpected </bogustag>
line 1 column 1 - Warning: inserting missing 'title' element

See also tidy_access_count() and tidy_warning_count().

tidy_get_body

(PHP 5)

tidy_get_body --  Returns a tidyNode Object starting from the <body> tag of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_body ( tidy object )

Object oriented style:

tidyNode tidy->body ( void )

This function returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Esempio 1. tidy_get_body() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$body = tidy_get_body($tidy);
echo $body->value;
?>

Il precedente esempio visualizzerà:

<body>
<p>paragraph</p>
</body>

Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.

See also tidy_get_head() and tidy_get_html().

tidy_get_config

(PHP 5)

tidy_get_config --  Get current Tidy configuration

Description

Procedural style:

array tidy_get_config ( tidy object )

Object oriented style:

array tidy->getConfig ( void )

tidy_get_config() returns an array with the configuration options in use by the given tidy object.

For an explanation about each option, visit http://tidy.sourceforge.net/docs/quickref.html.

Esempio 1. tidy_get_config() example

<?php
$html = '<p>test</p>';
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($html, $config);

print_r(tidy_get_config($tidy));
?>

Il precedente esempio visualizzerà:

Array
(
    [indent-spaces] => 2
    [wrap] => 200
    [tab-size] => 8
    [char-encoding] => 1
    [input-encoding] => 3
    [output-encoding] => 1
    [newline] => 1
    [doctype-mode] => 1
    [doctype] => 
    [repeated-attributes] => 1
    [alt-text] => 
    [slide-style] => 
    [error-file] => 
    [output-file] => 
    [write-back] => 
    [markup] => 1
    [show-warnings] => 1
    [quiet] => 
    [indent] => 1
    [hide-endtags] => 
    [input-xml] => 
    [output-xml] => 1
    [output-xhtml] => 1
    [output-html] => 
    [add-xml-decl] => 
    [uppercase-tags] => 
    [uppercase-attributes] => 
    [bare] => 
    [clean] => 
    [logical-emphasis] => 
    [drop-proprietary-attributes] => 
    [drop-font-tags] => 
    [drop-empty-paras] => 1
    [fix-bad-comments] => 1
    [break-before-br] => 
    [split] => 
    [numeric-entities] => 
    [quote-marks] => 
    [quote-nbsp] => 1
    [quote-ampersand] => 1
    [wrap-attributes] => 
    [wrap-script-literals] => 
    [wrap-sections] => 1
    [wrap-asp] => 1
    [wrap-jste] => 1
    [wrap-php] => 1
    [fix-backslash] => 1
    [indent-attributes] => 
    [assume-xml-procins] => 
    [add-xml-space] => 
    [enclose-text] => 
    [enclose-block-text] => 
    [keep-time] => 
    [word-2000] => 
    [tidy-mark] => 
    [gnu-emacs] => 
    [gnu-emacs-file] => 
    [literal-attributes] => 
    [show-body-only] => 
    [fix-uri] => 1
    [lower-literals] => 1
    [hide-comments] => 
    [indent-cdata] => 
    [force-output] => 1
    [show-errors] => 6
    [ascii-chars] => 1
    [join-classes] => 
    [join-styles] => 1
    [escape-cdata] => 
    [language] => 
    [ncr] => 1
    [output-bom] => 2
    [replace-color] => 
    [css-prefix] => 
    [new-inline-tags] => 
    [new-blocklevel-tags] => 
    [new-empty-tags] => 
    [new-pre-tags] => 
    [accessibility-check] => 0
    [vertical-space] => 
    [punctuation-wrap] => 
    [merge-divs] => 1
)

See also tidy_reset_config() and tidy_save_config().

tidy_get_error_buffer

(PHP 5)

tidy_get_error_buffer --  Return warnings and errors which occurred parsing the specified document

Description

Procedural style:

string tidy_get_error_buffer ( tidy object )

Object oriented style (property):

class tidy {

string errorBuffer

}

tidy_get_error_buffer() returns warnings and errors which occurred parsing the specified document.

Esempio 1. tidy_get_error_buffer() example

<?php
$html = '<p>paragraph</p>';

$tidy = tidy_parse_string($html);

echo tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy->errorBuffer;
?>

Il precedente esempio visualizzerà:

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

See also tidy_access_count(), tidy_error_count() and tidy_warning_count().

tidy_get_head

(PHP 5)

tidy_get_head --  Returns a tidyNode Object starting from the <head> tag of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_head ( tidy object )

Object oriented style:

tidyNode tidy->head ( void )

This function returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Esempio 1. tidy_get_head() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$head = tidy_get_head($tidy);
echo $head->value;
?>

Il precedente esempio visualizzerà:

<head>
<title>test</title>
</head>

Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.

See also tidy_get_body() and tidy_get_html().

tidy_get_html_ver

(PHP 5)

tidy_get_html_ver --  Get the Detected HTML version for the specified document

Description

Procedural style:

int tidy_get_html_ver ( tidy object )

Object oriented style:

int tidy->getHtmlVer ( void )

tidy_get_html_ver() returns the detected HTML version for the specified tidy object.

Avvertimento

This function is not yet implemented in the Tidylib itself, so it always return 0.

tidy_get_html

(PHP 5)

tidy_get_html --  Returns a tidyNode Object starting from the <html> tag of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_html ( tidy object )

Object oriented style:

tidyNode tidy->html ( void )

This function returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Esempio 1. tidy_get_html() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$html = tidy_get_html($tidy);
echo $html->value;
?>

Il precedente esempio visualizzerà:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.

See also tidy_get_body() and tidy_get_head().

tidy_get_opt_doc

(PHP 5 >= 5.1.0RC1)

tidy_get_opt_doc --  Returns the documentation for the given option name

Descrizione

Procedural style:

string tidy_get_opt_doc ( tidy object, string optname )

Object oriented style:

string tidy->getOptDoc ( string optname )

tidy_get_opt_doc() returns the documentation for the given option name.

Nota: You need at least libtidy from 25 April, 2005 for this function be available.

Elenco dei parametri

object

A tidy object

optname

The option name

Valori restituiti

Returns a string if the option exists and has documentation available, or FALSE otherwise.

Esempi

Esempio 1. Print all options along with their documentation and default value

<?php

$tidy = new tidy;
$config = $tidy->getConfig();

ksort($config);

foreach ($config as $opt => $val) {

    if (!$doc = $tidy->getOptDoc($opt))
        $doc = 'no documentation available!';

    $val = ($tidy->getOpt($opt) === true)  ? 'true'  : $val;
    $val = ($tidy->getOpt($opt) === false) ? 'false' : $val;

    echo "<p><b>$opt</b> (default: '$val')<br />".
         "$doc</p><hr />\n";
}

?>

tidy_get_output

(PHP 5)

tidy_get_output --  Return a string representing the parsed tidy markup

Description

string tidy_get_output ( tidy object )

tidy_get_output() returns a string with the repaired html.

Esempio 1. tidy_get_output() example

<?php

$html = '<p>paragraph</i>';
$tidy = tidy_parse_string($html);

$tidy->CleanRepair();

echo tidy_get_output($tidy);
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

tidy_get_release

(PHP 5)

tidy_get_release --  Get release date (version) for Tidy library

Description

Procedural style:

string tidy_get_release ( void )

Object oriented style:

string tidy->getRelease ( void )

This function returns a string with the release date of the Tidy library.

tidy_get_root

(PHP 5)

tidy_get_root --  Returns a tidyNode object representing the root of the tidy parse tree

Description

Procedural style:

tidyNode tidy_get_root ( tidy object )

Object oriented style:

tidyNode tidy->root ( void )

Returns a tidyNode object representing the root of the tidy parse tree.

Esempio 1. dump nodes

<?php

$html = <<< HTML
<html><body>

<p>paragraph</p>
<br/>

</body></html>
HTML;

$tidy = tidy_parse_string($html);
dump_nodes($tidy->root(), 1);


function dump_nodes($node, $indent) {

    if($node->hasChildren()) {
        foreach($node->child as $child) {
            echo str_repeat('.', $indent*2) . ($child->name ? $child->name : '"'.$child->value.'"'). "\n";

            dump_nodes($child, $indent+1);
        }
    }
}
?>

Il precedente esempio visualizzerà:

..html
....head
......title
....body
......p
........"paragraph"
......br

Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.

tidy_get_status

(PHP 5)

tidy_get_status --  Get status of specified document

Description

Procedural style:

int tidy_get_status ( tidy object )

Object oriented style:

int tidy->getStatus ( void )

tidy_get_status() returns the status for the specified tidy object. It returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Esempio 1. tidy_get_status() example

<?php
$html = '<p>paragraph</i>';
$tidy = tidy_parse_string($html);

$html2 = '<bogus>test</bogus>';
$tidy2 = tidy_parse_string($html2);

echo tidy_get_status($tidy); //1

echo tidy_get_status($tidy2); //2
?>

tidy_getopt

(PHP 5)

tidy_getopt --  Returns the value of the specified configuration option for the tidy document

Description

Procedural style:

mixed tidy_getopt ( tidy object, string option )

Object oriented style:

mixed tidy->getOpt ( string option )

tidy_getopt() returns the value of the specified option for the specified tidy object. The return type depends on the type of the specified option. You will find a list with each configuration option and their types at: http://tidy.sourceforge.net/docs/quickref.html.

Esempio 1. tidy_getopt() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

$config = array('accessibility-check' => 3,
                'alt-text' => 'some text');

$tidy = new tidy();
$tidy->parseString($html, $config);


var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string

?>

Il precedente esempio visualizzerà:

int(3)
bool(true)
string(9) "some text"

tidy_is_xhtml

(PHP 5)

tidy_is_xhtml --  Indicates if the document is a XHTML document

Description

Procedural style:

bool tidy_is_xhtml ( tidy object )

Object oriented style:

bool tidy->isXhtml ( void )

This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.

Avvertimento

This function is not yet implemented in the Tidylib itself, so it always return FALSE.

tidy_is_xml

(PHP 5)

tidy_is_xml --  Indicates if the document is a generic (non HTML/XHTML) XML document

Description

Procedural style:

bool tidy_is_xml ( tidy object )

Object oriented style:

bool tidy->isXml ( void )

This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.

Avvertimento

This function is not yet implemented in the Tidylib itself, so it always return FALSE.

tidy_load_config

(no version information, might be only in CVS)

tidy_load_config --  Load an ASCII Tidy configuration file with the specified encoding

Description

void tidy_load_config ( string filename, string encoding )

This function loads a Tidy configuration file, with the specified encoding.

Nota: Questa funzione ` disponibile soltanto in Tidy 1.0. Sarà obsoleta in Tidy 2.0, e quindi sar` rimossa.

tidy_node->get_attr

(no version information, might be only in CVS)

tidy_node->get_attr --  Return the attribute with the provided attribute id

Description

tidy_attr tidy_node->get_attr ( int attrib_id )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

tidy_node->get_nodes

(no version information, might be only in CVS)

tidy_node->get_nodes --  Return an array of nodes under this node with the specified id

Description

array tidy_node->get_nodes ( int node_id )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

tidy_node->next

(no version information, might be only in CVS)

tidy_node->next --  Returns the next sibling to this node

Description

tidy_node tidy_node->next ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

tidy_node->prev

(no version information, might be only in CVS)

tidy_node->prev --  Returns the previous sibling to this node

Description

tidy_node tidy_node->prev ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

tidy_parse_file

(PHP 5)

tidy_parse_file --  Parse markup in file or URI

Description

Procedural style:

tidy tidy_parse_file ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )

Object oriented style:

bool tidy->parseFile ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )

This function parses the given file.

Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.

Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.

Esempio 1. tidy_parse_file() example

<?php
$tidy = tidy_parse_file('file.html');

$tidy->cleanRepair();
    
if(!empty($tidy->errorBuffer)) {
    echo "The following errors or warnings occured:\n";
    echo $tidy->errorBuffer;
}
?>

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

See also tidy_parse_string(), tidy_repair_file() and tidy_repair_string().

tidy_parse_string

(PHP 5)

tidy_parse_string --  Parse a document stored in a string

Description

Procedural style:

tidy tidy_parse_string ( string input [, mixed config [, string encoding]] )

Object oriented style:

bool tidy->parseString ( string input [, mixed config [, string encoding]] )

tidy_parse_string() parses a document stored in a string.

Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.

Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.

Esempio 1. tidy_parse_string() example

<?php
ob_start();
?>

<html>
  <head>
   <title>test</title>
  </head>
  <body>
   <p>error<br>another line</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy->cleanRepair();
echo $tidy;
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error<br />
      another line
    </p>
  </body>
</html>

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

See also tidy_parse_file(), tidy_repair_file() and tidy_repair_string().

tidy_repair_file

(PHP 5)

tidy_repair_file --  Repair a file and return it as a string

Description

string tidy_repair_file ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )

This function repairs the given file and returns it as a string.

Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.

Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.

Esempio 1. tidy_repair_file() example

<?php
$file = 'file.html';

$repaired = tidy_repair_file($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?>

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

See also tidy_parse_file(), tidy_parse_string() and tidy_repair_string().

tidy_repair_string

(PHP 5)

tidy_repair_string --  Repair a string using an optionally provided configuration file

Description

string tidy_repair_string ( string data [, mixed config [, string encoding]] )

This function repairs the given string.

Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.

Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.

Esempio 1. tidy_repair_string() example

<?php
ob_start();
?>

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>error</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$tidy = tidy_repair_string($buffer);

echo $tidy;
?>

Il precedente esempio visualizzerà:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.

See also tidy_parse_file(), tidy_parse_string() and tidy_repair_file().

tidy_reset_config

(no version information, might be only in CVS)

tidy_reset_config --  Restore Tidy configuration to default values

Description

bool tidy_reset_config ( void )

This function restores the Tidy configuration to the default values.

Nota: Questa funzione ` disponibile soltanto in Tidy 1.0. Sarà obsoleta in Tidy 2.0, e quindi sar` rimossa.

tidy_save_config

(no version information, might be only in CVS)

tidy_save_config --  Save current settings to named file

Description

bool tidy_save_config ( string filename )

tidy_save_config() saves current settings to the specified file. Only non-default values are written.

See also tidy_get_config(), tidy_getopt(), tidy_reset_config() and tidy_setopt().

Nota: Questa funzione ` disponibile soltanto in Tidy 1.0. Sarà obsoleta in Tidy 2.0, e quindi sar` rimossa.

tidy_set_encoding

(no version information, might be only in CVS)

tidy_set_encoding --  Set the input/output character encoding for parsing markup

Description

bool tidy_set_encoding ( string encoding )

Sets the encoding for input/output documents. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Possible values for encoding are ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5 and shiftjis

Nota: Questa funzione ` disponibile soltanto in Tidy 1.0. Sarà obsoleta in Tidy 2.0, e quindi sar` rimossa.

tidy_setopt

(no version information, might be only in CVS)

tidy_setopt --  Updates the configuration settings for the specified tidy document

Description

bool tidy_setopt ( string option, mixed value )

tidy_setopt() updates the specified option with a new value.

Esempio 1. tidy_setopt() example

<?php
$html = '<p>test</i>';

$tidy = tidy_parse_string($html);

tidy_setopt('indent', FALSE);
?>

See also tidy_getopt(), tidy_get_config(), tidy_reset_config() and tidy_save_config().

Nota: Questa funzione ` disponibile soltanto in Tidy 1.0. Sarà obsoleta in Tidy 2.0, e quindi sar` rimossa.

tidy_warning_count

(PHP 5)

tidy_warning_count --  Returns the Number of Tidy warnings encountered for specified document

Description

int tidy_warning_count ( tidy object )

tidy_warning_count() returns the number of Tidy warnings encountered for the specified document.

Esempio 1. tidy_warning_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1
echo tidy_warning_count($tidy) . "\n"; //5
?>

See also tidy_access_count() and tidy_error_count().

tidyNode->hasChildren

(no version information, might be only in CVS)

tidyNode->hasChildren --  Returns true if this node has children

Description

bool tidyNode->hasChildren ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->has_children() in PHP 4/Tidy 1.

tidyNode->hasSiblings

(no version information, might be only in CVS)

tidyNode->hasSiblings --  Returns true if this node has siblings

Description

bool tidyNode->hasSiblings ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->has_siblings() in PHP 4/Tidy 1.

tidyNode->isAsp

(no version information, might be only in CVS)

tidyNode->isAsp --  Returns true if this node is ASP

Description

bool tidyNode->isAsp ( void )

This functions returns TRUE if the current node is ASP, or FALSE otherwise.

Nota: This function was named tidy_node->is_asp() in PHP 4/Tidy 1.

tidyNode->isComment

(no version information, might be only in CVS)

tidyNode->isComment --  Returns true if this node represents a comment

Description

bool tidyNode->isComment ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_comment() in PHP 4/Tidy 1.

tidyNode->isHtml

(no version information, might be only in CVS)

tidyNode->isHtml --  Returns true if this node is part of a HTML document

Description

bool tidyNode->isHtml ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_html() in PHP 4/Tidy 1.

tidyNode->isJste

(no version information, might be only in CVS)

tidyNode->isJste --  Returns true if this node is JSTE

Description

bool tidyNode->isJste ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_jste() in PHP 4/Tidy 1.

tidyNode->isPhp

(no version information, might be only in CVS)

tidyNode->isPhp --  Returns true if this node is PHP

Description

bool tidyNode->isPhp ( void )

Returns TRUE if the current node is PHP code, FALSE otherwise.

Esempio 1. get the PHP code from a mixed HTML/PHP document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
</head>
<body>

<?php
echo 'hello world!';
?>

</body></html>
HTML;


$tidy = tidy_parse_string($html);
$num = 0;

get_php($tidy->html());


function get_php($node) {

    // check if the current node is PHP code
    if($node->isPhp()) {
        echo "\n\n# PHP node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_php($child);
        }
    }
}

?>

Il precedente esempio visualizzerà:

# PHP node #1
<?php echo '<title>title</title>'; ?>

# PHP node #2
<?php
echo 'hello world!';
?>

Nota: This function was named tidy_node->is_php() in PHP 4/Tidy 1.

tidyNode->isText

(no version information, might be only in CVS)

tidyNode->isText --  Returns true if this node represents text (no markup)

Description

bool tidyNode->isText ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_text() in PHP 4/Tidy 1.

CL. Tokenizer Functions

Introduzione

The tokenizer functions provide an interface to the PHP tokenizer embedded in the Zend Engine. Using these functions you may write your own PHP source analyzing or modification tools without having to deal with the language specification at the lexical level.

See also the appendix about tokens.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Beginning with PHP 4.3.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-tokenizer. You can disable tokenizer support with --disable-tokenizer.

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: Builtin support for tokenizer is available with PHP 4.3.0.


Costanti predefinite

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.

T_INCLUDE (integer)

T_INCLUDE_ONCE (integer)

T_EVAL (integer)

T_REQUIRE (integer)

T_REQUIRE_ONCE (integer)

T_LOGICAL_OR (integer)

T_LOGICAL_XOR (integer)

T_LOGICAL_AND (integer)

T_PRINT (integer)

T_PLUS_EQUAL (integer)

T_MINUS_EQUAL (integer)

T_MUL_EQUAL (integer)

T_DIV_EQUAL (integer)

T_CONCAT_EQUAL (integer)

T_MOD_EQUAL (integer)

T_AND_EQUAL (integer)

T_OR_EQUAL (integer)

T_XOR_EQUAL (integer)

T_SL_EQUAL (integer)

T_SR_EQUAL (integer)

T_BOOLEAN_OR (integer)

T_BOOLEAN_AND (integer)

T_IS_EQUAL (integer)

T_IS_NOT_EQUAL (integer)

T_IS_IDENTICAL (integer)

T_IS_NOT_IDENTICAL (integer)

T_IS_SMALLER_OR_EQUAL (integer)

T_IS_GREATER_OR_EQUAL (integer)

T_SL (integer)

T_SR (integer)

T_INC (integer)

T_DEC (integer)

T_INT_CAST (integer)

T_DOUBLE_CAST (integer)

T_STRING_CAST (integer)

T_ARRAY_CAST (integer)

T_OBJECT_CAST (integer)

T_BOOL_CAST (integer)

T_UNSET_CAST (integer)

T_NEW (integer)

T_EXIT (integer)

T_IF (integer)

T_ELSEIF (integer)

T_ELSE (integer)

T_ENDIF (integer)

T_LNUMBER (integer)

T_DNUMBER (integer)

T_STRING (integer)

T_STRING_VARNAME (integer)

T_VARIABLE (integer)

T_NUM_STRING (integer)

T_INLINE_HTML (integer)

T_CHARACTER (integer)

T_BAD_CHARACTER (integer)

T_ENCAPSED_AND_WHITESPACE (integer)

T_CONSTANT_ENCAPSED_STRING (integer)

T_ECHO (integer)

T_DO (integer)

T_WHILE (integer)

T_ENDWHILE (integer)

T_FOR (integer)

T_ENDFOR (integer)

T_FOREACH (integer)

T_ENDFOREACH (integer)

T_DECLARE (integer)

T_ENDDECLARE (integer)

T_AS (integer)

T_SWITCH (integer)

T_ENDSWITCH (integer)

T_CASE (integer)

T_DEFAULT (integer)

T_BREAK (integer)

T_CONTINUE (integer)

T_OLD_FUNCTION (integer)

T_OLD_FUNCTION is not defined in PHP 5.

T_FUNCTION (integer)

T_CONST (integer)

T_RETURN (integer)

T_USE (integer)

T_GLOBAL (integer)

T_STATIC (integer)

T_VAR (integer)

T_UNSET (integer)

T_ISSET (integer)

T_EMPTY (integer)

T_CLASS (integer)

T_EXTENDS (integer)

T_OBJECT_OPERATOR (integer)

T_DOUBLE_ARROW (integer)

T_LIST (integer)

T_ARRAY (integer)

T_LINE (integer)

T_FILE (integer)

T_COMMENT (integer)

T_ML_COMMENT (integer)

T_ML_COMMENT is not defined in PHP 5. All comments in PHP 5 are of token T_COMMENT.

T_DOC_COMMENT (integer)

T_DOC_COMMENT was introduced in PHP 5.

T_OPEN_TAG (integer)

T_OPEN_TAG_WITH_ECHO (integer)

T_CLOSE_TAG (integer)

T_WHITESPACE (integer)

T_START_HEREDOC (integer)

T_END_HEREDOC (integer)

T_DOLLAR_OPEN_CURLY_BRACES (integer)

T_CURLY_OPEN (integer)

T_PAAMAYIM_NEKUDOTAYIM (integer)

T_DOUBLE_COLON (integer)

T_INTERFACE (integer)

PHP 5 only.

T_IMPLEMENTS (integer)

PHP 5 only.

T_CLASS_C (integer)

PHP 5 only.

T_FUNC_C (integer)

PHP 5 only.

T_METHOD_C (integer)

PHP 5 only.

T_ABSTRACT (integer)

PHP 5 only.

T_CATCH (integer)

PHP 5 only.

T_FINAL (integer)

PHP 5 only.

T_INSTANCEOF (integer)

PHP 5 only.

T_PRIVATE (integer)

PHP 5 only.

T_PROTECTED (integer)

PHP 5 only.

T_PUBLIC (integer)

PHP 5 only.

T_THROW (integer)

PHP 5 only.

T_TRY (integer)

PHP 5 only.

T_CLONE (integer)

PHP 5 only.


Esempi

Here is a simple example PHP scripts using the tokenizer that will read in a PHP file, strip all comments from the source and print the pure code only.

Esempio 1. Strip comments with the tokenizer

<?php
/*
 * T_ML_COMMENT does not exist in PHP 5.
 * The following three lines define it in order to
 * preserve backwards compatibility.
 *
 * The next two lines define the PHP 5 only T_DOC_COMMENT,
 * which we will mask as T_ML_COMMENT for PHP 4.
 */
if (!defined('T_ML_COMMENT')) {
    define('T_ML_COMMENT', T_COMMENT);
} else {
    define('T_DOC_COMMENT', T_ML_COMMENT);
}

$source = file_get_contents('example.php');
$tokens = token_get_all($source);

foreach ($tokens as $token) {
    if (is_string($token)) {
        // simple 1-character token
        echo $token;
    } else {
        // token array
        list($id, $text) = $token;
 
        switch ($id) { 
            case T_COMMENT: 
            case T_ML_COMMENT: // we've defined this
            case T_DOC_COMMENT: // and this
                // no action on comments
                break;

            default:
                // anything else -> output "as is"
                echo $text;
                break;
        }
    }
}
?>
Sommario
token_get_all -- Split given source into PHP tokens
token_name -- Get the symbolic name of a given PHP token

token_get_all

(PHP 4 >= 4.2.0, PHP 5)

token_get_all -- Split given source into PHP tokens

Descrizione

array token_get_all ( string source )

token_get_all() parses the given source string into PHP language tokens using the Zend engine's lexical scanner.

For a list of parser tokens, see Appendice Q, or use token_name() to translate a token value into its string representation.

Elenco dei parametri

source

The PHP source to parse.

Valori restituiti

An array of token identifiers. Each individual token identifier is either a single character (i.e.: ;, ., >, !, etc...), or a two element array containing the token index in element 0, and the string content of the original token in element 1.

Esempi

Esempio 1. token_get_all() examples

<?php
$tokens = token_get_all('<?php echo; ?>'); /* => array(
                                                  array(T_OPEN_TAG, '<?php'), 
                                                  array(T_ECHO, 'echo'),
                                                  ';',
                                                  array(T_CLOSE_TAG, '?>') ); */

/* Note in the following example that the string is parsed as T_INLINE_HTML
   rather than the otherwise expected T_COMMENT (T_ML_COMMENT in PHP <5).
   This is because no open/close tags were used in the "code" provided.
   This would be equivalent to putting a comment outside of <?php ?> tags in a normal file. */
$tokens = token_get_all('/* comment */'); // => array(array(T_INLINE_HTML, '/* comment */'));
?>

token_name

(PHP 4 >= 4.2.0, PHP 5)

token_name -- Get the symbolic name of a given PHP token

Descrizione

string token_name ( int token )

token_name() gets the symbolic name for a PHP token value.

Elenco dei parametri

token

The token value.

Valori restituiti

The symbolic name of the given token. The returned name returned matches the name of the matching token constant.

Esempi

Esempio 1. token_name() example

<?php
// 260 is the token value for the T_REQUIRE token
echo token_name(260);        // -> "T_REQUIRE"

// a token constant maps to its own name
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

Vedere anche:

List of Parser Tokens

CLI. Unicode Functions

Introduzione

Unicode Support.

Avvertimento

This extension is still in development and it isn't available to public yet.


Requisiti

ICU 3.4 or later is required.


Installazione

First you should download and install ICU:

Esempio 1. install ICU on Unix

./configure --disable-threads --enable-extras --enable-icuio --enable-layout
make && make install

Then checkout latest PHP and configure it --with-icu-dir=<dir> option, where <dir> was the dir to where you installed ICU. You don't need to explicitly use this option if you install ICU to a standard location.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Unicode Configuration Options

NameDefaultChangeableChangelog
unicode.fallback_encodingNULLPHP_INI_ALLAvailable since PHP 6.0.0.
unicode.from_error_mode2PHP_INI_ALLAvailable since PHP 6.0.0.
unicode.from_error_subst_char"3f"PHP_INI_ALLAvailable since PHP 6.0.0.
unicode.http_input_encodingNULLPHP_INI_ALLAvailable since PHP 6.0.0.
unicode.output_encodingNULLPHP_INI_ALLAvailable since PHP 6.0.0.
unicode.runtime_encodingNULLPHP_INI_ALLAvailable since PHP 6.0.0.
unicode.script_encodingNULLPHP_INI_ALLAvailable since PHP 6.0.0.
unicode.semanticsoffPHP_INI_PERDIRAvailable since PHP 6.0.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

unicode.output_encoding string

Default encoding for output.


Costanti predefinite

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.

constantvaluedescription
U_INVALID_STOP0stop at first invalid character
U_INVALID_SKIP1skip invalid characters
U_INVALID_SUBSTITUTE2replace invalid characters
U_INVALID_ESCAPE3escape invalid characters

Sommario
i18n_loc_get_default -- Get the default Locale
i18n_loc_set_default -- Set the default Locale
unicode_encode -- Takes a unicode string and converts it to a string in the specified encoding

i18n_loc_get_default

(no version information, might be only in CVS)

i18n_loc_get_default -- Get the default Locale

Descrizione

string i18n_loc_get_default ( void )

This function returns the default Locale, which is used by PHP to localize certain features. Please note that this isn't influenced by setlocale() or the system settings.

Valori restituiti

Returns a string with the current Locale.

Esempi

Esempio 1. A i18n_loc_get_default() example

<?php

// get the default Locale
echo i18n_loc_get_default();

//set a new Locale...
i18n_loc_set_default('pt_PT');

// ... and print it
echo i18n_loc_get_default();

?>

Il precedente esempio visualizzerà:

en_US_POSIX
pt_PT

Vedere anche:

i18n_loc_set_default()

i18n_loc_set_default

(no version information, might be only in CVS)

i18n_loc_set_default -- Set the default Locale

Descrizione

bool i18n_loc_set_default ( string name )

Sets the default Locale for PHP programs. Please note that this has nothing to do with setlocale() nor with the system locale.

Elenco dei parametri

name

The new Locale name. A comprehensive list of the supported locales is available at http://www-950.ibm.com/software/globalization/icu/demo/locales/en/?d_=en.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A i18n_loc_set_default() example

This example demonstrates a possible usage of i18n_loc_set_default() to localize the sort() functions.

<?php

// the list of the strings to sort
$array = array(
    'caramelo',
    'cacto',
    'caçada'
);

// set our locale (Portuguese, in this case)
i18n_loc_set_default('pt_PT');

// sort using the locale we previously set
sort($array, SORT_LOCALE_STRING);

print_r($array);
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => caçada
    [1] => cacto
    [2] => caramelo
)

If we didn't use the locale, PHP would sort the string using the ASCII characters value, thus returning (wrongly):

Array
(
    [0] => cacto
    [1] => caramelo
    [2] => caçada
)

Vedere anche:

i18n_loc_get_default()

unicode_encode

(PHP 5 CVS only)

unicode_encode -- Takes a unicode string and converts it to a string in the specified encoding

Descrizione

string unicode_encode ( unicode input, string encoding )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

input

Its description

encoding

Its description

Valori restituiti

What the function returns, first on success, then on failure.

Esempi

Esempio 1. A unicode_encode() example

Any text that describes the purpose of t

<?php
if ($anexample === true) {
    echo 'Use the PEAR Coding Standards';
}
?>

Il precedente esempio visualizzerà:

Use the PEAR Coding Standards

Vedere anche:

unicode_decode()

CLII. URL Functions

Introduzione

Dealing with URL strings: encoding, decoding and parsing.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
base64_decode -- Decodes data encoded with MIME base64
base64_encode -- Encodes data with MIME base64
get_headers --  Fetches all the headers sent by the server in response to a HTTP request
get_meta_tags --  Extracts all meta tag content attributes from a file and returns an array
http_build_query -- Generate URL-encoded query string
parse_url -- Parse a URL and return its components
rawurldecode -- Decode URL-encoded strings
rawurlencode -- URL-encode according to RFC 1738
urldecode -- Decodes URL-encoded string
urlencode -- URL-encodes string

base64_decode

(PHP 3, PHP 4, PHP 5)

base64_decode -- Decodes data encoded with MIME base64

Description

string base64_decode ( string encoded_data )

base64_decode() decodes encoded_data and returns the original data or FALSE on failure. The returned data may be binary.

Esempio 1. base64_decode() example

<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>

This example will produce:

This is an encoded string

See also base64_encode() and RFC 2045 section 6.8.

base64_encode

(PHP 3, PHP 4, PHP 5)

base64_encode -- Encodes data with MIME base64

Description

string base64_encode ( string data )

base64_encode() returns data encoded with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Base64-encoded data takes about 33% more space than the original data.

Esempio 1. base64_encode() example

<?php
  $str = 'This is an encoded string';
  echo base64_encode($str);
?>

This example will produce:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

See also base64_decode(), chunk_split(), convert_uuencode() and RFC 2045 section 6.8.

get_headers

(PHP 5)

get_headers --  Fetches all the headers sent by the server in response to a HTTP request

Description

array get_headers ( string url [, int format] )

get_headers() returns an array with the headers sent by the server in response to a HTTP request. Returns FALSE on failure and an error of level E_WARNING will be issued.

If the optional format parameter is set to 1, get_headers() parses the response and sets the array's keys.

Esempio 1. get_headers() example

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>

Il precedente esempio visualizzerà qualcosa simile a:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

get_meta_tags

(PHP 3 >= 3.0.4, PHP 4, PHP 5)

get_meta_tags --  Extracts all meta tag content attributes from a file and returns an array

Description

array get_meta_tags ( string filename [, bool use_include_path] )

Opens filename and parses it line by line for <meta> tags in the file. This can be a local file or an URL. The parsing stops at </head>.

Setting use_include_path to TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.

Esempio 1. What get_meta_tags() parses

<meta name="author" content="name">
<meta name="keywords" content="php documentation">
<meta name="DESCRIPTION" content="a php manual">
<meta name="geo.position" content="49.33;-86.59">
</head> <!-- parsing stops here -->
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).

The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.

Esempio 2. What get_meta_tags() returns

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

Nota: As of PHP 4.0.5, get_meta_tags() supports unquoted HTML attributes.

See also htmlentities() and urlencode().

http_build_query

(PHP 5)

http_build_query -- Generate URL-encoded query string

Description

string http_build_query ( array formdata [, string numeric_prefix] )

Generates a URL-encoded query string from the associative (or indexed) array provided. formdata may be an array or object containing properties. A formdata array may be a simple one-dimensional structure, or an array of arrays (who in turn may contain other arrays). If numeric indices are used in the base array and a numeric_prefix is provided, it will be prepended to the numeric index for elements in the base array only. This is to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

Nota: arg_separator.output is used to separate arguments.

Esempio 1. Simple usage of http_build_query()

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');
              
echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
?>

Esempio 2. http_build_query() with numerically index elements.

<?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor');
              
echo http_build_query($data);
/* Outputs:
      0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
 */
 
echo http_build_query($data, 'myvar_');
/* Outputs:
      myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor
 */
?>

Esempio 3. http_build_query() with complex arrays

<?php
$data = array('user'=>array('name'=>'Bob Smith',
                            'age'=>47,
                            'sex'=>'M',
                            'dob'=>'5/12/1956'),
              'pastimes'=>array('golf', 'opera', 'poker', 'rap'),
              'children'=>array('bobby'=>array('age'=>12,
                                               'sex'=>'M'),
                                'sally'=>array('age'=>8,
                                               'sex'=>'F')),
              'CEO');
                                               
echo http_build_query($data, 'flags_');
?>

this will output : (word wrapped for readability)

user[name]=Bob+Smith&user[age]=47&user[sex]=M&user[dob]=5%1F12%1F1956&
pastimes[0]=golf&pastimes[1]=opera&pastimes[2]=poker&pastimes[3]=rap&
children[bobby][age]=12&children[bobby][sex]=M&children[sally][age]=8&
children[sally][sex]=F&flags_0=CEO

Nota: Only the numerically indexed element in the base array "CEO" received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names.

Esempio 4. Using http_build_query() with an object

<?php
class myClass {
  var $foo;
  var $baz;
  
  function myClass() 
  {
    $this->foo = 'bar';
    $this->baz = 'boom';
  }
}

$data = new myClass();

echo http_build_query($data); // foo=bar&baz=boom

?>

See also: parse_str(), parse_url(), urlencode(), and array_walk()

parse_url

(PHP 3, PHP 4, PHP 5)

parse_url -- Parse a URL and return its components

Descrizione

array parse_url ( string url )

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Elenco dei parametri

url

The URL to parse

Valori restituiti

On seriously malformed URLs, parse_url() may return FALSE and emit a E_WARNING. Otherwise an associative array is returned, whose components may be (at least one):

  • scheme - e.g. http

  • host

  • port

  • user

  • pass

  • path

  • query - after the question mark ?

  • fragment - after the hashmark #

Esempi

Esempio 1. A parse_url() example

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));
?>

Il precedente esempio visualizzerà:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

Note

Nota: This function doesn't work with relative URLs.

rawurldecode

(PHP 3, PHP 4, PHP 5)

rawurldecode -- Decode URL-encoded strings

Description

string rawurldecode ( string str )

Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters.

Esempio 1. rawurldecode() example

<?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?>

Nota: rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.

See also rawurlencode(), urldecode() and urlencode().

rawurlencode

(PHP 3, PHP 4, PHP 5)

rawurlencode -- URL-encode according to RFC 1738

Description

string rawurlencode ( string str )

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URL's from being mangled by transmission media with character conversions (like some email systems). For example, if you want to include a password in an FTP URL:

Esempio 1. rawurlencode() example 1

<?php
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt">';
?>

Or, if you pass information in a PATH_INFO component of the URL:

Esempio 2. rawurlencode() example 2

<?php
echo '<a href="http://example.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '">';
?>

See also rawurldecode(), urldecode(), urlencode() and RFC 1738.

urldecode

(PHP 3, PHP 4, PHP 5)

urldecode -- Decodes URL-encoded string

Description

string urldecode ( string str )

Decodes any %## encoding in the given string. The decoded string is returned.

Esempio 1. urldecode() example

<?php
$a = explode('&', $QUERY_STRING);
$i = 0;
while ($i < count($a)) {
    $b = split('=', $a[$i]);
    echo 'Value for parameter ', htmlspecialchars(urldecode($b[0])),
         ' is ', htmlspecialchars(urldecode($b[1])), "<br />\n";
    $i++;
}
?>

See also urlencode(), rawurlencode() and rawurldecode().

urlencode

(PHP 3, PHP 4, PHP 5)

urlencode -- URL-encodes string

Description

string urlencode ( string str )

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs. This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page:

Esempio 1. urlencode() example

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

Note: Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2. PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

Esempio 2. urlencode() and htmlentities() example

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

See also urldecode(), htmlentities(), rawurldecode() and rawurlencode().

CLIII. Funzioni per la gestione delle variabili

Introduzione

Per maggiori informazioni sul comportamento delle variabili vedere la sezione Variabili nel capitolo Riferimento al Linguaggio del manuale.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Configurazioni per il modulo Variabili

NomeDefaultModificabileVariazioni
unserialize_callback_func""PHP_INI_ALLDisponibile dal PHP 4.2.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.

Breve descrizione dei parametri di configurazione.

unserialize_callback_func string

La funzione di callback di de-serializzazione unserialize() viene richiamata (con il parametro "nome classe" non definito) se la funzione trova una classe indefinita da da istanziare. Verrà prodotto un warning se la funzione specificata non è definita oppure se la funzione non include/implementa la classe mancante. Pertanto valorizzare questo parametro se si desidera implementare tale funzione di callback.

Vedere anche unserialize().


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
debug_zval_dump -- Dumps a string representation of an internal zend value to output
doubleval -- Alias di floatval()
empty -- Determina se una variabile è valorizzata
floatval -- Restituisce il valore di una variabile di tipo float
get_defined_vars --  Restituisce un'array contenente tutte le variabili definite
get_resource_type --  Restituisce il tipo di risorsa
gettype -- Resituisce il tipo di una variabile
import_request_variables -- Imposta la visibiltà a globale per le variabili GET/POST/Cookie
intval -- Estrae il valore intero da una variabile
is_array -- Verifica se una variabile è un array
is_bool --  Verifica se una variabile è di tipo boolean
is_callable --  Verifica se il contenuto dell'argomento può essere eseguito come funzione
is_double -- Alias di is_float()
is_float -- Verifica se una variabile è di tipo float (decimale a virgola mobile)
is_int -- Verifica se una variabile è di tipo integer
is_integer -- Alias di is_int()
is_long -- Alias di is_int()
is_null --  Verifica se la variabile è di tipo NULL
is_numeric --  Verifica se una variabile è un numero o una stringa numerica
is_object -- Verifica se una variabile è di tipo object
is_real -- Alias di is_float()
is_resource --  Verifica se una variabile è una risorsa
is_scalar --  Verifica se la variabile è di tipo scalare
is_string -- Verifica se una variabile sia una stringa
isset -- Verifica se una variabile è definita
print_r --  Stampa informazioni relative al contenuto di una variabile in formato leggibile
serialize --  Genera una versione archiviabile del valore
settype -- Definisce il tipo di una variabile
strval -- Restituisce il valore di una variabile interpretato come stringa
unserialize --  Crea un valore PHP a partire da una rappresentazione archiviata
unset -- Cancella una data variabile
var_dump -- Stampa delle informazioni relative ad una variabile
var_export -- Visualizza o restituisce una variabile in formato stringa

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5)

debug_zval_dump -- Dumps a string representation of an internal zend value to output

Descrizione

void debug_zval_dump ( mixed variable )

Dumps a string representation of an internal zend value to output.

Elenco dei parametri

variable

The variable being evaluated.

Valori restituiti

No value is returned.

Esempi

Esempio 1. debug_zval_dump() example

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

Il precedente esempio visualizzerà:

string(11) "Hello World" refcount(3)

Beware the refcount: The refcount value returned by this function is non-obvious in certain circumstances. For example, a developer might expect the above example to indicate a refcount of 2. The third reference is created when actually calling debug_zval_dump().

This behavior is further compounded when a variable is not passed to debug_zval_dump() by reference. To illustrate, consider a slightly modified version of the above example:

Esempio 2.

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump($var1); // not passed by reference, this time
?>

Il precedente esempio visualizzerà:

string(11) "Hello World" refcount(1)

Why refcount(1)? Because a copy of $var1 is being made, when the function is called.

This function becomes even more confusing when a variable with a refcount of 1 is passed (by copy/value):

Esempio 3.

<?php
$var1 = 'Hello World';

debug_zval_dump($var1);
?>

Il precedente esempio visualizzerà:

string(11) "Hello World" refcount(2)

A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?

When a variable has a single reference (as did $var1 before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

doubleval

(PHP 3, PHP 4, PHP 5)

doubleval -- Alias di floatval()

Descrizione

This function is an alias of: floatval().

Log delle modifiche

VersioneDescrizione
4.2.0 doubleval() è diventato un alias di floatval(). Prima esisteva solo doubleval().

empty

(PHP 3, PHP 4, PHP 5)

empty -- Determina se una variabile è valorizzata

Descrizione

bool empty ( mixed var )

Determina se una variabile è da considerare vuota.

Elenco dei parametri

var

Varibaile da controllare

Nota: empty() agisce solo su variabili, qualsiasi altra cosa genera un errore di parsing. In altre parole, il seguente comando non funziona: empty(trim($name)).

empty() è l'opposto di (boolean) var, tranne che non viene dato alcun warning quando la variabile non è valorizzata.

Valori restituiti

Restituisce FALSE se var non è vuota ed ha un valore diverso da zero.

I seguenti valori sono considerati vuoti:

"" (stringa vuota)
0 (0 come intero)
"0" (0 come stringa)
NULL
FALSE
array() (matrice vuota)
var $var; (una variabile dichiarata, ma senza valore in una classe)

Log delle modifiche

VersioneDescrizione
PHP 5

Dal PHP 5, oggetti privi di proprietà non sono più considerati vuoti.

PHP 4

Dal PHP 4, la stringa "0" è considerata vuota.

Esempi

Esempio 1. Semplici confronti empty() / isset().

<?php
$var = 0;

// Valutata come true perchè $var è vuota
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Valutata come vera perchè $var è impostata
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

Note

Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

floatval

(PHP 4 >= 4.2.0, PHP 5)

floatval -- Restituisce il valore di una variabile di tipo float

Descrizione

float floatval ( mixed var )

La funzione restituisce il valore di tipo float di var.

Elenco dei parametri

var

Può anche essere di tipo scalare. La funzione floatval() non può essere usata con variabili di tipo array oppure object.

Valori restituiti

Il valore in virgola mobile della variabile.

Esempi

Esempio 1. Esempio di uso di floatval()

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5)

get_defined_vars --  Restituisce un'array contenente tutte le variabili definite

Descrizione

array get_defined_vars ( void )

Questa funzione restituisce un'array multidimensionale contenente la lista di tutte le variabili definite, siano esse d'ambiente, variabili del server o definite dall'utente, visibili da dove get_defined_vars() viene eseguito.

Valori restituiti

Un'array multidimensionale contenente la lista di tutte le variabili definite.

Esempi

Esempio 1. Esempio di uso di get_defined_vars()

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// visualizza $b
print_r($arr["b"]);

/* visualizza il percorso dell'interprete PHP (se usato come CGI)
 * ad esempio /usr/local/bin/php */
echo $arr["_"];

// visualizza i parametri della linea di comando (se presenti)
print_r($arr["argv"]);

// visualizza tutte le variabili del server
print_r($arr["_SERVER"]);

// visualizza tutte le chiavi disponibili nell'array delle variabili
print_r(array_keys(get_defined_vars()));
?>

Log delle modifiche

VersioneDescrizione
5.0.0 La variabile $GLOBALS viene compresa nella matrice restituita.

get_resource_type

(PHP 4 >= 4.0.2, PHP 5)

get_resource_type --  Restituisce il tipo di risorsa

Descrizione

string get_resource_type ( resource handle )

Questa funzione restituisce il tipo della risorsa data.

Elenco dei parametri

handle

Risorsa da valutare.

Valori restituiti

Se il parametro handle è una risorsa, questa funzione restituirà una stringa indicante il tipo di risorsa. Se il tipo non è identificato dalla funzione, il valore restituito sarà Unknown.

La funzione restituisce FALSE e genera un errore se handle non è di tipo resource.

Esempi

Esempio 1. Esempio di uso di get_resource_type()

<?php
// visualizza: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// visualizza: file
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// visualizza: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>

gettype

(PHP 3, PHP 4, PHP 5)

gettype -- Resituisce il tipo di una variabile

Descrizione

string gettype ( mixed var )

Restituisce il tipo della variabile PHP var.

Avvertimento

Non utilizzare gettype() per testare certi tipi di variabili poichè la stringa restistuita potrebbe variare nelle versioni future. Inoltre questa funzione è lenta dato che richiede confronti tra stringhe

Piuttosto utilizzare le funzioni is_*.

La stringa restituita può assumere i seguenti valori:

  • "boolean" (dalla versione 4 di PHP)

  • "integer"

  • "double" (per ragioni storiche viene restituito "double" in caso di variabile di tipo float, e non semplicemente "float")

  • "string"

  • "array"

  • "object"

  • "resource" (dalla versione 4 di PHP)

  • "NULL" (dalla versione 4 di PHP)

  • "user function" (soltanto in PHP 3, deprecated)

  • "unknown type"

Nella versione 4 di PHP si dovrebbe applicare alle funzioni function_exists() o method_exists() al posto del precedente gettype().

Vedere anche settype(), is_array(), is_bool(), is_float(), is_int(), is_null(), is_numeric(), is_object(), is_resource(), is_scalar() e is_string().

import_request_variables

(PHP 4 >= 4.1.0, PHP 5)

import_request_variables -- Imposta la visibiltà a globale per le variabili GET/POST/Cookie

Descrizione

bool import_request_variables ( string tipo [, string prefisso] )

Imposta la visibilità delle variabili GET/POST/Cookie a globale. Ciò risulta utile nei casi in cui si è disabilitato register_globals, ma si vuole avere per qualche variabile una visibilità globale.

Tramite il parametro tipo, si può specificare quale variabile rendere visibile. I valori ammessi sono i caratteri 'G', 'P' e 'C' rispettivamente per GET, POST e Cookie. Questi caratteri non distinguono tra maiuscole e minuscole pertanto si può usare qualsiasi combinazione di 'g', 'p' e 'c'. POST include le informazioni dei file caricati. Occorre prestare attenzione all'ordine delle lettere, ad esempio usando "gp", le variabili POST sovrascrivono le variabili GET con il medesimo nome. Qualsiasi altra lettera al di fuori di GPC sarà scartata.

Il parametro prefisso viene utilizzato come prefisso nel nome della variabile, ovvero viene anteposto ai nomi di tutte le variabili portate a visibilità globale. Quindi, se si ha una variabile GET chiamata "userid", e si è passato il prefisso "pref_", si otterrà una variabile globale chiamata $pref_userid.

Se si è interessati a rendere visibili altre variabili, come ad esempio SERVER, si consideri l'utilizzo della funzione extract().

Nota: Sebbene il parametro prefisso sia opzionale, si ottiene un errore di livello E_NOTICE se non si specifica il prefisso, o si indica una stringa vuota. Ciò può comportare dei rischi di sicurezza. Gli errori di livello "notice" non sono visualizzati con il parametro error reporting impostato al valore standard.

<?php
// Questo esempio rende visibili le variabili GET e POST 
// con il prefisso "rvar_" 
import_request_variables("gP", "rvar_");

echo $rvar_foo;
?>

Vedere anche $_REQUEST, register_globals, Variabili predefinite e extract().

intval

(PHP 3, PHP 4, PHP 5)

intval -- Estrae il valore intero da una variabile

Descrizione

int intval ( mixed var [, int base] )

Estrae il valore intero di var, utilizzando la base definita a parametro per la conversione. (La base vale 10 di default).

Elenco dei parametri

var

Valore scalare da convertire in intero

base

Base per la conversione (il default è 10)

Valori restituiti

Il valore intero di var se riesce, oppure 0 in caso di errore. Le matrici e gli oggetti vuoti restituiscono 0, la matrici e gli oggetti pieni restituiscono 1.

Il valore massimo dipende dal sistema. Nei sistemi a 32 bit si ha come valore per il caso di intero con segno il range da -2147483648 a 2147483647. Così, ad esempio, su tali sistemi, la riga intval('1000000000000') restituirà 2147483647. Il massimo valore per un intero con segno sui sistemi a 64 bit è 9223372036854775807.

Le stringhe probabilmente restituiranno 0, sebbene il valore restituito dipenda dal primo carattere a sinistra della stringa. Si utilizzano le comuni di integer casting .

Esempi

Esempio 1. Esempi di uso di intval()

I seguenti esempi sono basati su un sistema a 32 bit.

<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
?>

Note

Nota: Il parametro base non ha influenza a meno che il parametro var non sia una stringa.

is_array

(PHP 3, PHP 4, PHP 5)

is_array -- Verifica se una variabile è un array

Descrizione

bool is_array ( mixed var )

Verifica se il valore dato è un array.

Elenco dei parametri

var

Variabile da verificare.

Valori restituiti

Restituisce TRUE se var è una matrice, FALSE in caso contrario.

Esempi

Esempio 1. Verifica se una variabile è un array

<?php
$yes = array('this', 'is', 'an array');
 
echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";
 
$no = 'this is a string';
 
echo is_array($no) ? 'Array' : 'not an Array';
?>

Il precedente esempio visualizzerà:

Array
not an Array

is_bool

(PHP 4, PHP 5)

is_bool --  Verifica se una variabile è di tipo boolean

Descrizione

bool is_bool ( mixed var )

Verifica se la variabile data sia di tipo boolean

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se var è di tipo boolean, FALSE in caso contrario.

Esempi

Esempio 1. Esempi di is_bool()

<?php
$a = false;
$b = 0;

// Poichè $a è booleana, questa è vera
if (is_bool($a)) {
    echo "Yes, this is a boolean";
}

// Poichè $b non è booleana, questa non è vera
if (is_bool($b)) {
    echo "Yes, this is a boolean";
}
?>

is_callable

(PHP 4 >= 4.0.6, PHP 5)

is_callable --  Verifica se il contenuto dell'argomento può essere eseguito come funzione

Descrizione

bool is_callable ( mixed var [, bool syntax_only [, string &callable_name]] )

Verifica che il contenuto di una funzione possa essere richiamato come una funzione. Questa verifica può essere eseguita su una semplice variabile contenente il nome di una funzione valida, oppure su un array contenente il nome di un oggetto ed il nome di una funzione

Il parametro var può essere sia il nome di una funzione sia un oggetto ed il nome del metodo nell'oggetto, tipo
array( $SomeObject, 'MethodName' )

Se il parametro syntax_only è impostato a TRUE la funzione eseguirà un controllo sulla validità del parametro var. La funzione scarterà variabili non stringhe o che non hanno la struttura per essere callback validi. L'unica struttura valida presuppone di avere solo 2 righe: una stringa con il nome dell'oggetto, una seconda riga con il nome del metodo.

Il terzo parametro callable_name contiene il "callable name". Nell'esempio che segue contiene "someClass:someMethod". Si noti che, nonostante someClass::SomeMethod() implichi il richiamo ad un metodo statico, questo non è il caso.

<?php
//  Come verificare se una variabile può essere eseguita
//  come funzione..

//
//  Semplice variabile contenente una funzione
//

function unaFunzione() 
{
}

$functionVariable = 'unaFunzione';

var_dump(is_callable( $functionVariable, false, $callable_name ));  // bool(true)

echo $callable_name, "\n";  // unaFunzione

//
//  Array contenente un metodo
//

class unaClasse {

  function unMetodo() 
  {
  }

}

$anObject = new unaClasse();
$methodVariable = array($anObject, 'unMetodo' );
var_dump(is_callable($methodVariable, true, $callable_name ));  //  bool(true)
echo $callable_name, "\n";  //  unaClasse:unMetodo
?>

is_double

(PHP 3, PHP 4, PHP 5)

is_double -- Alias di is_float()

Descrizione

This function is an alias of: is_float().

is_float

(PHP 3, PHP 4, PHP 5)

is_float -- Verifica se una variabile è di tipo float (decimale a virgola mobile)

Descrizione

bool is_float ( mixed var )

Verifica se una variabile è di tipo float (decimale a virgola mobile).

Nota: Per verificare se una variabile è un numero oppure una stringa numerica (come le variabili dei form, che sono sempre stringhe) occorre usare la funzione is_numeric().

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Questa funzione restituisce TRUE se var è di tipo float, FALSE in caso contrario.

is_int

(PHP 3, PHP 4, PHP 5)

is_int -- Verifica se una variabile è di tipo integer

Descrizione

bool is_int ( mixed var )

Verifica che la variabile data sia di tipo integer

Nota: Per verificare se una variabile è un numero oppure una stringa numerica (come le variabili dei form, che sono sempre stringhe) occorre usare la funzione is_numeric().

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se var è di tipo integer, FALSE in caso contrario.

is_integer

(PHP 3, PHP 4, PHP 5)

is_integer -- Alias di is_int()

Descrizione

This function is an alias of: is_int().

is_long

(PHP 3, PHP 4, PHP 5)

is_long -- Alias di is_int()

Descrizione

This function is an alias of: is_int().

is_null

(PHP 4 >= 4.0.4, PHP 5)

is_null --  Verifica se la variabile è di tipo NULL

Descrizione

bool is_null ( mixed var )

Verifica che la variabile data sia di tipo NULL

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se var è di tipo null, FALSE in caso contrario.

is_numeric

(PHP 4, PHP 5)

is_numeric --  Verifica se una variabile è un numero o una stringa numerica

Descrizione

bool is_numeric ( mixed var )

Verifica se una variabile è un numero o una stringa numerica.

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se var è un numero o una stringa numerica, FALSE in caso contrario.

is_object

(PHP 3, PHP 4, PHP 5)

is_object -- Verifica se una variabile è di tipo object

Descrizione

bool is_object ( mixed var )

Verifica se una variabile è di tipo object.

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se var è un di tipo object, FALSE in caso contrario.

is_real

(PHP 3, PHP 4, PHP 5)

is_real -- Alias di is_float()

Descrizione

This function is an alias of: is_float().

is_resource

(PHP 4, PHP 5)

is_resource --  Verifica se una variabile è una risorsa

Descrizione

bool is_resource ( mixed var )

Verifica se una data variabile sia di tipo risorsa.

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se la variabile individuata dal parametro var è di tipo resource, altrimenti restituisce FALSE.

Esempi

Esempio 1. Esempio di utilizzo di is_resource()

<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Can\'t connect : ' . mysql_error());
}

?>

is_scalar

(PHP 4 >= 4.0.5, PHP 5)

is_scalar --  Verifica se la variabile è di tipo scalare

Descrizione

bool is_scalar ( mixed var )

Verifica se la data variabile sia di tipo scalare

Le variabili scalari sono quelle contenenti valori di tipo integer, float, string oppure boolean. I tipi array, object e resource non sono scalari.

Nota: La funzione is_scalar() non considera il tipo resource come valore scalare, dato che il tipo resource è una tipologia di dato astratto che attualmente si basa su interi. Tuttavia non ci si può basare su questo tipo di implementazione, in futuro potrebbe cambiare.

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se la variabile indicata dal parametro var è di tipo scalare, in caso contrario restituisce FALSE.

Esempi

Esempio 1. Esempio di uso di is_scalar()

<?php
function show_var($var) 
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins)

?>

Il precedente esempio visualizzerà:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

is_string

(PHP 3, PHP 4, PHP 5)

is_string -- Verifica se una variabile sia una stringa

Descrizione

bool is_string ( mixed var )

Verifica se una data variabile sia una stringa.

Elenco dei parametri

var

La variabile da valutare.

Valori restituiti

Restituisce TRUE se var è di tipo string, FALSE in caso contrario.

isset

(PHP 3, PHP 4, PHP 5)

isset -- Verifica se una variabile è definita

Descrizione

bool isset ( mixed variabile [, ...] )

Restituisce TRUE se la variabile esiste; FALSE in caso contrario.

Se una variabile è stata cancellata con unset(), non potrà essere impostata. La funzione isset() restituirà FALSE se viene utilizzata per testare una variabile valorizzata a NULL. Inoltre occorre notare che il byte NULL ("\0") non equivale alla costante PHP NULL.

Attenzione: La funzione isset() lavora soltanto con variabili, il passaggio di qualsiasi altro tipo di parametro genera un errore di parsing. Per verificare se le costanti sono definite utilizzare la funzione defined().

<?php

$var = '';

// Questo test sarà TRUE pertanto sarà visualizzato il testo.
if (isset($var)) {
    echo "Questa variabile è valorizzata, pertanto scrivo.";
}

// Nel prossimo esempio useremo var_dump per visualizzare
// il valore restituito da isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>

Questo esempio utilizza gli elementi di un array:

<?php  

$a = array ('test' => 1, 'hello' => NULL);

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// La chiave 'hello' vale NULL pertanto viene considerata non impostata.
// Se si desidera verificare l'esistenza di chiavi con valore NULL, usare:
var_dump(array_key_exists('hello', $a)); // TRUE

?>

Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

Vedere anche empty(), unset(), defined(), la tabella di comparazione dei tipi, array_key_exists() e l'operatore di controllo degli errori @.

print_r

(PHP 4, PHP 5)

print_r --  Stampa informazioni relative al contenuto di una variabile in formato leggibile

Descrizione

bool print_r ( mixed expression [, bool return] )

Nota: Il parametro return è stato aggiunto in PHP 4.3.0.

Questa funzione stampa delle informazioni sul contenuto di una variabile in un formato facilmente leggibile. Se la variabile contiene una stringa, un intero o un numero decimale, il valore stesso viene visualizzato. Se la variabile contiene un array i valori vengono visualizzati in un formato che evidenzia le chiavi ed i relativi elementi. Una notazione simile viene utilizzata per gli oggetti. Le funzioni print_r() e var_export(), a differenza di var_dump(), visualizzano le proprietà protette e private degli oggetti di PHP 5.

Occorre ricordarsi che print_r() posiziona il puntatore dell'array alla fine. Pertanto utilizzare reset() per riportarsi all'inizio.

<pre>
<?php
    $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z'));
    print_r ($a);
?>
</pre>

Il precedente esempio visualizzerà:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Se si desidera catturare l'output di print_r(), occorre utilizzare il parametro return. Se questo viene impostato a TRUE, print_r() restituirà l'output anzichè visualizzarlo (come accade per default).

Esempio 1. Esempio dell'uso di return

<?php 
    $b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z')); 
    $results = print_r($b, true); //$results ora contiene l'output di print_r 
?>

Nota: Se occorre catturare l'output di print_r() con versioni di PHP precedenti alla 4.3.0, occorre utlizzare le funzioni di controllo dell'output.

Nota: Questa funzione continua all'infinito se riceve come parametro un vettore o un oggetto contenente un riferimento diretto od indiretto a se stesso oppure contenente ulteriori vettori o oggetti che a loro volta referenziano il padre o se stessi. Un caso evidente è print_r($GLOBALS), in quanto $GLOBALS è a sua volta una variabile globale e in quanto tale contiene una referenza a se stessa.

Vedere anche ob_start(), var_dump() e var_export().

serialize

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

serialize --  Genera una versione archiviabile del valore

Descrizione

string serialize ( mixed value )

La funzione serialize() restituisce una stringa contenente un flusso di bytes rappresentante value che possa essere archiviato ovunque.

Questo può essere utile per archiviare o passare valori senza perdere il tipo e la struttura.

Per ottenere il valore dalla stringa serializzata, utilizzare la funzione unserialize(). La funzione serialize() gestisce tutti i tipi di variabili tranne il tipo resource. Possono essere elaborati da serialize() array che contengano riferimenti a se stessi. Saranno archiviati anche i riferimenti interni agli array e ai tipi object passati a serialize()

Quando si esegue la serializzazione di oggetti, il PHP cerca di eseguire la funzione __sleep() prima di cominciare la serializzazione. Questo permette all'oggetto di eseguire le ultime operazioni di chiusura prima di essere serializzato. Analogamente quando l'oggetto viene ripristinato la funzione unserialize() richiama la funzione membro __wakeup().

Nota: Questa funzione non gira correttamente sino alla versione 4.0.7.

Nota: Nella versione 3 di PHP si serializzano le proprietà dell'oggetto, ma non i metodi. Nella versione 4 questa limitazione è stata rimossa, pertanto possono essere recuperati sia le proprietà sia i metodi. Per maggiori informazioni vedere la sezione Serializzare oggetti in Oggetti e Classi.

Non è possibile serializzare gli oggetti predefiniti di PHP.

Esempio 1. Esempio di serialize()

<?php
// L'array multi-dimensionale $session_data contiene le informazioni della sessione
// per l'utente. Si userà serialize() per memorizzare le informazioni
// all'interno di un database alla fine della richiesta..

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $PHP_AUTH_USER);
if (!odbc_execute($stmt, &$sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, &$sqldata)) {
    /* Qualcosa è andato storto */
    }
}
?>

Vedere anche: unserialize().

settype

(PHP 3, PHP 4, PHP 5)

settype -- Definisce il tipo di una variabile

Descrizione

bool settype ( mixed &var, string type )

Setta il tipo della variabile var a type.

Valori possibili di type sono:

  • "boolean" (oppure, da PHP 4.2.0, "bool")

  • "integer" (uppure, da PHP 4.2.0, "int")

  • "float" (soltanto a partire dalla versione 4.2.0 di PHP, per le versioni precedenti usare "double", deprecated)

  • "string"

  • "array"

  • "object"

  • "null" (dalla versione PHP 4.2.0)

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. Esempio di utilizzo di settype()

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo ora è 5   (integer)
settype($bar, "string");  // $bar ora è "1" (string)
?>

Vedere anche gettype(), Casting del tipo e Manipolazione del tipo.

strval

(PHP 3, PHP 4, PHP 5)

strval -- Restituisce il valore di una variabile interpretato come stringa

Descrizione

string strval ( mixed var )

Restituisce il valore di var interpretato come stringa. Per maggiori informazioni sulla conversione a stringa, vedere la documentazione relativa alle variabili di tipo string.

var può essere una qualsiasi variabile scalare. Non è possibile usare strval() con array o oggetti.

Vedere anche floatval(), intval(), settype() e Manipolazione del tipo.

unserialize

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

unserialize --  Crea un valore PHP a partire da una rappresentazione archiviata

Descrizione

mixed unserialize ( string str )

La funzione unserialize() prende il formato serializzato di una variabile (vedere serialize()) e la riporta a valore PHP. La funzione restituisce il valore ottenuto, che può essere di tipo boolean, integer, float, string, array oppure object. Nel caso in cui la stringa passata non sia deserializzabile la funzione restituisce FALSE e genera un E_NOTICE.

Avvertimento

FALSE è restituito sia in caso di errore e sia in caso di de-serializzazione del valore FALSE. Questo caso particolare può essere intercettato confrontando str con serialize(false) o rilevando il E_NOTICE generato.

Direttiva unserialize_callback_func: E' possibile impostare una funzione di callback che possa essere richiamata se, durante la fase di deserializzazione, occorre istanziare una classe indefinita. (per evitare di ottenere un tipo object incompleto "__PHP_Incomplete_Class".) Per definire il parametro 'unserialize_callback_func' si può agire sul php.ini, o usare ini_set() oppure con .htaccess. Verrà utilizzata questa funzione ogni volta che occorre istanziare una classe indefinita. Per disabilitare questa opzione, lasciare vuota questa impostazione. Attenzione che la direttiva unserialize_callback_func è disponibile dalla versione 4.2.0 di PHP.

Se la variabile da ripristinare è un oggetto, dopo avere ricostruito l'oggetto, il PHP cercherà di eseguire la funzione membro __wakeup() (se esiste).

Esempio 1. Esempio di unserialize_callback_func.

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// direttiva unserialize_callback_func disponibile dalla versione 4.2.0
ini_set('unserialize_callback_func', 'mycallback'); // imposta la funzione di callback

function mycallback($classname)
{
    // semplicemente include un file contenente la definizione della classe
    // la variabile $classname indica di quale classe occorre la definizione
}
?>

Nota: Nella versione 3 di PHP, i metodi non erano preservati durante la fase di deserializzazione di un oggetto. In PHP 4 questo limite è stato superato e possono essere recuperati sia metodi sia proprietà. Per maggiori informazioni vedere la sezione Serializzare oggetti in Classi e oggetti

Esempio 2. Esempio di uso di unserialize()

<?php
// In quest esempio si usa unserialize() per caricare i dati di una sessione da un database
// alla variabile $session_data. Questo esempio è complementare a quello illustrato
// nella funzione <function>serialize</function>.

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array ($PHP_AUTH_USER);
if (!odbc_execute($stmt, &$sqldata) || !odbc_fetch_into($stmt, &$tmp)) {
    // se odbc_execute o odbc_fetch_into hanno un errore si predispone un array vuoto
    $session_data = array();
} else {
    // ora abbiamo i dati serializzati in $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
       // qualcosa è andato storto, si predispone un array vuoto
       $session_data = array();
    }
}
?>

Vedere anche: serialize().

unset

(PHP 3, PHP 4, PHP 5)

unset -- Cancella una data variabile

Descrizione

void unset ( mixed var [, mixed var [, mixed ...]] )

unset() distrugge la variabile specificata. Occorre notare che in PHP 3 la funzione unset() restituiva sempre TRUE (in realtà era il valore 1). In PHP 4, invece, la funzione unset() non è più una vera funzione, ora è una istruzione. In questa veste non ritorna alcun valore, e cercare di ottenere un valore dalla funzione unset() produce un errore di parsing.

Esempio 1. Esempio di unset()

<?php
// Distrugge una singola variabile
unset($foo);

// distrugge un singolo elemento di un array
unset($bar['quux']);

// distrugge più di una variabile
unset($foo1, $foo2, $foo3);
?>

Il comportamento di unset() all'interno di una funzione può variare in funzione del tipo di variabile che si intende distruggere.

Se si applica unset() ad una variabile globale all'interno di una funzione, sarà distrutta solo la variabile locale. Nell'ambiente chiamante, la variabile manterrà il medesimo valore che aveva prima dell'uso di unset().

<?php
function destroy_foo()
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

Il precedente esempio visualizzerà:

bar

Nel caso di una variabile PASSATA PER RIFERIMENTO ad una funzione, l'uso della funzione unset() distrugge solo la copia locale della variabile. Nell'ambiente chiamante, la variabile manterrà il medesimo valore che aveva prima dell'uso di unset().

<?php
function foo(&$bar) 
{
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

Il precedente esempio visualizzerà:

something
something

Se si usa unset() su una variabile statica all'interno di una funzione, unset() cancella la variabile e tutti i suoi riferimenti.

<?php
function foo() 
{
    static $a;
    $a++;
    echo "$a\n";

    unset($a);
}

foo();
foo();
foo();
?>

Il precedente esempio visualizzerà:

1
2
3

Se si desidera cancellare una variabile globale dall'interno di una funzione, occorre usare unset() sull'array $GLOBALS nel seguente modo:

<?php
function foo() 
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

Vedere anche isset() e empty().

var_dump

(PHP 3 >= 3.0.5, PHP 4, PHP 5)

var_dump -- Stampa delle informazioni relative ad una variabile

Descrizione

void var_dump ( mixed expression [, mixed expression [, ...]] )

Questa funzione visualizza delle informazioni strutturate riguardanti una espressione, tra cui il suo tipo e il suo valore. Gli array e gli oggetti sono attraversati in maniera ricorsiva e i valori indentati per evidenziare la struttura.

In PHP 5 soltanto le proprietà pubbliche, private e protette di un oggetto possono essere restituite.

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.

Elenco dei parametri

expression

La variabile che si desidera visualizzare.

Valori restituiti

No value is returned.

Esempi

Esempio 1. var_dump() example

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

Il precedente esempio visualizzerà:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

Il precedente esempio visualizzerà:

float(3.1)
bool(true)

Vedere anche:

var_export()
print_r()

var_export

(PHP 4 >= 4.2.0, PHP 5)

var_export -- Visualizza o restituisce una variabile in formato stringa

Descrizione

mixed var_export ( mixed expression [, bool return] )

La funzione var_export() restituisce informazioni strutturate sulla data variabile. E' simile a var_dump() con una differenza: il valore restituito è codice PHP.

Elenco dei parametri

expression

La variabile che si desidera esportare.

return

Se utilizzato ed impostato a TRUE, la funzione var_export() restituisce la rappresentazione della variabile anzichè visualizzarla.

Valori restituiti

Restituisce la rappresentazione della variabile quando il parametro return viene impostato a TRUE. Altrimenti la funzione restituisce NULL.

Esempi

Esempio 1. Esempio di utilizzo di var_export()

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

Il precedente esempio visualizzerà:

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php
$b = 3.1;
$v = var_export($b, true);
echo $v;
?>

Il precedente esempio visualizzerà:

3.1

Note

Nota: Le variabili di tipo resource, le matrici e gli oggetti contenenti oggetti non possono essere esportati da questa funzione.

Vedere anche:

var_dump()
print_r()

CLIV. Verisign Payflow Pro Functions

Introduzione

This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/products-services/payment-processing/online-payment/payflow-pro/index.html).

When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.

These functions were added in PHP 4.0.2.

Nota: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Nota: 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.


Requisiti

You will require the appropriate SDK for your platform, which may be downloaded from within the manager interface once you have registered.

Once you have downloaded the SDK you should copy the files from the lib directory of the distribution. Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to /usr/local/lib.

Alternatively, you can extract the tarball from Verisign in one location, and reference it during build configuration with the --with-pfpro[=DIR] option:

Esempio 1. Explicit Configuration

tar -zxf pfpro_sunsparc.tar.gz -C /usr/local/

./configure --with-pfpro=/usr/local/verisign/payflowpro/sunsparc

Nota: The last portion of the path specified in the example above, in this case sunsparc, will vary based on which architecture your Verisign SDK was built for.


Installazione

These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.

Avvertimento

If you are planing to use this extension along with the OpenSSL extension or with ModSSL, you should compile this extension as shared: --with-pfpro=shared,/usr/local.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Verisign Payflow Pro configuration options

NameDefaultChangeableChangelog
pfpro.defaulthost/PFPRO_VERSION < 3 "test.signio.com"PHP_INI_ALL 
pfpro.defaulthost"test-payflow.verisign.com"PHP_INI_ALLAvailable since PHP 4.0.2.
pfpro.defaultport"443"PHP_INI_ALLAvailable since PHP 4.0.2.
pfpro.defaulttimeout"30"PHP_INI_ALLAvailable since PHP 4.0.2.
pfpro.proxyaddress""PHP_INI_ALLAvailable since PHP 4.0.2.
pfpro.proxyport""PHP_INI_ALLAvailable since PHP 4.0.2.
pfpro.proxylogon""PHP_INI_ALLAvailable since PHP 4.0.2.
pfpro.proxypassword""PHP_INI_ALLAvailable since PHP 4.0.2.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
pfpro_cleanup -- Shuts down the Payflow Pro library
pfpro_init -- Initialises the Payflow Pro library
pfpro_process_raw -- Process a raw transaction with Payflow Pro
pfpro_process -- Process a transaction with Payflow Pro
pfpro_version -- Returns the version of the Payflow Pro software

pfpro_cleanup

(PHP 4 >= 4.0.2, PHP 5)

pfpro_cleanup -- Shuts down the Payflow Pro library

Description

bool pfpro_cleanup ( void )

pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.

See also pfpro_init().

pfpro_init

(PHP 4 >= 4.0.2, PHP 5)

pfpro_init -- Initialises the Payflow Pro library

Description

bool pfpro_init ( void )

pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.

See also pfpro_cleanup().

pfpro_process_raw

(PHP 4 >= 4.0.2, PHP 5)

pfpro_process_raw -- Process a raw transaction with Payflow Pro

Description

string pfpro_process_raw ( string parameters [, string address [, int port [, int timeout [, string proxy_address [, int proxy_port [, string proxy_logon [, string proxy_password]]]]]]] )

Returns: A string containing the response.

pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.

The first parameter in this case is a string containing the raw transaction request. All other parameters are the same as with pfpro_process(). The return value is a string containing the raw response.

Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.

Esempio 1. Payflow Pro raw example

<?php

pfpro_init();

$response = pfpro_process_raw("USER=mylogin&PWD[5]=m&ndy&PARTNER=VeriSign&TRXTYPE=S&TENDER=C&AMT=1.50&ACCT=4111111111111111&EXPDATE=0904");

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign raw response was " . $response;

pfpro_cleanup();

?>

See also pfpro_process().

pfpro_process

(PHP 4 >= 4.0.2, PHP 5)

pfpro_process -- Process a transaction with Payflow Pro

Description

array pfpro_process ( array parameters [, string address [, int port [, int timeout [, string proxy_address [, int proxy_port [, string proxy_logon [, string proxy_password]]]]]]] )

Returns: An associative array containing the response

pfpro_process() processes a transaction with Payflow Pro. The first parameter is an associative array containing keys and values that will be encoded and passed to the processor.

The second parameter is optional and specifies the host to connect to. By default this is "test.signio.com", so you will certainly want to change this to "connect.signio.com" in order to process live transactions.

The third parameter specifies the port to connect on. It defaults to 443, the standard SSL port.

The fourth parameter specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in the event of DNS or network problems.

The fifth parameter, if required, specifies the hostname of your SSL proxy. The sixth parameter specifies the port to use.

The seventh and eighth parameters specify the logon identity and password to use on the proxy.

The function returns an associative array of the keys and values in the response.

Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Esempio 1. Payflow Pro example

<?php

pfpro_init();

$transaction = array('USER'    => 'mylogin',
                     'PWD'     => 'mypassword',
                     'PARTNER' => 'VeriSign',
                     'TRXTYPE' => 'S',
                     'TENDER'  => 'C',
                     'AMT'     => 1.50,
                     'ACCT'    => '4111111111111111',
                     'EXPDATE' => '0904'
                    );

$response = pfpro_process($transaction);

if (!$response) {
  die("Couldn't establish link to Verisign.\n");
}

echo "Verisign response code was " . $response['RESULT'];
echo ", which means: " . $response['RESPMSG'] . "\n";

echo "\nThe transaction request: ";
print_r($transaction);

echo "\nThe response: ";
print_r($response);

pfpro_cleanup();

?>

pfpro_version

(PHP 4 >= 4.0.2, PHP 5)

pfpro_version -- Returns the version of the Payflow Pro software

Description

string pfpro_version ( void )

pfpro_version() returns the version string of the Payflow Pro library. At the time of writing, this was L211.

CLV. Funzioni vpopmail

Introduzione

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 dalla versione 4.3.0 di PHP ed ora è disponibile sotto PECL.


Installazione

In PHP 4, queste funzioni sono disponibili soltanto se il PHP viene configurato con --with-vpopmail[=DIR].

Sommario
vpopmail_add_alias_domain_ex -- Aggiunge un alias ad un esistente dominio virtuale
vpopmail_add_alias_domain -- Aggiunge un alias per un dominio virtuale
vpopmail_add_domain_ex -- Aggiunge un nuovo dominio virtuale
vpopmail_add_domain -- Aggiunge un nuovo dominio virtuale
vpopmail_add_user -- Aggiunge un nuovo utente al dominio virtuale specificato
vpopmail_alias_add -- Inserisce un alias virtuale
vpopmail_alias_del_domain -- Elimina tutti gli alias virtuali di un dominio
vpopmail_alias_del -- Elimina tutti gli alias virtuali di un utente
vpopmail_alias_get_all -- Riceve tutte le linee di un alias per un dominio
vpopmail_alias_get -- Riceve tutte le linee di un alias per un dominio
vpopmail_auth_user -- Tenta di validare un nome utente/dominio/password
vpopmail_del_domain_ex -- Elimina un dominio virtuale
vpopmail_del_domain -- Elimina un dominio virtuale
vpopmail_del_user -- Elimina un utente da un dominio virtuale
vpopmail_error -- Riceve il messaggio testuale dell'ultimo errore di vpopmail
vpopmail_passwd -- Cambia la password virtuale ad un utente
vpopmail_set_user_quota -- Imposta la quota ad un utente virtuale

vpopmail_add_alias_domain_ex

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_alias_domain_ex -- Aggiunge un alias ad un esistente dominio virtuale

Descrizione

bool vpopmail_add_alias_domain_ex ( string olddomain, string newdomain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_add_alias_domain

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_alias_domain -- Aggiunge un alias per un dominio virtuale

Descrizione

bool vpopmail_add_alias_domain ( string domain, string aliasdomain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_add_domain_ex

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_domain_ex -- Aggiunge un nuovo dominio virtuale

Descrizione

bool vpopmail_add_domain_ex ( string domain, string passwd [, string quota [, string bounce [, bool apop]]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_add_domain

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_domain -- Aggiunge un nuovo dominio virtuale

Descrizione

bool vpopmail_add_domain ( string domain, string dir, int uid, int gid )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_add_user

(4.0.5 - 4.2.3 only, PECL)

vpopmail_add_user -- Aggiunge un nuovo utente al dominio virtuale specificato

Descrizione

bool vpopmail_add_user ( string user, string domain, string password [, string gecos [, bool apop]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_alias_add

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_add -- Inserisce un alias virtuale

Descrizione

bool vpopmail_alias_add ( string user, string domain, string alias )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_alias_del_domain

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_del_domain -- Elimina tutti gli alias virtuali di un dominio

Descrizione

bool vpopmail_alias_del_domain ( string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_alias_del

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_del -- Elimina tutti gli alias virtuali di un utente

Descrizione

bool vpopmail_alias_del ( string user, string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_alias_get_all

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_get_all -- Riceve tutte le linee di un alias per un dominio

Descrizione

array vpopmail_alias_get_all ( string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_alias_get

(4.1.0 - 4.2.3 only, PECL)

vpopmail_alias_get -- Riceve tutte le linee di un alias per un dominio

Descrizione

array vpopmail_alias_get ( string alias, string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_auth_user

(4.0.5 - 4.2.3 only, PECL)

vpopmail_auth_user -- Tenta di validare un nome utente/dominio/password

Descrizione

bool vpopmail_auth_user ( string user, string domain, string password [, string apop] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_del_domain_ex

(4.0.5 - 4.2.3 only, PECL)

vpopmail_del_domain_ex -- Elimina un dominio virtuale

Descrizione

bool vpopmail_del_domain_ex ( string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_del_domain

(4.0.5 - 4.2.3 only, PECL)

vpopmail_del_domain -- Elimina un dominio virtuale

Descrizione

bool vpopmail_del_domain ( string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_del_user

(4.0.5 - 4.2.3 only, PECL)

vpopmail_del_user -- Elimina un utente da un dominio virtuale

Descrizione

bool vpopmail_del_user ( string user, string domain )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_error

(4.0.5 - 4.2.3 only, PECL)

vpopmail_error -- Riceve il messaggio testuale dell'ultimo errore di vpopmail

Descrizione

string vpopmail_error ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_passwd

(4.0.5 - 4.2.3 only, PECL)

vpopmail_passwd -- Cambia la password virtuale ad un utente

Descrizione

bool vpopmail_passwd ( string user, string domain, string password [, bool apop] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

vpopmail_set_user_quota

(4.0.5 - 4.2.3 only, PECL)

vpopmail_set_user_quota -- Imposta la quota ad un utente virtuale

Descrizione

bool vpopmail_set_user_quota ( string user, string domain, string quota )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

CLVI. Funzioni W32api

Introduzione

Questa è una generica API verso le DLL. In origine fu scritta per consentire l'accesso alle API Win32 dal PHP, sebbene si possa anche accedere a funzioni esportate da altre DLL.

Attualmente i tipi di dati supportati dal modulo sono i generici tipi PHP (strings, booleans, floats, integers e null) e i tipi definiti dall'utente tramite w32api_deftype().

Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.

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.


Requisiti

Questo modulo gira solo su sistemi Windows.


Installazione

Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questo modulo definisce un solo tipo di risorsa utilizzata per i tipi di dati definiti dall'utente. Il nome i questa risorsa è "dynaparm".


Costanti predefinite

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.

DC_MICROSOFT (integer)

DC_BORLAND (integer)

DC_CALL_CDECL (integer)

DC_CALL_STD (integer)

DC_RETVAL_MATH4 (integer)

DC_RETVAL_MATH8 (integer)

DC_CALL_STD_BO (integer)

DC_CALL_STD_MS (integer)

DC_CALL_STD_M8 (integer)

DC_FLAG_ARGPTR (integer)


Esempi

Nel seguente esempio si ottiene da quanto tempo il sistema è attivo ed il risultato viene visualizzato in una finestra.

Esempio 1. Ottenere il tempo di attività e visualizzarlo in una finestra

<?php
// Definizione delle costanti richieste, dati ottenuti da
// Visual Studio/Tools/Winapi/WIN32API.txt
define("MB_OK", 0);
 
// Carico il modulo
dl("php_w32api.dll");
 
// Registrazione della funzione GetTickCount da kernel32.dll
w32api_register_function("kernel32.dll",
                         "GetTickCount",
                         "long");
 
// Registrazione della funzione MessageBoxA da User32.dll
w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");
 
// Ottiene il dato cercato
$ticks = GetTickCount();
 
// Converte in formato umano
$secs  = floor($ticks / 1000);
$mins  = floor($secs / 60);
$hours = floor($mins / 60);
 
$str = sprintf("You have been using your computer for:" .
                "\r\n %d Milliseconds, or \r\n %d Seconds" .
                "or \r\n %d mins or\r\n %d hours %d mins.",
                $ticks,
                $secs,
                $mins,
                $hours,
                $mins - ($hours*60));
	 
// Visualizza la finestra con il bottone di OK
MessageBoxA(NULL,
            $str,
            "Uptime Information",
            MB_OK);
?>
Sommario
w32api_deftype -- ...) Definisce un tipo per l'uso con altre w32api_functions
w32api_init_dtype --  Crea un'istanza ai tipi di dati typename e li riempie con i valori forniti
w32api_invoke_function -- ....) Invoca la funzione funcname con gli argomenti passati dopo il nome della funzione
w32api_register_function -- Registra la funzione function_name dalla libreria con PHP
w32api_set_call_method -- Imposta il metodo di chiamata usato

w32api_deftype

(4.2.0 - 4.2.3 only)

w32api_deftype -- ...) Definisce un tipo per l'uso con altre w32api_functions

Descrizione

bool w32api_deftype ( string typename, string member1_type, string member1_name [, string ... [, string ...]] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Se si desidera definire una tipologia di dati per le chiamate w32api, occorre eseguire al funzione w32api_deftype(). Questa funzione richiede 2n+1 argomenti, dove n è il numero dei membri costituenti il tipo. Il primo argomento è il nome del tipo. Quindi è seguito dal tipo del mebro che, a sua volta, è seguito dal nome del membro. I membri costituenti il tipo possono essere, a loro volta, dei tipi definiti dall'utente. Tutti i nomi dei tipi dati sono sensibili alle minuscole/maiuscole. I nomi dei tipi predefiniti sono in minuscolo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

w32api_init_dtype

(4.2.0 - 4.2.3 only)

w32api_init_dtype --  Crea un'istanza ai tipi di dati typename e li riempie con i valori forniti

Descrizione

resource w32api_init_dtype ( string typename, mixed value [, mixed ...] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 crea un'istanza di un tipo dati chiamato typename, valorizzandolo. Il parametro typename è sensibile alle minuscole/maiuscole. Si dovrebbe indicare i valori nel medesimo ordine con cui sono definiti i tipi di dati in w32api_deftype(). Il tipo di risorsa restituito è dynaparm.

w32api_invoke_function

(4.2.0 - 4.2.3 only)

w32api_invoke_function -- ....) Invoca la funzione funcname con gli argomenti passati dopo il nome della funzione

Descrizione

mixed w32api_invoke_function ( string funcname, mixed argument [, mixed ...] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 w32api_invoke_function() tenta di recuperare la funzione registrata in precedenza, indicata in funcname, passandogli i parametri previsti. Il tipo di valore restituito è uno di quelli impostati in fase di registrazione della funzione, il valore restituito è quello restituito dalla funzione stessa. Tutti i parametri possono essere o un qualsiasi tipo PHP oppure un tipo definito tramite w32api_deftype().

w32api_register_function

(4.2.0 - 4.2.3 only)

w32api_register_function -- Registra la funzione function_name dalla libreria con PHP

Descrizione

bool w32api_register_function ( string library, string function_name, string return_type )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 tenta di trovare la funzione function_name in library, e cerca di importarla in PHP. Sarà registrata con il tipo di parametro di ritorno indicato in return_type. Questo può essere un generico tipo PHP oppure un tipo definito tramite w32api_deftype(). I nomi dei tipi sono sensibili alle maiuscole/minuscole. I nomi dei tipi predefiniti dovrebbero essere in minuscolo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

w32api_set_call_method

(4.2.0 - 4.2.3 only)

w32api_set_call_method -- Imposta il metodo di chiamata usato

Descrizione

void w32api_set_call_method ( int 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.

Questa funzione imposta il tipo della chiamata al metodo. Il parametro può essere uno delle seguenti costanti: DC_CALL_CDECL o DC_CALL_STD. Per default assume DC_CALL_STD.

CLVII. WDDX Functions

Introduzione

These functions are intended for work with WDDX.


Requisiti

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).


Installazione

After installing expat compile PHP with --enable-wddx.

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Esempio 1. Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Esempio 2. Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Nota: If you want to serialize non-ASCII characters you have to convert your data to UTF-8 first (see utf8_encode() and iconv()).

Sommario
wddx_add_vars --  Add variables to a WDDX packet with the specified ID
wddx_deserialize -- Alias di wddx_unserialize()
wddx_packet_end -- Ends a WDDX packet with the specified ID
wddx_packet_start --  Starts a new WDDX packet with structure inside it
wddx_serialize_value -- Serialize a single value into a WDDX packet
wddx_serialize_vars -- Serialize variables into a WDDX packet
wddx_unserialize -- Unserializes a WDDX packet

wddx_add_vars

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_add_vars --  Add variables to a WDDX packet with the specified ID

Description

bool wddx_add_vars ( int packet_id, mixed name_var [, mixed ...] )

wddx_add_vars() is used to serialize passed variables and add the result to the packet specified by the packet_id. The variables to be serialized are specified in exactly the same way as wddx_serialize_vars().

wddx_deserialize

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_deserialize -- Alias di wddx_unserialize()

Descrizione

This function is an alias of: wddx_unserialize().

wddx_packet_end

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_packet_end -- Ends a WDDX packet with the specified ID

Description

string wddx_packet_end ( resource packet_id )

wddx_packet_end() ends the WDDX packet specified by the packet_id and returns the string with the packet.

wddx_packet_start

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_packet_start --  Starts a new WDDX packet with structure inside it

Description

resource wddx_packet_start ( [string comment] )

Use wddx_packet_start() to start a new WDDX packet for incremental addition of variables. It takes an optional comment string and returns a packet ID for use in later functions. It automatically creates a structure definition inside the packet to contain the variables.

wddx_serialize_value

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_serialize_value -- Serialize a single value into a WDDX packet

Description

string wddx_serialize_value ( mixed var [, string comment] )

wddx_serialize_value() is used to create a WDDX packet from a single given value. It takes the value contained in var, and an optional comment string that appears in the packet header, and returns the WDDX packet.

wddx_serialize_vars

(PHP 3 >= 3.0.7, PHP 4, PHP 5)

wddx_serialize_vars -- Serialize variables into a WDDX packet

Description

string wddx_serialize_vars ( mixed var_name [, mixed ...] )

wddx_serialize_vars() is used to create a WDDX packet with a structure that contains the serialized representation of the passed variables.

wddx_serialize_vars() takes a variable number of arguments, each of which can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

Esempio 1. wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

The above example will produce:
<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

wddx_unserialize

(PHP 3 >= 3.0.7, PHP 5 CVS only)

wddx_unserialize -- Unserializes a WDDX packet

Description

mixed wddx_unserialize ( string packet )

wddx_unserialize() takes a packet string and unserializes it. It returns the result which can be string, number, or array. Note that structures are unserialized into associative arrays.

CLVIII. win32service Functions

Introduzione

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.


Requisiti

Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of windows derived from Windows NT should be compatible.


Installazione

Installing from PECL

  1. You can download php_win32service.dll from http://snaps.php.net/win32/. Choose the PECL_X_X folder that matches you PHP version.

  2. Copy the php_win32service.dll into your extension_dir.

  3. Load the extension from your php.ini
    extension=php_win32service.dll


Esempi

Esempio 1. Registering a PHP script to run as a service

<?php
win32_create_service(array(
		'service' => 'dummyphp',                 # the name of your service
		'display' => 'sample dummy PHP service', # description
		'params' => 'c:\path\to\script.php run', # path to the script and parameters
	));
?>

Esempio 2. Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Esempio 3. Running as a service

<?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # do your work here.
    # try not to take up more than 30 seconds before going around the loop
    # again
  }
}
?>


Costanti predefinite

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.

WIN32_SERVICE_CONTROL_CONTINUE (integer)

WIN32_SERVICE_CONTROL_INTERROGATE (integer)

WIN32_SERVICE_CONTROL_PAUSE (integer)

WIN32_SERVICE_CONTROL_STOP (integer)

WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE (integer)

WIN32_SERVICE_CONTROL_POWEREVENT (integer)

WIN32_SERVICE_CONTROL_SESSIONCHANGE (integer)

WIN32_ERROR_CALL_NOT_IMPLEMENTED (integer)

WIN32_NO_ERROR (integer)

WIN32_SERVICE_RUNNING (integer)

WIN32_SERVICE_STOPPED (integer)

WIN32_SERVICE_STOP_PENDING (integer)

WIN32_SERVICE_WIN32_OWN_PROCESS (integer)

WIN32_SERVICE_INTERACTIVE_PROCESS (integer)

WIN32_SERVICE_STOPPED (integer)

WIN32_SERVICE_START_PENDING (integer)

WIN32_SERVICE_STOP_PENDING (integer)

WIN32_SERVICE_RUNNING (integer)

WIN32_SERVICE_CONTINUE_PENDING (integer)

WIN32_SERVICE_PAUSE_PENDING (integer)

WIN32_SERVICE_PAUSED (integer)

WIN32_SERVICE_ACCEPT_NETBINDCHANGE (integer)

WIN32_SERVICE_ACCEPT_PARAMCHANGE (integer)

WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE (integer)

WIN32_SERVICE_ACCEPT_SHUTDOWN (integer)

WIN32_SERVICE_ACCEPT_STOP (integer)

WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE (integer)

WIN32_SERVICE_ACCEPT_POWEREVENT (integer)

WIN32_SERVICE_ACCEPT_SESSIONCHANGE (integer)

WIN32_SERVICE_FILE_SYSTEM_DRIVER (integer)

WIN32_SERVICE_KERNEL_DRIVER (integer)

WIN32_SERVICE_WIN32_SHARE_PROCESS (integer)

WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS (integer)

Sommario
win32_create_service -- Creates a new service entry in the SCM database
win32_delete_service -- Deletes a service entry from the SCM database
win32_get_last_control_message -- Returns the last control message that was sent to this service
win32_query_service_status -- Queries the status of a service
win32_set_service_status -- Update the service status
win32_start_service_ctrl_dispatcher -- Registers the script with the SCM, so that it can act as the service with the given name
win32_start_service -- Starts a service
win32_stop_service -- Stops a service

win32_create_service

(PECL)

win32_create_service -- Creates a new service entry in the SCM database

Descrizione

long win32_create_service ( array details [, string machine] )

Elenco dei parametri

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run.

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

Valori restituiti

Returns TRUE on success, otherwise returns a win32 error code.

Esempi

Esempio 1. A win32_create_service() example

Any text that describes the purpose of the example, or what goes on in the example should go here (inside the
<?php
$x = win32_create_service(array(
		'service' => 'dummyphp',
		'display' => 'sample dummy PHP service',
		'params' => __FILE__ . ' run',
));
debug_zval_dump($x);
?>

Vedere anche:

win32_delete_service()

win32_delete_service

(PECL)

win32_delete_service -- Deletes a service entry from the SCM database

Descrizione

long win32_delete_service ( string servicename [, string machine] )

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

Elenco dei parametri

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Valori restituiti

Returns TRUE on success, or a win32 error code on failure.

Esempi

Esempio 1. A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

win32_get_last_control_message

(PECL)

win32_get_last_control_message -- Returns the last control message that was sent to this service

Descrizione

long win32_get_last_control_message ( void )

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Valori restituiti

Returns a control constant; one of WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_STOP, WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE, WIN32_SERVICE_CONTROL_POWEREVENT, WIN32_SERVICE_CONTROL_SESSIONCHANGE.

win32_query_service_status

(PECL)

win32_query_service_status -- Queries the status of a service

Descrizione

mixed win32_query_service_status ( string servicename [, string machine] )

Queries the current status for a service, returning an array of information.

Elenco dei parametri

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Valori restituiti

Returns FALSE on failure, otherwise returns an array consisting of the following information:

ServiceType

The dwServiceType.

CurrentState

The dwCurrentState.

ControlsAccepted

Which service controls are accepted by the service.

Win32ExitCode

If the service exited, the return code from the process.

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here.

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags.

win32_set_service_status

(PECL)

win32_set_service_status -- Update the service status

Descrizione

bool win32_set_service_status ( int status )

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Elenco dei parametri

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

win32_start_service_ctrl_dispatcher

(PECL)

win32_start_service_ctrl_dispatcher -- Registers the script with the SCM, so that it can act as the service with the given name

Descrizione

bool win32_start_service_ctrl_dispatcher ( string name )

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Elenco dei parametri

name

The short-name of the service, as registered by win32_create_service().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. A win32_start_service_ctrl_dispatcher() example

Any text that describes the purpose of the example, or what goes on in the example should go here (inside the

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
  die("I'm probably not running under the service control manager");
}

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # do some work here, trying not to take more than around 30 seconds
  # before coming back into the loop again
}
?>

win32_start_service

(PECL)

win32_start_service -- Starts a service

Descrizione

long win32_start_service ( string servicename [, string machine] )

Attempts to start the named service. Usually requires administrative privileges.

Elenco dei parametri

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valori restituiti

Returns WIN32_NO_ERROR on success, or some other win32 error code on failure.

Vedere anche:

win32_stop_service()

win32_stop_service

(PECL)

win32_stop_service -- Stops a service

Descrizione

long win32_stop_service ( string servicename [, string machine] )

Stops a named service. Requires administrative privileges.

Elenco dei parametri

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valori restituiti

Returns WIN32_NO_ERROR on success, or a win32 error code on failure.

Vedere anche:

win32_start_service()

CLIX. xattr Functions

Introduzione

The xattr extension allows for the manipulation of extended attributes on a filesystem.


Requisiti

To use xattr, you will need libattr installed. It is available at http://oss.sgi.com/projects/xfs/.

Nota: These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.


Installazione

xattr is currently available through PECL http://pecl.php.net/package/xattr.

If PEAR is available on your *nix-like system you can use the pear installer to install the xattr extension, by the following command: pear -v install xattr.

You can always download the tar.gz package and install xattr by hand:

Esempio 1. xattr install by hand

gunzip xattr-xxx.tgz
tar -xvf xattr-xxx.tar
cd xattr-xxx
phpize
./configure && make && make install


Costanti predefinite

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.

XATTR_ROOT (integer)

Set attribute in root (trusted) namespace. Requires root privileges.

XATTR_DONTFOLLOW (integer)

Do not follow the symbolic link but operate on symbolic link itself.

XATTR_CREATE (integer)

Function will fail if extended attribute already exists.

XATTR_REPLACE (integer)

Function will fail if extended attribute doesn't exist.

Sommario
xattr_get --  Get an extended attribute
xattr_list --  Get a list of extended attributes
xattr_remove --  Remove an extended attribute
xattr_set --  Set an extended attribute
xattr_supported --  Check if filesystem supports extended attributes

xattr_get

(PECL)

xattr_get --  Get an extended attribute

Descrizione

string xattr_get ( string filename, string name [, int flags] )

This function gets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Elenco dei parametri

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Tabella 1. Supported xattr flags

XATTR_DONTFOLLOWDo not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOTSet attribute in root (trusted) namespace. Requires root privileges.

Valori restituiti

Returns a string containing the value or FALSE if the attribute doesn't exist.

Esempi

Esempio 1. Checks if system administrator has signed the file

<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);

/* ... check if $signature is valid ... */

?>

xattr_list

(PECL)

xattr_list --  Get a list of extended attributes

Descrizione

array xattr_list ( string filename [, int flags] )

This functions gets a list of names of extended attributes of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Elenco dei parametri

filename

The path of the file.

flags

Tabella 1. Supported xattr flags

XATTR_DONTFOLLOWDo not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOTSet attribute in root (trusted) namespace. Requires root privileges.

Valori restituiti

This function returns an array with names of extended attributes.

Esempi

Esempio 1. Prints names of all extended attributes of file

<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);

echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

?>

Vedere anche:

xattr_get()

xattr_remove

(PECL)

xattr_remove --  Remove an extended attribute

Descrizione

bool xattr_remove ( string filename, string name [, int flags] )

This function removes an extended attribute of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Elenco dei parametri

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Tabella 1. Supported xattr flags

XATTR_DONTFOLLOWDo not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOTSet attribute in root (trusted) namespace. Requires root privileges.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Removes all extended attributes of a file

<?php
$file = 'some_file';
$attributes = xattr_list($file);

foreach ($attributes as $attr_name) {
    xattr_remove($file, $attr_name);
}
?>

xattr_set

(PECL)

xattr_set --  Set an extended attribute

Descrizione

bool xattr_set ( string filename, string name, string value [, int flags] )

This function sets the value of an extended attribute of a file.

Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.

Elenco dei parametri

filename

The file in which we set the attribute.

name

The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.

value

The value of the attribute.

flags

Tabella 1. Supported xattr flags

XATTR_CREATEFunction will fail if extended attribute already exists.
XATTR_REPLACEFunction will fail if extended attribute doesn't exist.
XATTR_DONTFOLLOWDo not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOTSet attribute in root (trusted) namespace. Requires root privileges.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Sets extended attributes on .wav file

<?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');

/* ... other code ... */

printf("You've played this song %d times", xattr_get($file, 'Listen count')); 
?>

xattr_supported

(PECL)

xattr_supported --  Check if filesystem supports extended attributes

Descrizione

bool xattr_supported ( string filename [, int flags] )

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

Elenco dei parametri

filename

The path of the tested file.

flags

Tabella 1. Supported xattr flags

XATTR_DONTFOLLOWDo not follow the symbolic link but operate on symbolic link itself.

Valori restituiti

This function returns TRUE if filesystem supports extended attributes, FALSE if it doesn't and NULL if it can't be determined (for example wrong path or lack of permissions to file).

Esempi

Esempio 1. xattr_supported() example

The following code checks if we can use extended attributes.

<?php
$file = 'some_file';

if (xattr_supported($file)) {
    /* ... make use of some xattr_* functions ... */
}

?>

CLX. xdiff Functions

Introduzione

xdiff extension creates and applies patches to both text and binary files.


Requisiti

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage http://www.xmailserver.org/xdiff-lib.html.

Nota: You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.


Installazione

xdiff is currently available through PECL http://pecl.php.net/package/xdiff.

If PEAR is available on your *nix-like system you can use the pear installer to install the xdiff extension, by the following command: pear -v install xdiff.

You can always download the tar.gz package and install xdiff by hand:

Esempio 1. xdiff install by hand

gunzip xdiff-xxx.tgz
tar -xvf xdiff-xxx.tar
cd xdiff-xxx
phpize
./configure && make && make install


Costanti predefinite

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.

XDIFF_PATCH_NORMAL (integer)

XDIFF_PATCH_REVERSE (integer)

Sommario
xdiff_file_diff_binary --  Make binary diff of two files
xdiff_file_diff --  Make unified diff of two files
xdiff_file_merge3 --  Merge 3 files into one
xdiff_file_patch_binary --  Patch a file with a binary diff
xdiff_file_patch --  Patch a file with an unified diff
xdiff_string_diff_binary --  Make binary diff of two strings
xdiff_string_diff --  Make unified diff of two strings
xdiff_string_merge3 --  Merge 3 strings into one
xdiff_string_patch_binary --  Patch a string with a binary diff
xdiff_string_patch --  Patch a string with an unified diff

xdiff_file_diff_binary

(PECL)

xdiff_file_diff_binary --  Make binary diff of two files

Description

bool xdiff_file_diff_binary ( string file1, string file2, string dest )

xdiff_file_diff_binary() makes binary diff of files file1 and file2 and stores result in file dest. This function works with both text and binary files. Resulting file is in binary format.

Nota: Both files will be loaded into memory so ensure that your memory_limit is set high enough.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>

See also xdiff_string_diff_binary().

xdiff_file_diff

(PECL)

xdiff_file_diff --  Make unified diff of two files

Description

bool xdiff_file_diff ( string file1, string file2, string dest [, int context [, bool minimal]] )

xdiff_file_diff() makes unified diff of files file1 and file2 and stores result in file dest. context indicated how many lines of context you want to include in diff result. Set minimal to TRUE if you want to minimalize size of diff (can take a long time). Resulting file is human-readable.

Nota: This function doesn't work well with binary files. To make diff of binary files use xdiff_file_diff_binary().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. xdiff_file_diff() example

The following code makes unified diff of two php files.

<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';

xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>

See also xdiff_string_diff().

xdiff_file_merge3

(PECL)

xdiff_file_merge3 --  Merge 3 files into one

Description

mixed xdiff_file_merge3 ( string file1, string file2, string file3, string dest )

xdiff_file_merge3() merges files file1, file2 and file3 into one and stores result in file dest.

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Esempio 1. xdiff_file_merge3() example

The following code merges three files into one.

<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';

$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
    echo "Rejects:\n";
    echo $errors;
}
?>

See also xdiff_string_merge3().

xdiff_file_patch_binary

(PECL)

xdiff_file_patch_binary --  Patch a file with a binary diff

Description

bool xdiff_file_patch_binary ( string file, string patch, string dest )

xdiff_file_patch_binary() patches file file with binary patch in file patch and stores result in file dest.

Nota: Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. xdiff_file_patch_binary() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

See also xdiff_string_patch_binary().

xdiff_file_patch

(PECL)

xdiff_file_patch --  Patch a file with an unified diff

Description

mixed xdiff_file_patch ( string file, string patch, string dest [, int flags] )

xdiff_file_patch() patches file file with unified patch in file patch and stores result in file dest.

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Returns FALSE if an internal error happened, string with rejected chunks of patch or TRUE if patch has been successfully applied.

Esempio 1. xdiff_file_patch() example

The following code applies unified diff to a file.

<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

Esempio 2. Patch reversing example

The following code reverses a patch.

<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

See also xdiff_string_patch().

xdiff_string_diff_binary

(PECL)

xdiff_string_diff_binary --  Make binary diff of two strings

Description

string xdiff_string_diff_binary ( string str1, string str2 )

xdiff_string_diff_binary() makes binary diff of strings str1 and str2.

Returns string with result or FALSE if an internal error happened.

See also xdiff_file_diff_binary().

xdiff_string_diff

(PECL)

xdiff_string_diff --  Make unified diff of two strings

Description

string xdiff_string_diff ( string str1, string str2 [, int context [, bool minimal]] )

xdiff_string_diff() makes unified diff of strings str1 and str2. context indicated how many lines of context you want to include in diff result. Set minimal to TRUE if you want to minimalize size of diff (can take a long time).

Nota: This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_diff_binary().

Returns string with result or FALSE if an internal error happened.

Esempio 1. xdiff_string_diff() example

The following code makes unified diff of two articles.

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

?>

See also xdiff_file_diff().

xdiff_string_merge3

(PECL)

xdiff_string_merge3 --  Merge 3 strings into one

Description

mixed xdiff_string_merge3 ( string str1, string str2, string str3 [, string &error] )

xdiff_string_merge3() merges strings str1, str2 and str3 into one.

If error is passed then rejected parts are stored inside this variable.

Returns merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

See also xdiff_file_merge3().

xdiff_string_patch_binary

(PECL)

xdiff_string_patch_binary --  Patch a string with a binary diff

Description

string xdiff_string_patch_binary ( string str, string patch )

xdiff_string_patch_binary() patches string str with binary patch in string patch.

Returns a patched string.

See also xdiff_file_patch_binary().

xdiff_string_patch

(PECL)

xdiff_string_patch --  Patch a string with an unified diff

Description

string xdiff_string_patch ( string str, string patch [, int flags [, string &error]] )

xdiff_string_patch() patches string str with unified patch in string patch.

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

If error is passed then rejected parts are stored inside this variable.

Esempio 1. xdiff_string_patch() example

The following code applies changes to some article.

<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors = '';

$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
    echo "New article:\n";
    echo $new_article;
}

if (strlen($errors)) {
    echo "Rejects: \n";
    echo $errors;
}

?>

Returns a patched string.

See also xdiff_file_patch().

CLXI. Funzioni relative al parser XML

Introduzione

XML (eXtensible Markup Language) è un formato utilizzato per l'interscambio di documenti strutturati sul Web. Questo è uno standard definito da The World Wide Web consortium (W3C). Maggiori informazioni su XML e le relative tecnologie possono essere reperite all'indirizzo http://www.w3.org/XML/.

Questo modulo del PHP offre il supporto del modulo expat di James Clark. Questo tool permette il parsing, ma non la validazione, di documenti XML. Sono supportati tre tipi di codifica di caratteri, supportati anche dal PHP:US-ASCII, ISO-8859-1 ed UTF-8. La codifica UTF-16 non è supportata.

Questo modulo permette di creare parser XML e di definire dei gestori per i vari eventi XML. Inoltre ogni singolo parser XML ha diversi parametri che possono essere configurati in base alle varie esigenze.


Requisiti

Di norma questo modulo utilizza un expat compat layer. Tuttavia si può utilizzare anche expat, che può essere reperito all'indirizzo http://www.jclark.com/xml/expat.html. Il Makefile fornito con expat, per default, non compila la libreria, occorre utilizzare le seguenti istruzioni per il comando make:
libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
Il sorgente in formato package RPM può essere reperito all'indirizzo http://sourceforge.net/projects/expat/.


Installazione

Queste funzioni sono abilitate per default utilizzando le libreria expat fornita. Si può disabilitare il supporto XML utilizzando --disable-xml. Se si compila il PHP come modulo per Apache 1.3.9 o versioni successive, il PHP automaticamente utilizzerà la libreria expat di Apache. Se non si desidera utilizzare la libreria fornita, configurare il PHP con --with-expat-dir=DIR, dove DIR indica la directory in cui è installato expat.

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.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

xml

La risorsa xml restituita da xml_parser_create() e xml_parser_create_ns() è un riferimento all'istanza del parser da utilizzarsi con le funzioni previste da questo modulo.


Costanti predefinite

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.

XML_ERROR_NONE (integer)

XML_ERROR_NO_MEMORY (integer)

XML_ERROR_SYNTAX (integer)

XML_ERROR_NO_ELEMENTS (integer)

XML_ERROR_INVALID_TOKEN (integer)

XML_ERROR_UNCLOSED_TOKEN (integer)

XML_ERROR_PARTIAL_CHAR (integer)

XML_ERROR_TAG_MISMATCH (integer)

XML_ERROR_DUPLICATE_ATTRIBUTE (integer)

XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)

XML_ERROR_PARAM_ENTITY_REF (integer)

XML_ERROR_UNDEFINED_ENTITY (integer)

XML_ERROR_RECURSIVE_ENTITY_REF (integer)

XML_ERROR_ASYNC_ENTITY (integer)

XML_ERROR_BAD_CHAR_REF (integer)

XML_ERROR_BINARY_ENTITY_REF (integer)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)

XML_ERROR_MISPLACED_XML_PI (integer)

XML_ERROR_UNKNOWN_ENCODING (integer)

XML_ERROR_INCORRECT_ENCODING (integer)

XML_ERROR_UNCLOSED_CDATA_SECTION (integer)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)

XML_OPTION_CASE_FOLDING (integer)

XML_OPTION_TARGET_ENCODING (integer)

XML_OPTION_SKIP_TAGSTART (integer)

XML_OPTION_SKIP_WHITE (integer)


Gestori di eventi

I gestori di eventi XML definiti sono:

Tabella 1. Gestori XML supportati

Funzione PHP per attivare il gestoreDescrizione dell'evento
xml_set_element_handler() L'evento 'Elemento' viene attivato quando il parser XML incontra i tag di apertura e chiusura. Esistono gestori separati per i tag di apertura e di chiusura.
xml_set_character_data_handler() Sono dati tutti i contenuti dei documenti XML che non siano dei markup, compresi gli spazi tra i tag. Si noti che il parser XML non aggiunge ne rimuove spazi, è compito dell'applicazione decidere se gli spazi siano significativi o meno.
xml_set_processing_instruction_handler() Ai programmatori PHP dovrebbe già essere familiare le istruzioni di processo (PIs). <?php ?> è un istruzione di processo dove php viene definito "PI target". La gestione di questi è specifica dell'applicazione, tranne che tutti i PI targets che iniziano con "XML", questi sono riservati.
xml_set_default_handler() Tutto ciò che non rientra negli altri gestori ricade nel gestore di default. In questo gestore si ha elementi come la dichiarazione dei tipo documento.
xml_set_unparsed_entity_decl_handler() Questo gestore viene richiamato per la gestione di entità non analizzate (NDATA).
xml_set_notation_decl_handler() Questo gestore viene richiamato per la dichiarazione di una notazione.
xml_set_external_entity_ref_handler() Questo gestore viene richiamato quando il parser XML incontra un riferimento ad una entità esterna analizzata. Questa può essere, ad esempio, un riferimento ad un file o ad un URL. Vedere esempio di entità esterne per una dimostrazione.


Case Folding

Le funzioni di gestione degli elementi possono ottenere i nomi dei propri elementi case-folded. Lo standard XML definisce il case-folding come "un processo applicato ad una sequenza di caratteri, nel quale quelli identificati come non-maiuscoli sono sostituiti dai corrispettivi caratteri maiuscoli". In altre parole, in XML il termine case-folding indica, semplicemente, la conversione a lettere maiuscole.

Per default, i nomi di tutti gli elementi passati alle funzioni di gestione sono case-folded. Questo comportamento può essere verificato e controllato nel parser XML rispettivamente con le funzioni xml_parser_get_option() e xml_parser_set_option().


Codici di errore

Vengono definite le seguenti costanti per i codici di errore XML (come restituito da xml_parse()):

XML_ERROR_NONE
XML_ERROR_NO_MEMORY
XML_ERROR_SYNTAX
XML_ERROR_NO_ELEMENTS
XML_ERROR_INVALID_TOKEN
XML_ERROR_UNCLOSED_TOKEN
XML_ERROR_PARTIAL_CHAR
XML_ERROR_TAG_MISMATCH
XML_ERROR_DUPLICATE_ATTRIBUTE
XML_ERROR_JUNK_AFTER_DOC_ELEMENT
XML_ERROR_PARAM_ENTITY_REF
XML_ERROR_UNDEFINED_ENTITY
XML_ERROR_RECURSIVE_ENTITY_REF
XML_ERROR_ASYNC_ENTITY
XML_ERROR_BAD_CHAR_REF
XML_ERROR_BINARY_ENTITY_REF
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
XML_ERROR_MISPLACED_XML_PI
XML_ERROR_UNKNOWN_ENCODING
XML_ERROR_INCORRECT_ENCODING
XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_EXTERNAL_ENTITY_HANDLING


Codifica dei caratteri

L'estensione XML di PHP supporta il set di caratteri Unicode tramite differenti codifiche di caratteri. Esistono due tipi di codifiche di caratteri, source encoding e target encoding. Nella rappresentazione interna dei documenti il PHP utilizza sempre la codifica UTF-8.

La codifica del sorgente viene eseguita quando un documento XML viene analizzato. Durante la creazione di un parser XML, si può specificare la codifica del sorgente (questa codifica non potrà essere variata in seguito nel corso della vita del parser XML). Le codifiche supportate sono ISO-8859-1, US-ASCII e UTF-8. Le prime due sono codifiche a singolo byte, ciò significa che ciascun carattere è rappresentato da un byte singolo, mentre la codifica UTF-8 può rappresentare caratteri composti da un numero variabile di bit (fino a 21) usando da uno fino a quattro byte. La codifica del sorgente utilizzata per default dal PHP è ISO-8859-1.

La codifica per il destinatario viene eseguita quando il PHP passa i dati alle funzioni di gestione del XML. Quando viene creato un parser XML, la codifica per il destinatario viene posta uguale alla codifica del sorgente, ma ciò può essere variato. La codifica per il destinatario viene applicata ai caratteri dei dati, ai nomi dei tag e alle istruzioni di processamento.

Se il parser XML incontra caratteri esterni al range dei caratteri rappresentabili dalla codifica, restituirà un errore.

Se il PHP incontra nel documento analizzato dei caratteri che non è in grado di rappresentare con la codifica scelta per il destinatario, "degrada" il carattere problematico. Attaualmente ciò significa sostuire il carattere in questione con un punto interrogativo.


Esempi

Di seguito verranno illustrati alcuni esempi di script PHP per il parsing di documenti XML.


Esempio della struttura degli elementi XML

Il primo esempio visualizza, con indentazione, la struttura degli elementi di apertura di un documento.

Esempio 1. Visualizza la struttura degli elementi XML

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs) 
{
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name) 
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>


Esempio di mappatura dei tag XML

Esempio 2. Conversione da XML a HTML

Il seguente esempio converte i tag di un documento XML in tag HTML. Gli elementi non trovati nella matrice dei tag saranno ignorati. Ovviamente questo esempio funziona solo con uno specifico tipo di documento XML:

<?php
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs) 
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
    }
}

function characterData($parser, $data) 
{
    echo $data;
}

$xml_parser = xml_parser_create();
// Si utilizza il case-folding per essere certi di trovare le tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("Non si riesce ad aprire il documento XML");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("Errore XML: %s alla linea %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>


Esempio di entità XML esterna

Questo esempio evidenzia il codice XML. Si illustrerà come utilizzare il riferimento ad entità esterne per includere ed analizzare altri documenti, sarà illustrato anche come processare le PI, ed il modo per determinare l'affidabilità del codice contenuto delle PI.

I documenti XML che possono essere usati per questo esempio sono presenti dopo l'esempio (xmltest.xml e xmltest2.xml.)

Esempio 3. Esempio di entità esterna

<?php
$file = "xmltest.xml";

function trustedFile($file) 
{
    // si considera affidabili soltanto i file locali del proprio utente
    if (!eregi("^([a-z]+)://", $file) 
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs) 
{
    echo "&lt;<font color=\"#0000cc\">$name</font>";
    if (sizeof($attribs)) {
        while (list($k, $v) = each($attribs)) {
            echo " <font color=\"#009900\">$k</font>=\"<font 
                   color=\"#990000\">$v</font>\"";
        }
    }
    echo "&gt;";
}

function endElement($parser, $name) 
{
    echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data) 
{
    echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data) 
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // Se il documento analizzato è "affidabile", si può dire che è sicura
            // l'esecuzione del codice PHP presente in esso. In caso contrario si visualizza
            // il codice.
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Codice PHP inaffidabile: <i>%s</i>", 
                        htmlspecialchars($data));
            }
            break;
    }
}

function defaultHandler($parser, $data) 
{
    if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
        printf('<font color="#aa00aa">%s</font>', 
                htmlspecialchars($data));
    } else {
        printf('<font size="-1">%s</font>', 
                htmlspecialchars($data));
    }
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
                                  $publicId) {
    if ($systemId) {
        if (!list($parser, $fp) = new_xml_parser($systemId)) {
            printf("Non si riesce ad aprire l'entità %s at %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("XML error: %s at line %d while parsing entity %s\n",
                       xml_error_string(xml_get_error_code($parser)),
                       xml_get_current_line_number($parser), $openEntityNames);
                xml_parser_free($parser);
                return false;
            }
        }
        xml_parser_free($parser);
        return true;
    }
    return false;
}

function new_xml_parser($file) 
{
    global $parser_file;

    $xml_parser = xml_parser_create();
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
    xml_set_element_handler($xml_parser, "startElement", "endElement");
    xml_set_character_data_handler($xml_parser, "characterData");
    xml_set_processing_instruction_handler($xml_parser, "PIHandler");
    xml_set_default_handler($xml_parser, "defaultHandler");
    xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");
    
    if (!($fp = @fopen($file, "r"))) {
        return false;
    }
    if (!is_array($parser_file)) {
        settype($parser_file, "array");
    }
    $parser_file[$xml_parser] = $file;
    return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    die("Non si riesce ad aprire il documento XML");
}

echo "<pre>";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("Errore XML: %s alla linea %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "</pre>";
echo "parsing completato\n";
xml_parser_free($xml_parser);

?>

Esempio 4. xmltest.xml

<?xml version='1.0'?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
 <TITLE>Title &plainEntity;</TITLE>
 <para>
  <informaltable>
   <tgroup cols="3">
    <tbody>
     <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     <row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
 &systemEntity;
 <section id="about">
  <title>Circa questo documento</title>
  <para>
   <!-- questo è un commento -->
   <?php echo 'Ciao!  Questa è la versione di PHP '.phpversion(); ?>
  </para>
 </section>
</chapter>

Questo file è stato richiamato da xmltest.xml:

Esempio 5. xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "Entità di test">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "Questa è una ulteriore riga di codice PHP eseguito."; ?>
</foo>

Sommario
utf8_decode --  Converte una stringa con caratteri ISO-8859-1 codificati con UTF-8 in formato ISO-8859-1 singolo byte
utf8_encode -- Codifica una stringa da ISO-8859-1 a UTF-8
xml_error_string -- Restituisce la stringa di errore dal parser XML
xml_get_current_byte_index -- Restituisce il corrente indice di posizione per un parser XML
xml_get_current_column_number --  Restituisce il numero di colonna corrente di un parser XML
xml_get_current_line_number -- Restituisce il numero di linea corrente da un parser XML
xml_get_error_code -- Restituisce il codice di errore dal parser XML
xml_parse_into_struct -- Analisi di dati XML in una struttura a matrice
xml_parse -- Inizia il parsing di un documento XML
xml_parser_create_ns --  Crea un parser XML con il supporto dello spazio dei nomi
xml_parser_create -- Crea un parser XML
xml_parser_free -- Cancella un parser XML
xml_parser_get_option -- Restituisce le opzioni da un parser XML
xml_parser_set_option -- Valorizza un'opzione di un parser XML
xml_set_character_data_handler -- Valorizza il gestore dei dati
xml_set_default_handler -- Valorizza il gestore di default
xml_set_element_handler -- Valorizza i gestori di inizio e fine elemento
xml_set_end_namespace_decl_handler --  Valorizza il gestore dello spazio dei nomi
xml_set_external_entity_ref_handler -- Valorizza il gestore dei riferimenti a entità esterne
xml_set_notation_decl_handler -- Valorizza il gestore delle dichiarazione delle notazioni
xml_set_object -- Utilizza il parser XML all'interno di un oggetto
xml_set_processing_instruction_handler --  Indica il gestore delle istruzioni di processo (PI)
xml_set_start_namespace_decl_handler --  Valorizza il gestore dei caratteri di dati
xml_set_unparsed_entity_decl_handler --  Valorizza il gestore delle dichiarazioni di entità non analizzate

utf8_decode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

utf8_decode --  Converte una stringa con caratteri ISO-8859-1 codificati con UTF-8 in formato ISO-8859-1 singolo byte

Descrizione

string utf8_decode ( string data )

Questa funzione decodifica il parametro data, considerato codificato in UTF-8, alla codifica ISO-8859-1.

Vedere anche utf8_encode() per dettagli sulla codifica UTF-8.

utf8_encode

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

utf8_encode -- Codifica una stringa da ISO-8859-1 a UTF-8

Descrizione

string utf8_encode ( string data )

Questa funzione converte la stringa data al formato UTF-8, e restituisce la nuova versione. UTF-8 è il meccanismo standard utilizzato da Unicode per la codifica dei valori wide character in un flusso di byte. La codifica UTF-8 è trasparente ai caratteri ASCII, è auto-sincronizzata (per un programma è possibile determinare dove iniziano i caratteri in un flusso di dati) e può essere usata nelle normali funzioni di confronto di stringhe per i sort e simili. Il PHP codifica i caratteri UTF-8 fino a quattro byte come segue:

Tabella 1. Codifica UTF-8

bytesbitsrappresentazione
170bbbbbbb
211110bbbbb 10bbbbbb
3161110bbbb 10bbbbbb 10bbbbbb
42111110bbb 10bbbbbb 10bbbbbb 10bbbbbb
Ciascuna b rappresenta un bit che può essere utilizzato per registrare le informazioni del carattere.

xml_error_string

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_error_string -- Restituisce la stringa di errore dal parser XML

Descrizione

string xml_error_string ( int codice_errore )

codice_errore

Un codice di errore da xml_get_error_code().

La funzione restituisce una stringa con la descrizione dell'errore codice_errore, oppure FALSE se non si trova una descrizione.

xml_get_current_byte_index

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_current_byte_index -- Restituisce il corrente indice di posizione per un parser XML

Descrizione

int xml_get_current_byte_index ( resource parser )

parser

Il riferimento al parser XML da cui si vuole ottenere la posizione.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, altrimenti la funzione restituisce in quale byte si trova attualmente il parser nel buffer dei dati (partendo da 0).

xml_get_current_column_number

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_current_column_number --  Restituisce il numero di colonna corrente di un parser XML

Descrizione

int xml_get_current_column_number ( resource parser )

parser

Il riferimento al parser XML da cui ottenere il numero di colonna.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, altrimenti restituisce in quale colonna sulla linea corrente (come indicato da xml_get_current_line_number()) si trova il parser.

xml_get_current_line_number

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_current_line_number -- Restituisce il numero di linea corrente da un parser XML

Descrizione

int xml_get_current_line_number ( resource parser )

parser

Il riferimento al parser XML da cui si vuole ottenere il numero di linea.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, altrimenti la funzione restituisce in quale linea del buffer dati si trova attualmente il parser.

xml_get_error_code

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_get_error_code -- Restituisce il codice di errore dal parser XML

Descrizione

int xml_get_error_code ( resource parser )

parser

Il riferimento al parser XML da cui si vuole ottenere il codice di errore.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, altrimenti la funzione restituisce uno dei codici di errore elencati in codici di errore.

Vedere anche xml_error_string().

xml_parse_into_struct

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

xml_parse_into_struct -- Analisi di dati XML in una struttura a matrice

Descrizione

int xml_parse_into_struct ( resource parser, string data, array &valori [, array &indice] )

Questa funzione registra un file XML in 2 strutture a matrice, una (indice) contiene i puntatori alla posizione dei valori nella matrice valori. Questi due parametri devono essere passati per riferimento.

Nota: La funzione xml_parse_into_struct() restituisce 0 in caso di errore e 1 in caso di successo. Questo non è lo stesso di FALSE e TRUE, fare attenzione con gli operatori tipo ===.

Nell'esempio seguente si illustra la struttura interna delle matrici generata dalla funzione. Qui si userà una semplice struttura con il tag note inserito all'interno del tag para, e quindi si analizzerà questo visualizzando la struttura ottenuta:

Esempio 1. Esempio di uso di xml_parse_into_struct()

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Array indice\n";
print_r($index);
echo "\narray dei valori\n";
print_r($vals);
?>

Eseguendo questo codice si otterrà:

Array indice
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Array dei valori
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

Un parsing event-driven (basato sulla libreria expat) può essere molto complicato se si deve trattare un documento XML complesso. Questa funzione non produce un oggetto in stile DOM, ma genera una struttura che permette di essere gestita a modo di albero. Quindi si può facilmente creare oggetti rappresentanti i dati del file XML. Si consideri il seguente file XML rappresentante un piccolo database di informazioni sugli aminoacidi.

Esempio 2. moldb.xml - piccolo database di informazioni sulle molecole

<?xml version="1.0"?>
<moldb>

    <molecule>
        <name>Alanine</name>
        <symbol>ala</symbol>
        <code>A</code>
        <type>hydrophobic</type>
    </molecule>

    <molecule>
        <name>Lysine</name>
        <symbol>lys</symbol>
        <code>K</code>
        <type>charged</type>
    </molecule>

</moldb>
Un codice per analizzare il documento e generare gli oggetti appropriati:

Esempio 3. parsemoldb.php - analizza moldb.xml e genera una matrice di oggetti molecole

<?php

class AminoAcid {
    var $name;  // aa nome
    var $symbol;    // simbolo di tre lettere
    var $code;  // codice di una lettera
    var $type;  // hydrophobic, charged or neutral
    
    function AminoAcid ($aa)
    {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename) 
{
    // legge il database degli aminoacidi
    $data = implode("", file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // loop attraverso la struttura
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // ciascuna coppia di elementi della matrice contigui
            // sono il limite inferiore e superiore per la definizione di ciascuna molecola
            for ($i=0; $i < count($molranges); $i+=2) {
                    $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues) {
    for ($i=0; $i < count($mvalues); $i++)
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database di oggetti Aminoacidi:\n";
print_r($db);

?>
Dopo l'esecuzione di parsemoldb.php, la variabile $db contiene una matrice di oggetti AminoAcid, e ciò viene confermato dall'output dello script:

** Database di oggetti Aminoacidi:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

xml_parse

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parse -- Inizia il parsing di un documento XML

Descrizione

bool xml_parse ( resource parser, string data [, bool e_finale] )

La funzione xml_parse() esegue il parsing di un documento XML. Gli handler configurati per la gestione degli eventi saranno richiamati ogni volta che si renderà necessario.

Elenco dei parametri

parser

Il riferimento al parser XML da utilizzare.

data

Segmento di dati da analizzare. Un documento può essere elaborato a segmenti richiamando xml_parse() diverse volte con nuovi dati, con il parametro e_finale settato a TRUE quando si elabora l'ultimo segmento.

e_finale (optional)

Se valorizzato a TRUE, il parametro data rappresenta l'ultimo segmento dei dati inviati al parser.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

In caso di parsing non riuscito, si può recuperare informazioni sull'errore usando xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() e xml_get_current_byte_index().

Nota: Gli errori nelle entità sono riportati alla fine dei dati questo soltanto se is_final è impostato a TRUE.

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5)

xml_parser_create_ns --  Crea un parser XML con il supporto dello spazio dei nomi

Descrizione

resource xml_parser_create_ns ( [string codifica [, string separatore]] )

La funzione xml_parser_create_ns() crea un nuovo parser XML con il supporto dello spazio dei nomi XML e restituisce un handle da utilizzarsi con le altre funzioni XML.

Con un parser che gestisce gli spazi dei nomi, i tag passati alle varie funzioni saranno composti dallo spazio dei nomi e dal nome del tag separati dalla stringa specificata in separatore oppure ':' per default.

Il parametro opzionale codifica indica la codifica dei caratteri in input ed output per il PHP 4. A partire dal PHP 5, la codifica dell'input è determinata automaticamente, pertanto il parametro codifica indica solo dal codifica dell'output. In PHP 4, la codifica di default dell'output è la medesima utilizzata dall'input. Se si indica una stringa vuota, il parser tenta di inviduare la codifica utilizzata per il documento guardando l'intestazione dello stesso. In PHP 5.0.0 a 5.0.1, il set di caratteri di default è l' ISO-8859-1, mentre in PHP 5.0.2 e successivi è UTF-8. Le codifiche supportate sono "ISO-8859-1", "UTF-8" e "US-ASCII".

Vedere anche xml_parser_create() e xml_parser_free().

xml_parser_create

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_create -- Crea un parser XML

Descrizione

resource xml_parser_create ( [string codifica] )

La funzione xml_parser_create() crea un nuovo parser XML e restituisce un handle da utilizzarsi con le altre funzioni XML.

Il parametro opzionale codifica indica la codifica dei caratteri in input ed output per il PHP 4. A partire dal PHP 5, la codifica dell'input è determinata automaticamente, pertanto il parametro codifica indica solo dal codifica dell'output. In PHP 4, la codifica di default dell'output è la medesima utilizzata dall'input. Se si indica una stringa vuota, il parser tenta di inviduare la codifica utilizzata per il documento guardando l'intestazione dello stesso. In PHP 5.0.0 a 5.0.1, il set di caratteri di default è l' ISO-8859-1, mentre in PHP 5.0.2 e successivi è UTF-8. Le codifiche supportate sono "ISO-8859-1", "UTF-8" e "US-ASCII".

Vedere anche xml_parser_create_ns() e xml_parser_free().

xml_parser_free

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_free -- Cancella un parser XML

Descrizione

bool xml_parser_free ( resource parser )

parser

Riferimento al parser XML da cancellare.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, altrimenti cancella il parser e restituisce TRUE

xml_parser_get_option

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_get_option -- Restituisce le opzioni da un parser XML

Descrizione

mixed xml_parser_get_option ( resource parser, int opzione )

parser

Riferimento al parser XML da cui ottenere l'opzione

opzione

Quale opzione ottenere. Vedere xml_parser_set_option() per l'elenco delle opzioni.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, o se option non è valido (viene anche generato un E_WARNING). Altrimenti viene restituito il valore dell'opzione.

Vedere xml_parser_set_option() per l'elenco delle opzioni.

xml_parser_set_option

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_parser_set_option -- Valorizza un'opzione di un parser XML

Descrizione

bool xml_parser_set_option ( resource parser, int opzione, mixed valore )

parser

Riferimento al parser XML di cui si vuole valorizzare l'opzione,

opzione

Quale opzione valorizzare. Vedere più avanti.

valore

Nuovo valore dell'opzione.

Questa funzione restituisce FALSE se parser non si riferisce ad un parser valido, o se l'opzione non può essere valorizzata. Altrimenti l'opzione viene valorizzata e la funzione restituisce TRUE.

Sono disponibili le seguenti opzioni:

Tabella 1. Opzioni del parser XML

Costante dell'opzionetipo di datoDescrizione
XML_OPTION_CASE_FOLDINGinteger Controlla se il case-folding è abilitato per questo parser XML. Abilitato per default.
XML_OPTION_SKIP_TAGSTARTinteger Indica quanti caratteri devono essere ignorati dall'inizio del nome del tag.
XML_OPTION_SKIP_WHITEinteger Indica se contare anche gli spazi nei caratteri da ignorare.
XML_OPTION_TARGET_ENCODINGstring Indica quale target encoding utilizzare in questo parser XML. Per default, è valorizzato con la medesima codifica del sorgente utilizzata da xml_parser_create(). Le codifiche supportate per il destinatario sono ISO-8859-1, US-ASCII e UTF-8.

xml_set_character_data_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_character_data_handler -- Valorizza il gestore dei dati

Descrizione

bool xml_set_character_data_handler ( resource parser, callback gestore )

Valorizza la funzione di gestione dei dati per il parser XML parser. Il parametro gestore è una stringa contenente il nome di una funzione che deve esistere quando viene richiamata la funzione xml_parse() per il parser.

La fuzione indicata in gestore deve accettare due parametri: gestore ( resource parser, string dati )

parser

Il primo parametro, parser, è un riferimento al parser XML chiamante il gestore.

dati

Il secondo parametro, dati, è una stringa contenente i dati.

Se il nome della funzione di gestione viene indicato come una stringa vuota o FALSE il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene valorizzato, oppure FALSE se parser non indica un parser.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_default_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_default_handler -- Valorizza il gestore di default

Descrizione

bool xml_set_default_handler ( resource parser, callback gestore )

Questa funzione valorizza il gestore di default per parser. Il parametro gestore è una stringa contenente il nome di una funzione che deve esistere quando viene eseguito xml_parse() per il parser XML.

La funzione indicata da gestore deve accettare due parametri: gestore ( resource parser, string dati )

parser

Il primo parametro, parser, è un riferimento al parser XML chiamante il gestore.

dati

Il secondo parametro, dati, contiene i dati. Questi possono essere dichiarazioni XML, dichiarazioni di tipo documento, entità oppure altri dati per i quali non è definito il gestore.

Se il nome della funzione del gestore viene valorizzato con una stringa vuota oppure a FALSE, il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene attivato, FALSE se parser non indica un parser XML.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_element_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_element_handler -- Valorizza i gestori di inizio e fine elemento

Descrizione

bool xml_set_element_handler ( resource parser, callback gestore_inizio_elemento, callback gestore_fine_elemento )

La funzione indica le funzioni di gestione di inizio e fine elemento per il parser XML. gestore_inizio_elemento e gestore_fine_elemento sono stringhe contenenti i nomi di funzioni che devono esistere quando viene eseguito xml_parse() per il parser.

La funzione indicata da gestore_inizio_elemento deve accettare tre parametri: gestore ( resource parser, string nome, array attibuti )

parser

Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.

nome

Il secondo parametro, nome, contiene il nome dell'elemento per il quale viene chiamato il gestore. Se è attivo il case-folding per questo parser, il nome dell'elemento sarà in maiuscolo.

attributi

Il terzo parametro, attributi, contiene un array associativo con gli attributi dell'elemento (se presenti). Le chiavi di questo array sono i nomi degli attributi, mentre i valori delle chiavi sono i valori degli attributi. I nomi degli attributi sono case-folded allo stesso modo dei nomi degli elementi. I valori degli attributi non lo sono.

L'ordine originale degli attributi può essere recuperato attraversando attributi in modo normale utilizzando la funzione each(). La prima chiave dell'array è il primo attributo, e così via.

La funzione indicata da gestore_fine_elemento deve accettare due parametri: gestore ( resource parser, string nome )

parser

Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.

nome

Il secondo parametro, nome, contiene il nome dell'elemento per il quale viene chiamato il gestore. Se è attivo il case-folding per questo parser, il nome dell'elemento sarà in maiuscolo.

Se il nome della funzione del gestore viene valorizzato con una stringa vuota oppure a FALSE, il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene attivato, FALSE se parser non indica un parser XML.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_end_namespace_decl_handler --  Valorizza il gestore dello spazio dei nomi

Descrizione

bool xml_set_end_namespace_decl_handler ( resource parser, callbaccallback hdl )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_external_entity_ref_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_external_entity_ref_handler -- Valorizza il gestore dei riferimenti a entità esterne

Descrizione

bool xml_set_external_entity_ref_handler ( resource parser, callback gestore )

Indica al parser XML parser la funzione per la gestione dei riferimenti a entità esterne. Il gestore è una stringa contenente il nome di una funzione che deve esistere quando viene eseguita la funzione xml_parse() per il parser.

La funzione indicata da gestore deve accettare cinque parametri, e dovrebbe restituire un intero. Se il valore restituito dal gestore è FALSE (valore assunto per default in caso di nessun valore restituito), il parser XML ferma l'elaborazione e xml_get_error_code() restituirà XML_ERROR_EXTERNAL_ENTITY_HANDLING. gestore ( resource parser, string nomi_entita_aperte, string base, string system_id, string public_id )

parser

Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.

nome_entita_aperte

Il secondo parametro, nomi_entita_aperte, è una lista di nomi, separati da spazio, delle entità che saranno aperte per il parsing di questa entità (compreso il nome dell'entità indicata)

base

Questa è la base per la risoluzione dell'identificatore system (systemid) delle entità esterne. Attualmente questo parametro è sempre valorizzato con una stringa vuota.

system_id

Il quarto parametro, system_id, è l'identificatore system come specificato nella dichiarazione dell'entità.

public_id

Il quinto parametro, public_id, è l'identificatore public come specificato nella dichiarazione dell'entità, oppure una stringa vuota se non viene specificato; lo spazio nell'identificatore public è normalizzato come richiesto dalle specifiche XML.

Se il nome della funzione del gestore viene valorizzato con una stringa vuota oppure a FALSE, il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene attivato, FALSE se parser non indica un parser XML.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_notation_decl_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_notation_decl_handler -- Valorizza il gestore delle dichiarazione delle notazioni

Descrizione

bool xml_set_notation_decl_handler ( resource parser, callback handler )

Indica al parser XML parser la funzione per la gestione delle dichiarazioni delle notazioni. Il gestore è una stringa contenente il nome di una funzione che deve esistere quando viene eseguita la funzione xml_parse() per il parser.

La dichiarazione di una notazione è una parte della DTD del documento ed ha il seguente formato:
<!NOTATION <parameter>name</parameter> 
{ <parameter>system_id</parameter> | <parameter>public_id</parameter>?>
Vedere la sezione 4.7 delle specifiche XML 1.0 per la definizione delle dichiarazioni delle notazioni.

La funzione indicata da gestore deve accettare cinque parametri: gestore ( resource parser, string nome_notazione, string base, string system_id, string public_id )

parser

Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.

nome_notazione

Questo è il parametro name della notazione, come dal formato descritto in precedenza.

base

Questa è la base per la risoluzione dell'identificatore system (system_id) delle entità esterne. Attualmente questo parametro è sempre valorizzato con una stringa vuota.

system_id

Identificatore system della dichiarazione della notazione esterna.

public_id

Identificatore public della dichiarazione della notazione esterna.

Se il nome della funzione del gestore viene valorizzato con una stringa vuota oppure a FALSE, il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene attivato, FALSE se parser non indica un parser XML.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_object

(PHP 4, PHP 5)

xml_set_object -- Utilizza il parser XML all'interno di un oggetto

Descrizione

void xml_set_object ( resource parser, object &oggetto )

Questa funzione permette l'uso del parser all'interno di un oggetto. Tutte le funzioni di callback possono essere indicate con xml_set_element_handler() e simili, e sono assunte come metodi dell'oggetto.

Esempio 1. Esempio di uso di xml_set_object()

<?php
class xml  {
    var $parser;

    function xml() 
    {
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);        
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

    function parse($data) 
    { 
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    { 
        var_dump($parser, $tag, $attributes); 
    }

    function cdata($parser, $cdata) 
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag) 
    {
        var_dump($parser, $tag);
    }

} // fine della classe xml

$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

xml_set_processing_instruction_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_processing_instruction_handler --  Indica il gestore delle istruzioni di processo (PI)

Descrizione

bool xml_set_processing_instruction_handler ( resource parser, callback gestore )

Indica al parser XML parser la funzione per la gestione delle istruzioni di processo (PI). Il gestore è una stringa contenente il nome di una funzione che deve esistere quando viene eseguita la funzione xml_parse() per il parser.

Le istruzioni di processo hanno il seguente formato:

<?
       target 
       data?>

Si può inserire codice PHP all'interno di questo tipo di tag, ma occorre fare attenzione ad una limitazione: in una PI XML, il tag di fine PI (?>) non può essere tra apici, pertanto questa seguenza di caratteri non dovrebbe apparire nel codice PHP che si inserisce nel documento XML con le PIs. Se ciò accade il resto del codice PHP, come il "reale" tag di fine PI, saranno trattati come caratteri di dati.

La funzione indicata da gestore deve accettare tre parametri: gestore ( resource parser, string target, string dati )

parser

Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.

target

Il secondo parametro, target, contiene la PI target.

dati

Il terzo parametro, dati, contiene i dati del PI.

Se il nome della funzione del gestore viene valorizzato con una stringa vuota oppure a FALSE, il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene attivato, FALSE se parser non indica un parser XML.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_start_namespace_decl_handler --  Valorizza il gestore dei caratteri di dati

Descrizione

bool xml_set_start_namespace_decl_handler ( resource parser, callback handler )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

xml_set_unparsed_entity_decl_handler

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

xml_set_unparsed_entity_decl_handler --  Valorizza il gestore delle dichiarazioni di entità non analizzate

Descrizione

bool xml_set_unparsed_entity_decl_handler ( resource parser, callback gestore )

Indica al parser XML parser la funzione per la gestione delle dichiarazioni di entità non analizzate. Il gestore è una stringa contenente il nome di una funzione che deve esistere quando viene eseguita la funzione xml_parse() per il parser.

Questo gestore viene richiamato quando il parser XML incontra una dichiarazione di entità esterna con una dichiarazione NDATA, tipo la seguente:
<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>} 
        NDATA <parameter>notationName</parameter>

Vedere la sezione 4.2.2 delle specifiche di XML 1.0 per la definizione di notazioni dichiarate in entità esterne.

La funzione indicata da gestore deve accettare sei parametri: gestore ( resource parser, string nome_entità, string base, string system_id, string public_id, string nome_notazione )

parser

Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.

nome_entità

Il nome dell'entità che sta per essere definita.

base

Questa è la base per la risoluzione dell'identificatore system (systemid) delle entità esterne. Attualmente questo parametro è sempre valorizzato con una stringa vuota.

system_id

Identificatore system per l'entità esterna.

public_id

Identificatore public per l'entità esterna.

nome_notazione

Nome della notazione di questa entità (vedere xml_set_notation_decl_handler()).

Se il nome della funzione del gestore viene valorizzato con una stringa vuota oppure a FALSE, il gestore in questione viene disabilitato.

La funzione restituisce TRUE se il gestore viene attivato, FALSE se parser non indica un parser XML.

Nota: Invece di un nome di funzione è possibile passare un vettore contenente un riferimento ad un oggetto e un nome di metodo.

CLXII. Funzioni XML-RPC

Introduzione

Queste funzioni possono essere utilizzate per scrivere client e server XML-RPC. Si possono trovare maggiori informazioni sul XML-RPC in http://www.xmlrpc.com/, e maggiore documentazione su questo modulo e le sue funzioni in http://xmlrpc-epi.sourceforge.net/.

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.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Per default il modulo XML-RPC non è abilitato in PHP. Per abilitarlo occorre utilizzare il perametro di configurazione --with-xmlrpc[=DIR] in fase di compila del PHP. Questo modulo è rilasciato con il PHP dalla versione 4.1.0.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione XML-RPC

NomeDefaultModificabileVariazioni
xmlrpc_errors"0"PHP_INI_SYSTEMDisponibile dal PHP 4.1.0.
xmlrpc_error_number"0"PHP_INI_ALLDisponibile dal PHP 4.1.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.

Sommario
xmlrpc_decode_request -- Decodifica XML nei nativi tipi di PHP
xmlrpc_decode -- Decodifica XML nei nativi tipi di PHP
xmlrpc_encode_request -- Genera XML per un metodo di richiesta
xmlrpc_encode -- Genera XML per un valore PHP
xmlrpc_get_type -- Riceve il tipo di xmlrpc per un valore PHP. Maggiormente ì usato per le stringhe base64 e datetime
xmlrpc_is_fault --  Determines if an array value represents an XMLRPC fault
xmlrpc_parse_method_descriptions -- Decodifica XML in una lista di method descriptions
xmlrpc_server_add_introspection_data -- Aggiunge documentazione introspettiva
xmlrpc_server_call_method -- Struttura le richieste XML e i metodi di chiamata
xmlrpc_server_create -- Crea un server xmlrpc
xmlrpc_server_destroy -- Distrugge le risorse del server
xmlrpc_server_register_introspection_callback -- Registra una funzione PHP per generare la documentazione
xmlrpc_server_register_method -- Registra una funzione PHP nel metodo di risorsa abbinato method_name
xmlrpc_set_type -- Imposta il tipo di xmlrpc, base64 o datetime, per un valore di stringa PHP

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode_request -- Decodifica XML nei nativi tipi di PHP

Descrizione

array xmlrpc_decode_request ( string xml, string &method [, string encoding] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode -- Decodifica XML nei nativi tipi di PHP

Descrizione

array xmlrpc_decode ( string xml [, string encoding] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode_request -- Genera XML per un metodo di richiesta

Descrizione

string xmlrpc_encode_request ( string method, mixed params [, array output_options] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode -- Genera XML per un valore PHP

Descrizione

string xmlrpc_encode ( mixed value )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_get_type -- Riceve il tipo di xmlrpc per un valore PHP. Maggiormente ì usato per le stringhe base64 e datetime

Descrizione

string xmlrpc_get_type ( mixed value )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5)

xmlrpc_is_fault --  Determines if an array value represents an XMLRPC fault

Description

bool xmlrpc_is_fault ( array arg )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_parse_method_descriptions -- Decodifica XML in una lista di method descriptions

Descrizione

array xmlrpc_parse_method_descriptions ( string xml )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_add_introspection_data -- Aggiunge documentazione introspettiva

Descrizione

int xmlrpc_server_add_introspection_data ( resource server, array desc )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_call_method -- Struttura le richieste XML e i metodi di chiamata

Descrizione

mixed xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options] )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_create -- Crea un server xmlrpc

Descrizione

resource xmlrpc_server_create ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_destroy -- Distrugge le risorse del server

Descrizione

int xmlrpc_server_destroy ( resource server )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_introspection_callback -- Registra una funzione PHP per generare la documentazione

Descrizione

bool xmlrpc_server_register_introspection_callback ( resource server, string 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_method -- Registra una funzione PHP nel metodo di risorsa abbinato method_name

Descrizione

bool xmlrpc_server_register_method ( resource server, string method_name, string 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_set_type -- Imposta il tipo di xmlrpc, base64 o datetime, per un valore di stringa PHP

Descrizione

bool xmlrpc_set_type ( string &value, string type )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

CLXIII. XMLReader functions

Introduzione

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.


Installazione

The XMLReader extension is available in PECL for PHP 5.0 and is included in PHP 5.1 by default. It and can be enabled by adding the argument --with--xmlreader to your configure line. The libxml extension is required.


Classi predefinite


XMLReader


Metodi


Proprietà

Tabella 1.

NameTypeRead-onlyDescription
attributeCountintyesThe number of attributes on the node
baseURIstringyesThe base URI of the node
depthintyesDepth of the node in the tree starting at 0
hasAttributesboolyesIndicates if node has attributes
hasValueboolyesIndicates if node has a text value
isDefaultboolyesIndicates if attribute is defaulted from DTD
isEmptyElementboolyesIndicates if node is an empty element tag
localNamestringyesThe local name of the node
namestringyesThe qualified name of the node
namespaceURIstringyesThe URI of the namespace associated with the node
nodeTypeintyesThe node type for the node
prefixstringyesThe prefix of the namespace associated with the node
valuestringyesThe text value of the node
xmlLangstringyesThe xml:lang scope which the node resides

Costanti predefinite

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. XMLReader Node Types

ConstantValueDescription
XMLREADER_NONE (integer) 0No node type
XMLREADER_ELEMENT (integer) 1Start element
XMLREADER_ATTRIBUTE (integer) 2Attribute node
XMLREADER_TEXT (integer) 3Text node
XMLREADER_CDATA (integer) 4CDATA node
XMLREADER_ENTITY_REF (integer) 5Entity Reference node
XMLREADER_ENTITY (integer) 6Entity Declaration node
XMLREADER_PI (integer) 7Processing Instruction node
XMLREADER_COMMENT (integer) 8Comment node
XMLREADER_DOC (integer) 9Document node
XMLREADER_DOC_TYPE (integer) 10Document Type node
XMLREADER_DOC_FRAGMENT (integer) 11Document Fragment node
XMLREADER_NOTATION (integer) 12Notation node
XMLREADER_WHITESPACE (integer) 13Whitespace node
XMLREADER_SIGNIFICANT_WHITESPACE (integer) 14Significant Whitespace node
XMLREADER_END_ELEMENT (integer) 15End Element
XMLREADER_END_ENTITY (integer) 16End Entity
XMLREADER_XML_DECLARATION (integer) 17XML Declaration node

Tabella 3. XMLReader Parser Options

ConstantValueDescription
XMLREADER_LOADDTD (integer) 1Load DTD but do not validate
XMLREADER_DEFAULTATTRS (integer) 2Load DTD and default attributes but do not validate
XMLREADER_VALIDATE (integer) 3Load DTD and validate while parsing
XMLREADER_SUBST_ENTITIES (integer) 4Subsitute entities and expand references
Sommario
XMLReader->close() -- Close the XMLReader input
XMLReader->expand() -- Returns a copy of the current node as a DOM object
XMLReader->getAttribute() -- Get the value of a named attribute
XMLReader->getAttributeNo() -- Get the value of an attribute by index
XMLReader->getAttributeNS() -- Get the value of an attribute by localname and URI
XMLReader->getParserProperty() --  Indicates if specified property has been set
XMLReader->isValid() -- Indicates if the parsed document is valid
XMLReader->lookupNamespace() -- Lookup namespace for a prefix
XMLReader->moveToAttribute() -- Move cursor to a named attribute
XMLReader->moveToAttributeNo() -- Move cursor to an attribute by index
XMLReader->moveToAttributeNs() -- Move cursor to a named attribute
XMLReader->moveToElement() -- Position cursor on the parent Element of current Attribute
XMLReader->moveToFirstAttribute() -- Position cursor on the first Attribute
XMLReader->moveToNextAttribute() -- Position cursor on the next Attribute
XMLReader->next() -- Move cursor to next node skipping all subtrees
XMLReader->open() -- Set the URI containing the XML to parse
XMLReader->read() -- Move to next node in document
XMLReader->setParserProperty() -- Set or Unset parser options
XMLReader->setRelaxNGSchema() -- Set the filename or URI for a RelaxNG Schema
XMLReader->setRelaxNGSchemaSource() -- Set the data containing a RelaxNG Schema
XMLReader->XML() -- Set the data containing the XML to parse

XMLReader->close()

(no version information, might be only in CVS)

XMLReader->close() -- Close the XMLReader input

Descrizione

class XMLReader {

bool close ( void )

}

Closes the input the XMLReader object is currently parsing.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->expand()

(no version information, might be only in CVS)

XMLReader->expand() -- Returns a copy of the current node as a DOM object

Descrizione

class XMLReader {

DOMNode expand ( void )

}

This method copies the current node and returns the appropriate DOM object.

Valori restituiti

The resulting DOMNode or FALSE on error.

XMLReader->getAttribute()

(no version information, might be only in CVS)

XMLReader->getAttribute() -- Get the value of a named attribute

Descrizione

class XMLReader {

string getAttribute ( string name )

}

Returns the value of a named attribute or an empty string if attribute does not exist or not positioned on an element node.

Elenco dei parametri

name

The name of the attribute.

Valori restituiti

The value of the attribute, or an empty string if no attribute with the given name is found or not positioned of element.

XMLReader->getAttributeNo()

(no version information, might be only in CVS)

XMLReader->getAttributeNo() -- Get the value of an attribute by index

Descrizione

class XMLReader {

string getAttributeNo ( int index )

}

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

Elenco dei parametri

index

The position of the attribute.

Valori restituiti

The value of the attribute, or an empty string if no attribute exists at index or not positioned of element.

XMLReader->getAttributeNS()

(no version information, might be only in CVS)

XMLReader->getAttributeNS() -- Get the value of an attribute by localname and URI

Descrizione

class XMLReader {

string getAttributeNS ( string localName, string namespaceURI )

}

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

Elenco dei parametri

localName

The local name.

namespaceURI

The namespace URI.

Valori restituiti

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found or not positioned of element.

XMLReader->getParserProperty()

(no version information, might be only in CVS)

XMLReader->getParserProperty() --  Indicates if specified property has been set

Descrizione

class XMLReader {

bool getParserProperty ( int property )

}

Indicates if specified property has been set.

Elenco dei parametri

property

One of the parser option constants.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->isValid()

(no version information, might be only in CVS)

XMLReader->isValid() -- Indicates if the parsed document is valid

Descrizione

class XMLReader {

bool isValid ( void )

}

Returns a boolean indicating if the document being parsed is currently valid.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->lookupNamespace()

(no version information, might be only in CVS)

XMLReader->lookupNamespace() -- Lookup namespace for a prefix

Descrizione

class XMLReader {

bool lookupNamespace ( string prefix )

}

Lookup in scope namespace for a given prefix.

Elenco dei parametri

prefix

String containing the prefix.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->moveToAttribute()

(no version information, might be only in CVS)

XMLReader->moveToAttribute() -- Move cursor to a named attribute

Descrizione

class XMLReader {

bool moveToAttribute ( string name )

}

Positions cursor on the named attribute.

Elenco dei parametri

name

The name of the attribute.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->moveToAttributeNo()

(no version information, might be only in CVS)

XMLReader->moveToAttributeNo() -- Move cursor to an attribute by index

Descrizione

class XMLReader {

bool moveToAttributeNo ( int index )

}

Positions cursor on attribute based on its position.

Elenco dei parametri

index

The position of the attribute.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->moveToAttributeNs()

(no version information, might be only in CVS)

XMLReader->moveToAttributeNs() -- Move cursor to a named attribute

Descrizione

class XMLReader {

bool moveToAttributeNs ( string localName, string namespaceURI )

}

Positions cursor on the named attribute in specified namespace.

Elenco dei parametri

localName

The local name.

namespaceURI

The namespace URI.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->moveToElement()

(no version information, might be only in CVS)

XMLReader->moveToElement() -- Position cursor on the parent Element of current Attribute

Descrizione

class XMLReader {

bool moveToElement ( void )

}

Moves cursor to the parent Element of current Attribute. Returns TRUE if sucessful and FALSE if it fails or not positioned on Attribute when this method is called.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->moveToFirstAttribute()

(no version information, might be only in CVS)

XMLReader->moveToFirstAttribute() -- Position cursor on the first Attribute

Descrizione

class XMLReader {

bool moveToFirstAttribute ( void )

}

Moves cursor to the first Attribute.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->moveToNextAttribute()

(no version information, might be only in CVS)

XMLReader->moveToNextAttribute() -- Position cursor on the next Attribute

Descrizione

class XMLReader {

bool moveToNextAttribute ( void )

}

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->next()

(no version information, might be only in CVS)

XMLReader->next() -- Move cursor to next node skipping all subtrees

Descrizione

class XMLReader {

bool next ( [string localname] )

}

Positions cursor on the next node skipping all subtrees.

Elenco dei parametri

localname

The name of the next node to move to.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->open()

(no version information, might be only in CVS)

XMLReader->open() -- Set the URI containing the XML to parse

Descrizione

class XMLReader {

bool open ( string URI )

}

Set the URI containing the XML document to be parsed.

Elenco dei parametri

URI

URI pointing to the document.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->read()

(no version information, might be only in CVS)

XMLReader->read() -- Move to next node in document

Descrizione

class XMLReader {

bool read ( void )

}

Moves cursor to the next node in the document.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->setParserProperty()

(no version information, might be only in CVS)

XMLReader->setParserProperty() -- Set or Unset parser options

Descrizione

class XMLReader {

bool setParserProperty ( int property, bool value )

}

Set or Unset parser option for the parser. The options must be set after xmlreader-open() or xmlreader-xml() are called and before the first xmlreader-read() call.

Elenco dei parametri

property

One of the parser option constants.

value

If set to TRUE the option will be enabled otherwise will be disabled.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->setRelaxNGSchema()

(no version information, might be only in CVS)

XMLReader->setRelaxNGSchema() -- Set the filename or URI for a RelaxNG Schema

Descrizione

class XMLReader {

bool setRelaxNGSchema ( string filename )

}

Set the filename or URI for the RelaxNG Schema to use for validation.

Elenco dei parametri

filename

filename or URI pointing to a RelaxNG Schema.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->setRelaxNGSchemaSource()

(no version information, might be only in CVS)

XMLReader->setRelaxNGSchemaSource() -- Set the data containing a RelaxNG Schema

Descrizione

class XMLReader {

bool setRelaxNGSchemaSource ( string source )

}

Set the data containing a RelaxNG Schema to use for validation.

Elenco dei parametri

source

String containing the RelaxNG Schema.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XMLReader->XML()

(no version information, might be only in CVS)

XMLReader->XML() -- Set the data containing the XML to parse

Descrizione

class XMLReader {

bool open ( string source )

}

Set the data containing the XML to parse.

Elenco dei parametri

source

String containing the XML to be parsed.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

CLXIV. XSL functions

Introduzione

The XSL extension implements the XSL standard, performing XSLT transformations using the libxslt library


Requisiti

This extension uses libxslt which can be found at http://xmlsoft.org/XSLT/. libxslt version 1.0.18 or greater is required.


Installazione

PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line. DIR is the libxslt installation directory.


Classi predefinite


XSLTProcessor


Costruttori


Metodi


Esempi

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

Esempio 1. collection.xml

<collection>
 <cd>
  <title>Fight for your mind</title>
  <artist>Ben Harper</artist>
  <year>1995</year>
 </cd>
 <cd>
  <title>Electric Ladyland</title>
  <artist>Jimi Hendrix</artist>
  <year>1997</year>
 </cd>
</collection>

Esempio 2. collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection! 
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="cd">
  <h1><xsl:value-of select="title"/></h1>
  <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  <hr />
 </xsl:template>
</xsl:stylesheet>


Costanti predefinite

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.

XSL_CLONE_AUTO (integer)

XSL_CLONE_NEVER (integer)

XSL_CLONE_ALWAYS (integer)

Sommario
XSLTProcessor->__construct() -- Creates a new XSLTProcessor object
XSLTProcessor->getParameter() -- Get value of a parameter
XSLTProcessor->hasExsltSupport() -- Determine if PHP has EXSLT support
XSLTProcessor->importStylesheet() -- Import stylesheet
XSLTProcessor->registerPHPFunctions() -- Enables the ability to use PHP functions as XSLT functions
XSLTProcessor->removeParameter() -- Remove parameter
XSLTProcessor->setParameter() -- Set value for a parameter
XSLTProcessor->transformToDoc() -- Transform to a DOMDocument
XSLTProcessor->transformToURI() -- Transform to URI
XSLTProcessor->transformToXML() -- Transform to XML

XSLTProcessor->__construct()

(no version information, might be only in CVS)

XSLTProcessor->__construct() -- Creates a new XSLTProcessor object

Descrizione

class XSLTProcessor {

__construct ( (void); )

}

Creates a new XSLTProcessor object.

Esempi

Esempio 1. Creating an XSLTProcessor

<?php

$xsl = new XSLTProcessor();
$xsl->importStyleSheet(DOMDocument::load($xsl_filename));
echo $xsl->transformToXML(DOMDocument::load($xml_filename));

?>

XSLTProcessor->getParameter()

(no version information, might be only in CVS)

XSLTProcessor->getParameter() -- Get value of a parameter

Descrizione

class XSLTProcessor {

string getParameter ( string namespaceURI, string localName )

}

Gets a parameter if previously set by XSLTProcessor->setParameter().

Elenco dei parametri

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Valori restituiti

The value of the parameter or NULL if it's not set.

XSLTProcessor->hasExsltSupport()

(no version information, might be only in CVS)

XSLTProcessor->hasExsltSupport() -- Determine if PHP has EXSLT support

Descrizione

class XSLTProcessor {

bool hasExsltSupport ( void )

}

This method determine if PHP was built with the EXSLT library.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Testing EXSLT support

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT support not available');
}

// do EXSLT stuff here ..

?>

XSLTProcessor->importStylesheet()

(no version information, might be only in CVS)

XSLTProcessor->importStylesheet() -- Import stylesheet

Descrizione

class XSLTProcessor {

void importStylesheet ( DOMDocument stylesheet )

}

This method import the stylesheet into the XSLTProcessor for transformations.

Elenco dei parametri

stylesheet

The imported style sheet as a DOMDocument object.

Valori restituiti

No value is returned.

XSLTProcessor->registerPHPFunctions()

(no version information, might be only in CVS)

XSLTProcessor->registerPHPFunctions() -- Enables the ability to use PHP functions as XSLT functions

Descrizione

class XSLTProcessor {

void registerPHPFunctions ( [mixed restrict] )

}

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

Elenco dei parametri

restrict

Use this parameter to only allow certain functions to be called from XSLT.

This parameter can be either a string (a function name) or an array of functions.

Valori restituiti

No value is returned.

Log delle modifiche

VersioneDescrizione
5.1.0 The restrict parameter was added.

XSLTProcessor->removeParameter()

(no version information, might be only in CVS)

XSLTProcessor->removeParameter() -- Remove parameter

Descrizione

class XSLTProcessor {

bool removeParameter ( string namespaceURI, string localName )

}

Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.

Elenco dei parametri

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

XSLTProcessor->setParameter()

(no version information, might be only in CVS)

XSLTProcessor->setParameter() -- Set value for a parameter

Descrizione

class XSLTProcessor {

bool setParameter ( string namespace, string name, string value )

}class XSLTProcessor {

bool setParameter ( string namespace, array options )

}

Sets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.

Elenco dei parametri

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

value

The new value of the XSLT parameter.

options

An array of name => value pairs. This syntax is available since PHP 5.1.0.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Changing the owner before the transformation

<?php

$collections = array(
    'Marc Rutkowski' => 'marc',
    'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

foreach ($collections as $name => $file) {
    // Load the XML source
    $xml = new DOMDocument;
    $xml->load('collection_' . $file . '.xml');

    $proc->setParameter('', 'owner', $name);
    $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

XSLTProcessor->transformToDoc()

(no version information, might be only in CVS)

XSLTProcessor->transformToDoc() -- Transform to a DOMDocument

Descrizione

class XSLTProcessor {

DOMDocument transformToDoc ( DOMNode doc )

}

Transforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor->importStylesheet() method.

Elenco dei parametri

doc

The node to be transformed.

Valori restituiti

The resulting DOMDocument or FALSE on error.

Esempi

Esempio 1. Transforming to a DOMDocument

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

Il precedente esempio visualizzerà:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

XSLTProcessor->transformToURI()

(no version information, might be only in CVS)

XSLTProcessor->transformToURI() -- Transform to URI

Descrizione

class XSLTProcessor {

int transformToURI ( DOMDocument doc, string uri )

}

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor->importStylesheet() method.

Elenco dei parametri

doc

The transformed document.

uri

Valori restituiti

Returns the number of bytes written or FALSE if an error occurred.

Esempi

Esempio 1. Transforming to a HTML file

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

XSLTProcessor->transformToXML()

(no version information, might be only in CVS)

XSLTProcessor->transformToXML() -- Transform to XML

Descrizione

class XSLTProcessor {

string transformToXML ( DOMDocument doc )

}

Transforms the source node to a string applying the stylesheet given by the XSLTProcessor->importStylesheet() method.

Elenco dei parametri

doc

The transformed document.

Valori restituiti

The result of the transformation as a string or FALSE on error.

Esempi

Esempio 1. Transforming to a string

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo $proc->transformToXML($xml);

?>

Il precedente esempio visualizzerà:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

<h1>Fight for your mind</h1><h2>by Ben Harper - 1995</h2><hr>
<h1>Electric Ladyland</h1><h2>by Jimi Hendrix - 1997</h2><hr>

CLXV. Funzioni XSLT

Introduzione

Questo modulo PHP consiste in un processore, basato su API indipendenti, per le trasformazioni XSLT. Attualmente questo modulo supporta la libreria Sablotron di Ginger Alliance. E' previsto di estendere il supporto ad altre librerie, quali Xalan o le librerie libxslt.

XSLT (Extensible Stylesheet Language (XSL) Transformations) è un linguaggio per trasformare documenti XML in altri documenti XML. E' uno standard definito dal World Wide Web consortium (W3C). Informazioni circa l' XSLT e le relative tecnologie possono essere trovate su http://www.w3.org/TR/xslt.

Nota: Questa estensione è differente dall'estensione sablotron distribuita con le versioni del PHP precedenti PHP 4.1, attualmente è supportata nel PHP 4.1 solo la nuova estensione XSLT. Se hai bisogno di supporto per le vecchie estensioni, fai la tua domanda sulla mailing list php-general@lists.php.net.

Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.

Nota: Se occorre il supporto xslt in PHP 5 utilizzare il modulo XSL.


Requisiti

Questo modulo utilizza le librerie Sablotron e expat, che possono essere reperite all'indirizzo http://www.gingerall.com/. E' disponibile sia la versione binaria sia la versione con i sorgenti.


Installazione

Nei sistemi UNIX, eseguire configure con le opzioni --enable-xslt --with-xslt-sablot. La libreria Sablotron deve essere installata in una posizione accessibile al compilatore.

Accertarsi di utilizzare per il PHP le medesime librerie utilizzate per Sablotron. I parametri di configurazione sono: --with-expat-dir=DIR --with-iconv-dir=DIR. Quando si chiede supporto, ricordarsi di citare sempre queste impostazioni, e dove sono installate altre versioni di queste librerie nel sistema. Ovviemente fornire i numeri di versione.

Attenzione

Accertarsi che la libreria Sablot sia compilata con -lstdc++ altrimenti potrebbe fallire il processo di configurazione oppure il PHP non essere in grado di caricare la libreria.

Supporto per JavaScript E-XSLT: Se si compila Sablotron con il supporto JavaScript, occorre indicare il parametro: --with-sablot-js=DIR.

Nota per gli utenti Win32: Per potere abilitare questo modulo sui sistemi Windows, occorre copiare diversi file dalla directory PHP/Win32 del rilascio di PHP alla directory SYSTEM32 della macchina. (Es: C:\WINNT\SYSTEM32 oppure C:\WINDOWS\SYSTEM32). In PHP <= 4.2.0 copiare sablot.dll e expat.dll nella cartella SYSTEM32. In PHP >= 4.2.1 copiare sablot.dll, expat.dll e iconv.dll nella cartella SYSTEM32.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

XSLT_OPT_SILENT (integer)

Rimuove i messaggi di log e di errore. Questa è una generica opzione che potrà essere aggiunta in futuro.

XSLT_SABOPT_PARSE_PUBLIC_ENTITIES (integer)

Indica a Sablotron di considerare tutte le entità pubbliche. Per default è impostata a off.

XSLT_SABOPT_DISABLE_ADDING_META (integer)

Non aggiungere i tag "Content-Type" nell'output HTML. Il default viene impostato in fase di compila di Sablotron.

XSLT_SABOPT_DISABLE_STRIPPING (integer)

Sopprime la rimozione degli spazi (solo sui file di dati).

XSLT_SABOPT_IGNORE_DOC_NOT_FOUND (integer)

Considera non risolti i documenti (la funzione document() ) non letali.

XSLT_SABOPT_FILES_TO_HANDLER (integer)

XSLT_ERR_UNSUPPORTED_SCHEME (integer)

Codice di errore restituito da scheme handlers.

Sommario
xslt_backend_info --  Returns the information on the compilation settings of the backend
xslt_backend_name --  Returns the name of the backend
xslt_backend_version --  Returns the version number of Sablotron
xslt_create -- Crea un nuovo processore XSLT
xslt_errno -- Restituisce un numero di errore
xslt_error -- Returns an error string
xslt_free -- Libera un processore XSLT
xslt_getopt --  Get options on a given xsl processor
xslt_process -- Esegue una trasformazione XSLT
xslt_set_base -- Imposta l'URI di base per tuttte le trasformazioni XSLT
xslt_set_encoding -- Imposta l'encoding per il parsing dei documenti XML
xslt_set_error_handler -- Imposta un error handler per un processore XSLT
xslt_set_log -- Imposta il file di log per scrivere i messaggi di log
xslt_set_object --  Sets the object in which to resolve callback functions
xslt_set_sax_handler -- Imposta un handler SAX per un processore XSLT
xslt_set_sax_handlers --  Imposta gli handler SAX da richiamare quando il document XML viene processato
xslt_set_scheme_handler -- Imposta lo schema dell'handler per un processore XSLT
xslt_set_scheme_handlers -- Imposta lo schema degli handler per un processore XSLT
xslt_setopt --  Set options on a given xsl processor

xslt_backend_info

(PHP 4 >= 4.3.0, PECL)

xslt_backend_info --  Returns the information on the compilation settings of the backend

Description

string xslt_backend_info ( void )

xslt_backend_info() returns a string with information about the compilation setting of the backend or an error string when no information available.

xslt_backend_name

(PHP 4 >= 4.3.0, PECL)

xslt_backend_name --  Returns the name of the backend

Description

string xslt_backend_name ( void )

xslt_backend_name() will always return Sablotron.

Esempi

Esempio 1. xslt_backend_name() example

<?php

echo xslt_backend_name(); // Sablotron

?>

xslt_backend_version

(PHP 4 >= 4.3.0, PECL)

xslt_backend_version --  Returns the version number of Sablotron

Description

string xslt_backend_version ( void )

xslt_backend_version() returns the version number of Sablotron if available, FALSE otherwise.

Esempi

Esempio 1. xslt_backend_version() example

<?php

echo xslt_backend_version(); // 0.98 for example

?>

xslt_create

(PHP 4 >= 4.0.3, PECL)

xslt_create -- Crea un nuovo processore XSLT

Descrizione

resource xslt_create ( void )

Crea e restituisce un nuovo processore XSLT risorsa per la modifica dalle altre funzioni XSLT.

Esempi

Esempio 1. Esempio di utilizzo di xslt_create()

<?php
function xml2html($xmldata, $xsl)
{
    /* $xmldata -> your XML */
    /* $xsl -> XSLT file */
 
    $path = 'include';
    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', "$path/$xsl", NULL, $arguments);
 
    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}
?>

Vedere anche:

xslt_free().

xslt_errno

(PHP 4 >= 4.0.3, PECL)

xslt_errno -- Restituisce un numero di errore

Descrizione

int xslt_errno ( resource xh )

Restituisce un codice di errore che descrive l'ultimo errore successo sul processore XSLT indicato.

Vedere anche:

xslt_error().

xslt_error

(PHP 4 >= 4.0.3, PECL)

xslt_error -- Returns an error string

Description

string xslt_error ( resource xh )

Returns a string describing the last error that occurred on the passed XSLT processor.

Esempi

Esempio 1. Handling errors using the xslt_error() and xslt_errno() functions.

<?php

$xh = xslt_create();
$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
if (!$result) {
    die(sprintf("Cannot process XSLT document [%d]: %s", 
                xslt_errno($xh), xslt_error($xh)));
}

echo $result;

xslt_free($xh);
?>

Vedere anche:

xslt_errno().

xslt_free

(PHP 4 >= 4.0.3, PECL)

xslt_free -- Libera un processore XSLT

Descrizione

void xslt_free ( resource xh )

Libera il processore XSLT identificato dall'handle dato.

Vedere anche:

xslt_create()

xslt_getopt

(PHP 4 >= 4.3.0, PECL)

xslt_getopt --  Get options on a given xsl processor

Description

int xslt_getopt ( resource processor )

xslt_getopt() returns the options on the given processor.

Vedere anche:

xslt_setopt().

xslt_process

(PHP 4 >= 4.0.3, PECL)

xslt_process -- Esegue una trasformazione XSLT

Descrizione

mixed xslt_process ( resource xh, string xmlcontainer, string xslcontainer [, string resultcontainer [, array arguments [, array parameters]]] )

La funzione xslt_process() è una delle più importanti della nuova estensione XSLT. Permette di eseguire una trasformazione XSLT usando quasi ogni tipo di fonte per l'input - i contenitori. Questa è un completamento mediante l'uso dell'argomento buffers -- un concetto preso dal processore XSLT Sablotron (attualmente l'unico processore XSLT supportato da questa estensione). Il contenituore di input di default è il nome del file del documento trasformato. Se il contenitore di destinaizone non viene fornito, ad esempio è impostato a NULL - alla la funzione restituisce il risultato.

Avvertimento

Questa funzione ha modifica i propri argomenti dalla versione 4.0.6. Infatti non fornire più il contenuto XML o XSL come secondi e terzi argomenti, poichè questi creano un segmentation fault in Sablotron fino alla versione 0.95 inclusa.

I contenitori possono essere impostati anche tramite la matrice $arguments (vedere più avanti).

Il più semplice tipo di trasformazione con la funzione xslt_process() è la trasformazione di un file XML con un file XSLT, mettendo il risultato in un terzo file contenente un nuovo documento XML (o HTML). Fare questo con Sablotron è davvero molto semplice...

Esempio 1. Uso di xslt_process() per trasformare un file XML e un file XSL in un nuovo file XML

<?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
if (xslt_process($xh, 'sample.xml', 'sample.xsl', 'result.xml')) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into result.xml";
    echo ", result.xml has the following contents\n<br />\n";
    echo "<pre>\n";
    readfile('result.xml');
    echo "</pre>\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  result.xml the reason is that " . xslt_error($xh) . " and the ";
    echo "error code is " . xslt_errno($xh);
}

xslt_free($xh);

?>

Mentre questa funzionalità è importante, a volte, specialmente in un ambiente web, si vorrebbe avere la possibilità di scrivere a video il risultato direttamente. Quindi, se si omette il terzo argomento alla funzione xslt_process() (o si inserisce il valore NULL per l'argomento), lo script restituirà automaticamente il valore della trasformazione dell'XSLT, invece di scriverlo in un file...

Esempio 2. Uso di xslt_process() per trasformare un file XML e uno XSL in una variabile contenente i dati XML restituiti

<?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document, returning the result into the $result variable
$result = xslt_process($xh, 'sample.xml', 'sample.xsl');
if ($result) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    echo " variable, the \$result variable has the following contents\n<br />\n";
    echo "<pre>\n";
    echo $result;
    echo "</pre>\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  the \$result variable the reason is that " . xslt_error($xh) . 
    echo " and the error code is " . xslt_errno($xh);
}

xslt_free($xh);

?>

I due casi sopra sono i due casi più semplici che ci sono quando c'è una trasformazione XSLT e c'è da dire che dovreste essere per la maggior parte delle volte in questi casi, ma, a volte, puoi prendere il tuo codice XML e XSLT da fonti esterne, come database e socket. In questi casi, avrai i dati XML e/o XSLT in una variabile -- nella produzione di applicazioni l'overhead per scaricare questo codice al file potrebbere essere eccessivo. Qui la sinstassi degli argomenti dell'XSLT ci aiuta. Invece dei file come argomenti XML e XSLT alla funzione xslt_process(), puoi specificare l' "argument place holders" il quale è poi sostituito dal valore dato nell'argomento dell'array (il quinto parametro della funzione xslt_process()). Di seguito c'è un esempio del processo di inserimento di codice XML e XSLT senza l'ausilio di file.

Esempio 3. Uso di xslt_process() per trasformare una variabile contenente dati XML e una variabile contenente dati XSL in una variabile contenente i dati XML risultanti

<?php
// $xml and $xsl contain the XML and XSL data

$arguments = array(
     '/_xml' => $xml,
     '/_xsl' => $xsl
);

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); 
if ($result) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    echo " variable, the \$result variable has the following contents\n<br />\n";
    echo "<pre>\n";
    echo $result;
    echo "</pre>\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  the \$result variable the reason is that " . xslt_error($xh) . 
    echo " and the error code is " . xslt_errno($xh);
}
xslt_free($xh);
?>

Finalmente, l'ultimo argomento della funzione xslt_process() rappresenta una matrice di qualsiasi parametro di alto livello che si desidera passare al documento XSLT. Questi parametri possono essere referenziati dal file XSL utilizzando l'istruzione <xsl:param name="parameter_name">. I parametri devono avere la codifica UTF-8 ed i rispettivi valori devono essere interpretati come stringhe dal processore Sablotron. In altre parole non si possono passare come parametri al documento XSLT dei node-set.

Esempio 4. Passaggio di variabili PHP al file XSL

<?php
 
// XML string
$xml = '<?xml version="1.0"?>
<para>
 change me
</para>';
 
// stringa XSL 
$xsl = '
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no"
 omit-xml-declaration="yes"  media-type="text/html"/>
 <xsl:param name="myvar"/>
 <xsl:param name="mynode"/>
 <xsl:template match="/">
My PHP variable : <xsl:value-of select="$myvar"/><br />
My node set : <xsl:value-of select="$mynode"/>
 </xsl:template>
</xsl:stylesheet>';
 
 
$xh = xslt_create();
 
// Il secondo parametro sarà interpretato come stringa
$parameters = array (
  'myvar' => 'test',
  'mynode' => '<foo>bar</foo>'
);
 
$arguments = array (
  '/_xml' => $xml,
  '/_xsl' => $xsl
);
 
echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments, $parameters);
 
?>

Il precedente esempio visualizzerà:

My PHP variable : test<br>
My node set : &lt;foo&gt;bar&lt;/foo&gt;

Nota: Please note that file:// is needed in front of path if you use Windows.

xslt_set_base

(PHP 4 >= 4.0.5, PECL)

xslt_set_base -- Imposta l'URI di base per tuttte le trasformazioni XSLT

Descrizione

void xslt_set_base ( resource xh, string uri )

Imposta l'URI di base per tutte le trasformazioni XSLT, l'URI di base è usato con le istruzioni Xpath per la risoluzione di document() e di altri comandi che accedono a risorse esterne. Viene utilizzato, inoltre, per risolvere gli URI degli elementi <xsl:include> ed <xsl:import>

Dalla versione 4.3, la base di default per l'URI è la directory di esecuzione dello script. Infatti è la directory indicata dalla costante __FILE__. Prima delle versione 4.3, la base di default per l'URI era meno prevedibile.

Nota: Please note that file:// is needed in front of path if you use Windows.

xslt_set_encoding

(PHP 4 >= 4.0.5, PECL)

xslt_set_encoding -- Imposta l'encoding per il parsing dei documenti XML

Descrizione

void xslt_set_encoding ( resource xh, string encoding )

Imposta l'output encoding per le trasformazioni XSLT. Quando è usato il Sablotron backend quasta opzione è disponibile solo quando compili Sablotron con il supporto per l'encoding.

xslt_set_error_handler

(PHP 4 >= 4.0.4, PECL)

xslt_set_error_handler -- Imposta un error handler per un processore XSLT

Descrizione

void xslt_set_error_handler ( resource xh, mixed handler )

Imposta una funzione di error handler per il processore XSLT dato da xh, questa funzione sarà richiamata quando ha luogo un errore nella trasformazione XSLT (questa funzione è anche richiamata per le nuove notizie dallo script).

La funzione utente deve ricevere quattro parametri: il processore XSLT, il livello di errore, il codice di errore ed una matrice di messaggi. La funzione potrebbe essere rappresentata come: error_handler ( resource xh, int error_level, int error_code, array messages )

Esempi

Esempio 1. Esempio di uso di xslt_set_error_handler()

<?php
 
// Il nostro gestore degli errori XSLT
function xslt_error_handler($handler, $errno, $level, $info)
{
  // Per ora visualizza i parametri
  var_dump(func_get_args());
}
 
// contenuto XML:
$xml='<?xml version="1.0"?>
<para>
 oops, I misspelled the closing tag
</pata>';
 
// Contenuto XSL:
$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
   <strong><xsl:value-of select="para"/></strong>
</xsl:template>
</xsl:stylesheet>';
 
$xh = xslt_create();
 
xslt_set_error_handler($xh, "xslt_error_handler");
 
echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl',
                  NULL, array("/_xml" => $xml, "/_xsl" => $xsl));
 
?>

Il precedente esempio visualizzerà qualcosa simile a:

array(4) {
  [0]=>
  resource(1) of type (XSLT Processor)
  [1]=>
  int(3)
  [2]=>
  int(0)
  [3]=>
  array(6) {
    ["msgtype"]=>
    string(5) "error"
    ["code"]=>
    string(1) "2"
    ["module"]=>
    string(9) "Sablotron"
    ["URI"]=>
    string(9) "arg:/_xml"
    ["line"]=>
    string(1) "4"
    ["msg"]=>
    string(34) "XML parser error 7: mismatched tag"
  }
}

Vedere anche:

Vedere xslt_set_object() se si desidera utilizzare come handler un medoto di un oggetto.

xslt_set_log

(PHP 4 >= 4.0.6, PECL)

xslt_set_log -- Imposta il file di log per scrivere i messaggi di log

Descrizione

void xslt_set_log ( resource xh [, mixed log] )

xh

Un riferimento all'XSLT parser.

log

Questo parametro può essere un valore booleano che può essere settato su on o off oppure una stringa contenente il file di log incluso dei log di errore.

Questa funzione permette di impostare il file nel quale vuoi i messaggi di log di XSLT, i messaggi di log di XSLT sono differenti dagli altri messaggi di errore, nei quali messaggi di log non siano presenti i messaggi di errore ma piuttosto messaggi inerenti allo stato del processore di XSLT. Sono usati per il debugging dell'XSLT, quando qualcosa va storto.

Per default il logging è disabilitato, ma se vuoi abilitarlo devi prima richiamare xslt_set_log() con un parametro booleano il quale abilita il logging, poi se vuoi impostare il file di log per fare il debug, devi poi passargli una stringa contenente il nome del file:

Nota: Please note that file:// is needed in front of path if you use Windows.

Esempi

Esempio 1. Uso delle features del Logging di XSLT

<?php

$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . '/myfile.log');

$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
echo $result;

xslt_free($xh);
?>

xslt_set_object

(PHP 4 >= 4.3.0, PECL)

xslt_set_object --  Sets the object in which to resolve callback functions

Description

bool xslt_set_object ( resource processor, object &obj )

This function allows to use the processor inside an object and to resolve all callback functions in it.

The callback functions can be declared with xml_set_sax_handlers(), xslt_set_scheme_handlers() or xslt_set_error_handler() and are assumed to be methods of object.

Esempi

Esempio 1. Using your own error handler as a method

<?php

class my_xslt_processor {
    
    var $_xh; // our XSLT processor
    
    function my_xslt_processor()
    {
        $this->_xh = xslt_create();

        // Make $this object the callback resolver
        xslt_set_object($this->_xh, $this);

        // Let's handle the errors
        xslt_set_error_handler($this->_xh, "my_xslt_error_handler");
    }

    function my_xslt_error_handler($handler, $errno, $level, $info)
    {
        // for now, let's just see the arguments
        var_dump(func_get_args());
    }
}

?>

xslt_set_sax_handler

(4.0.3 - 4.0.6 only)

xslt_set_sax_handler -- Imposta un handler SAX per un processore XSLT

Descrizione

void xslt_set_sax_handler ( resource xh, array handler )

Imposta una handler SAX sulla risorsa dell'handle data da xh. L'handler SAX può avere un array bi-dimensionale con il formato (tutti gli elementi al livello top sono opzionali):

array(
[document] => 
    array(
        start document handler,
        end document handler
    ),
[element] => 
    array(
        start element handler,
        end element handler
    ),
[namespace] => 
    array(
        start namespace handler,
        end namespace handler
    ),
[comment] => comment handler,
[pi] => processing instruction handler,
[character] => character data handler
)

xslt_set_sax_handlers

(PHP 4 >= 4.0.6, PECL)

xslt_set_sax_handlers --  Imposta gli handler SAX da richiamare quando il document XML viene processato

Descrizione

void xslt_set_sax_handlers ( resource processor, array handler )

xslt_set_sax_handlers() registra gli handlers SAX per il documento, dato processor XSLT.

Il parametro handlers dovrebbe essere una matrice del seguente formato:

<?php
 
$handlers = array(
 
  "document" => array(
    "start_doc",
    "end_doc"),
 
  "element"  => array(
    "start_element",
    "end_element"),
 
  "namespace" => array(
    "start_namespace",
    "end_namespace"),
 
  "comment"   => "comment",
 
  "pi"        => "pi",
 
  "character" => "characters"
 
);
?>

Dove le funzioni seguono la sintassi descritta per lo schema.

Nota: La matrice fornita non richiede di essere completa di tutti i differenti handler agli elementi sax (sebbene possa esserlo), ma richiede solo di essere conforme al formato "handler" => "function" descritto in precedenza.

Chiascuno degli handler SAX sono nel formato:

  • start_doc ( resource processor )

  • end_doc ( resource processor )

  • start_element ( resource processor, string name, array attributes )

  • end_element ( resource processor, string name )

  • start_namespace ( resource processor, string prefix, string uri )

  • end_namespace ( resource processor, string prefix )

  • comment ( resource processor, string contents )

  • pi ( resource processor, string target, string contents )

  • characters ( resource processor, string contents )

L'utilizzo di xslt_set_sax_handlers() non è molto differente rispetto ad un parser SAX tipo xml_parse() nelle trasformazioni xslt_process().

Esempi

Esempio 1. Esempio di uso xslt_set_sax_handlers()

<?php
// Da ohlesbeauxjours at yahoo dot fr
// Questo è un semplice esempio che applica strtoupper()
// sul contenuto di ciascun tag <auteur> e visualizza
// l'albero XML risultante:
 	 
$xml='<?xml version="1.0"?>
<books>
 <book>
  <title>Mme Bovary</title>
  <author>Gustave Flaubert</author>
 </book>
 <book>
  <title>Mrs Dalloway</title>
  <author>Virginia Woolf</author>
 </book>
</books>';
 
$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no" omit-xml-declaration="yes"/>
<xsl:template match="/">
 <xsl:for-each select="books/book">
  <livre>
   <auteur><xsl:value-of select="author/text()"/></auteur>
  </livre>
 </xsl:for-each>
</xsl:template>
</xsl:stylesheet>';
 
// Handlers :
function start_document()
{
  // inizia la lettura del coumento
}
  	 
function end_document()
{
  // fine lettura del documento
}
  	 
function start_element($parser, $name, $attributes)
{
  global $result,$tag;
  $result .= "<". $name . ">";
  $tag = $name;
}
 
function end_element($parser, $name)
{
  global $result;
  $result .= "</" . $name . ">";
}
 
function characters($parser, $data)
{
  global $result,$tag;
  if ($tag == "auteur" ) {
    $data = strtoupper($data);
  }
  $result .= $data;
}
 
// Trasformazione :
$xh = xslt_create();
$handlers = array("document" => array("start_document","end_document"),
   "element" => array("start_element","end_element"),
   "character" => "characters");
 
xslt_set_sax_handlers($xh, $handlers);
xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=>$xml, "/_xsl"=>$xsl));
xslt_free($xh);
?>

Si può anche utilizzare xslt_set_object() per implementare i propri handler in un oggetto.

Esempio 2. Handler orientato agli oggetti

<?php
// Questa è una versione ad oggetti dell'esempi precedente
class data_sax_handler {
 
  var $buffer, $tag, $attrs;
 
  var $_xh;
 
  function data_sax_handler($xml, $xsl)
  {
      // la nostra risorsa xslt
      $this->_xh = xslt_create();
 
      xslt_set_object($this->_xs, $this);
 
      // configura gli handler sax
      $handlers = array(
        "document" => array('start_document', 'end_document'),
        "element" => array('start_element', 'end_element'),
        "character" => 'characters'
      );
 
      xslt_set_sax_handlers($this->_xh, $handlers);
 
      xslt_process($this->_xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=>$xml, "/_xsl"=>$xsl));
      xslt_free($this->_xh);
 
 
  }
 
  function start_document()
  {
        // inizia la lettura del documento
  }
 
  function end_document() {
        // completa la lettura del documento
  }
	 
  function start_element($parser, $name, $attributes) {
        $this->tag = $name;
        $this->buffer .= "<" . $name . ">";
        $this->attrs = $attributes;
  }
 
  function end_element($parser, $name)
  {
        $this->tag = '';
        $this->buffer .= "</" . $name . ">";
  }
 
  function characters($parser, $data)
  {
    if ($this->tag == 'auteur') {
          $data = strtoupper($data);
    }
    $this->buffer .= $data;
  }
 
  function get_buffer() {
    return $this->buffer;
  }
	 
}
  	 
$exec = new data_sax_handler($xml, $xsl);
 
?>

Entrambi gli esempi visualizzeranno:

<livre>
   <auteur>GUSTAVE FLAUBERT</auteur>
</livre>
<livre>
   <auteur>VIRGINIA WOOLF</auteur>
</livre>

xslt_set_scheme_handler

(4.0.5 - 4.0.6 only)

xslt_set_scheme_handler -- Imposta lo schema dell'handler per un processore XSLT

Descrizione

void xslt_set_scheme_handler ( resource xh, array handler )

Imposta lo schema dell'handler sulla risorsa dell'handle data da xh. Lo schema dell'handler può essere un array con il formato (tutti gli elementi sono opzionali):

array(
[get_all] => get all handler,
[open] => open handler,
[get] => get handler,
[put] => put handler,
[close] => close handler
)

xslt_set_scheme_handlers

(PHP 4 >= 4.0.6, PECL)

xslt_set_scheme_handlers -- Imposta lo schema degli handler per un processore XSLT

Descrizione

void xslt_set_scheme_handlers ( resource processor, array handler )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xslt_setopt

(PHP 4 >= 4.3.0, PECL)

xslt_setopt --  Set options on a given xsl processor

Description

mixed xslt_setopt ( resource processor, int newmask )

xslt_setopt() sets the options specified by newmask on the given processor. Returns the number of previous mask is possible, TRUE otherwise, FALSE in case of an error.

newmask is a bitmask constructed with the following constants:

  • XSLT_SABOPT_PARSE_PUBLIC_ENTITIES - Tell the processor to parse public entities. By default this has been turned off.

  • XSLT_SABOPT_DISABLE_ADDING_META - Do not add the meta tag "Content-Type" for HTML output. The default is set during the compilation of the processor.

  • XSLT_SABOPT_DISABLE_STRIPPING - Suppress the whitespace stripping (on data files only).

  • XSLT_SABOPT_IGNORE_DOC_NOT_FOUND - Consider unresolved documents (the document() function) non-lethal.

Esempi

Esempio 1. xslt_setopt() Example

<?php

$xh = xslt_create();

// Tell Sablotron to process public entities
xslt_setopt($xh, XSLT_SABOPT_PARSE_PUBLIC_ENTITIES);

// Let's also ask him to suppress whitespace stripping
xslt_setopt($xh, xslt_getopt($xh) | XSLT_SABOPT_DISABLE_STRIPPING);

?>

Vedere anche:

xslt_getopt().

CLXVI. YAZ Functions

Introduzione

This extension offers a PHP interface to the YAZ toolkit that implements the Z39.50 Protocol for Information Retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.

The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various RDB APIs that are available for PHP. This means that sessions are stateless but shared among users, thus saving the connect and initialize phase steps in most cases.

YAZ is available at http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at http://www.indexdata.dk/phpyaz/.

Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.


Installazione

Compile YAZ (ANSI/NISO Z39.50 support) and install it. Build PHP with your favourite modules and add option --with-yaz[=DIR]. Your task is roughly the following:

Esempio 1. YAZ compilation

gunzip -c php-4.3.X.tar.gz|tar xf -
gunzip -c yaz-2.0.tar.gz|tar xf -
cd yaz-2.0
./configure --prefix=/usr
make
make install
cd ../php-4.3.X.
./configure --with-yaz=/usr/bin
make
make install

If you are using YAZ as a shared extension, add (or uncomment) the following line in php.ini on Unix:
extension=php_yaz.so
And for Windows:
extension=php_yaz.dll

On Windows, php_yaz.dll depend on yaz.dll. You'll find yaz.dll in sub directory dlls in the Win32 zip archive. Copy yaz.dll to a directory in your PATH environment (c:\winnt\system32 or c:\windows\system32).

Avvertimento

Il modulo IMAP non può essere utilizzato in congiunzione con i moduli recode, YAZ oppure Cyrus. Poichè questi moduli condividono i medesimi simboli interni.

Nota: The above problem is solved in version 2.0 of YAZ.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. YAZ configuration options

NameDefaultChangeableChangelog
yaz.max_links"100"PHP_INI_ALLAvailable since PHP 4.3.0.
yaz.log_fileNULLPHP_INI_ALLAvailable since PHP 4.3.0.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.

The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in array host.

Esempio 2. Parallel searching using Yaz

<?php
$host=$_REQUEST[host];
$query=$_REQUEST[query];
$num_hosts = count($host);
if (empty($query) || count($host) == 0) {
    echo '<form method="get">
    <input type="checkbox"
    name="host[]" value="bagel.indexdata.dk/gils" />
        GILS test
    <input type="checkbox"
    name="host[]" value="localhost:9999/Default" />
        local test
    <input type="checkbox" checked="checked"
    name="host[]" value="z3950.loc.gov:7090/voyager" />
        Library of Congress
    <br />
    RPN Query:
    <input type="text" size="30" name="query" />
    <input type="submit" name="action" value="Search" />
    </form>
    ';        
} else {
    echo 'You searched for ' . htmlspecialchars($query) . '<br />';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
	yaz_syntax($id[$i], "usmarc");
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $query);
    }
    yaz_wait();
    for ($i = 0; $i < $num_hosts; $i++) {
        echo '<hr />' . $host[$i] . ':';
        $error = yaz_error($id[$i]);
        if (!empty($error)) {
            echo "Error: $error";
        } else {
            $hits = yaz_hits($id[$i]);
            echo "Result Count $hits";
        }
        echo '<dl>';
        for ($p = 1; $p <= 10; $p++) {
            $rec = yaz_record($id[$i], $p, "string");
            if (empty($rec)) continue;
            echo "<dt><b>$p</b></dt><dd>";
            echo nl2br($rec);
            echo "</dd>";
        }
        echo '</dl>';
    }
}
?>

Sommario
yaz_addinfo -- Returns additional error information
yaz_ccl_conf -- Configure CCL parser
yaz_ccl_parse -- Invoke CCL Parser
yaz_close -- Close YAZ connection
yaz_connect --  Prepares for a connection to a Z39.50 server
yaz_database --  Specifies the databases within a session
yaz_element --  Specifies Element-Set Name for retrieval
yaz_errno -- Returns error number
yaz_error -- Returns error description
yaz_es_result --  Inspects Extended Services Result
yaz_get_option -- Returns value of option for connection
yaz_hits -- Returns number of hits for last search
yaz_itemorder --  Prepares for Z39.50 Item Order with an ILL-Request package
yaz_present --  Prepares for retrieval (Z39.50 present)
yaz_range --  Specifies a range of records to retrieve
yaz_record -- Returns a record
yaz_scan_result -- Returns Scan Response result
yaz_scan -- Prepares for a scan
yaz_schema --  Specifies schema for retrieval
yaz_search -- Prepares for a search
yaz_set_option -- Sets one or more options for connection
yaz_sort -- Sets sorting criteria
yaz_syntax --  Specifies the preferred record syntax for retrieval
yaz_wait -- Wait for Z39.50 requests to complete

yaz_addinfo

(PHP 4 >= 4.0.1, PECL)

yaz_addinfo -- Returns additional error information

Descrizione

string yaz_addinfo ( resource id )

Returns additional error information for the last request on the server.

With some servers, this function may return the same string as yaz_error().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

Valori restituiti

A string containing additional error information or an empty string if the last operation was successful or if no additional information was provided by the server.

Vedere anche:

yaz_error()
yaz_errno()

yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL)

yaz_ccl_conf -- Configure CCL parser

Descrizione

void yaz_ccl_conf ( resource id, array config )

This function configures the CCL query parser for a server with definitions of access points (CCL qualifiers) and their mapping to RPN.

To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

config

An array of configuration. Each key of the array is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN.

The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.

Additional information can be found on the CCL page.

Valori restituiti

No value is returned.

Esempi

In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is the connection ID.

Esempio 1. CCL configuration

<?php
$fields = array(
  "ti" => "1=4",
  "au"   => "1=1",
  "isbn" => "1=7"
);
yaz_ccl_conf($id, $fields);
?>

Vedere anche:

yaz_ccl_parse()

yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL)

yaz_ccl_parse -- Invoke CCL Parser

Descrizione

bool yaz_ccl_parse ( resource id, string query, array &result )

This function invokes a CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search.

To define a set of valid CCL fields call yaz_ccl_conf() prior to this function.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

query

The CCL FIND query.

result

If the function was executed successfully, this will be an array containing the valid RPN query under the key rpn.

Upon failure, three indexes are set in this array to indicate the cause of failure:

  • errorcode - the CCL error code (integer)

  • errorstring - the CCL error string

  • errorpos - approximate position in query of failure (integer is character position)

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. CCL Parsing

We will try to search using CCL. In the example below, $ccl is a CCL query.

<?php

yaz_ccl_conf($id, $fields);  // see example for yaz_ccl_conf
if (!yaz_ccl_parse($id, $ccl, &$cclresult)) {
    echo 'Error: ' . $cclresult["errorstring"];
} else {
    $rpn = $cclresult["rpn"];
    yaz_search($id, "rpn", $rpn);
}
?>

yaz_close

(PHP 4 >= 4.0.1, PECL)

yaz_close -- Close YAZ connection

Descrizione

bool yaz_close ( resource id )

Closes the connection given by parameter id.

Nota: This function will only close a non-persistent connection opened by setting the persistent option to FALSE with yaz_connect().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

yaz_connect()

yaz_connect

(PHP 4 >= 4.0.1, PECL)

yaz_connect --  Prepares for a connection to a Z39.50 server

Descrizione

mixed yaz_connect ( string zurl [, mixed options] )

This function returns a connection resource on success, zero on failure.

yaz_connect() prepares for a connection to a Z39.50 server. This function is non-blocking and does not attempt to establish a connection - it merely prepares a connect to be performed later when yaz_wait() is called.

Nota: The YAZ proxy is a freely available Z39.50 proxy.

Elenco dei parametri

zurl

A string that takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used.

options

If given as a string, it is treated as the Z39.50 V2 authentication string (OpenAuth).

If given as an array, the contents of the array serves as options.

user

Username for authentication.

group

Group for authentication.

password

Password for authentication.

cookie

Cookie for session (YAZ proxy).

proxy

Proxy for connection (YAZ proxy).

persistent

A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.

Nota: If you open a persistent connection, you won't be able to close it later with yaz_close().

piggyback

A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled.

Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 servers do not support piggyback or they ignore element set names. For those, piggyback should be disabled.

charset

A string that specifies character set to be used in Z39.50 language and character set negotiation. Use strings such as: ISO-8859-1, UTF-8, UTF-16.

Most Z39.50 servers do not support this feature (and thus, this is ignored). Many servers use the ISO-8859-1 encoding for queries and messages. MARC21/USMARC records are not affected by this setting.

Valori restituiti

A connection resource on success, FALSE on error.

Log delle modifiche

VersioneDescrizione
4.1.0 The parameter options was added.

Vedere anche:

yaz_close()

yaz_database

(PHP 4 >= 4.0.6, PECL)

yaz_database --  Specifies the databases within a session

Descrizione

bool yaz_database ( resource id, string databases )

This function allows you to change databases within a session by specifying one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

databases

A string containing one or more databases. Multiple databases are separated by a plus sign +.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_element

(PHP 4 >= 4.0.1, PECL)

yaz_element --  Specifies Element-Set Name for retrieval

Descrizione

bool yaz_element ( resource id, string elementset )

This function sets the element set name for retrieval.

Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved.

Nota: If this function seems effectless, see the description of the piggybacking option in yaz_connect().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

elementset

Most servers support F (for full records) and B (for brief records).

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_errno

(PHP 4 >= 4.0.1, PECL)

yaz_errno -- Returns error number

Descrizione

int yaz_errno ( resource id )

Returns an error number for the server (last request) identified by id.

yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).

Elenco dei parametri

id

The connection resource returned by yaz_connect().

Valori restituiti

Returns an error code. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.

yaz_error

(PHP 4 >= 4.0.1, PECL)

yaz_error -- Returns error description

Descrizione

string yaz_error ( resource id )

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

Valori restituiti

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

yaz_es_result

(PHP 4 >= 4.2.0, PECL)

yaz_es_result --  Inspects Extended Services Result

Descrizione

array yaz_es_result ( resource id )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

yaz_get_option

(PECL)

yaz_get_option -- Returns value of option for connection

Descrizione

string yaz_get_option ( resource id, string name )

Returns the value of the option specified with name.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

name

The option name.

Valori restituiti

Returns the value of the specified option or an empty string if the option wasn't set.

Vedere anche:

The description of yaz_set_option() for available options

yaz_hits

(PHP 4 >= 4.0.1, PECL)

yaz_hits -- Returns number of hits for last search

Descrizione

int yaz_hits ( resource id )

yaz_hits() returns the number of hits for the last search.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

Valori restituiti

Returns the number of hits for the last search or 0 if no search was performed.

yaz_itemorder

(PHP 4 >= 4.0.5, PECL)

yaz_itemorder --  Prepares for Z39.50 Item Order with an ILL-Request package

Descrizione

void yaz_itemorder ( resource id, array args )

This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See this and the specification.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

args

Must be an associative array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.

The ILL-Request parameters are:


protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
      

There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:


package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item
      

Valori restituiti

No value is returned.

yaz_present

(PHP 4 >= 4.0.5, PECL)

yaz_present --  Prepares for retrieval (Z39.50 present)

Descrizione

bool yaz_present ( resource id )

This function prepares for retrieval of records after a successful search.

The yaz_range() function should be called prior to this function to specify the range of records to be retrieved.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_range

(PHP 4 >= 4.0.1, PECL)

yaz_range --  Specifies a range of records to retrieve

Descrizione

void yaz_range ( resource id, int start, int number )

Specifies a range of records to retrieve.

This function should be called before yaz_search() or yaz_present().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

start

Specifies the position of the first record to be retrieved. The records numbers goes from 1 to yaz_hits().

number

Specifies the number of records to be retrieved.

Valori restituiti

No value is returned.

yaz_record

(PHP 4 >= 4.0.1, PECL)

yaz_record -- Returns a record

Descrizione

string yaz_record ( resource id, int pos, string type )

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

pos

The record position. Records positions in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

type

The type specifies the form of the returned record.

Nota: It is the application which is responsible for actually ensuring that the records are returned from the Z39.50/SRW server in the proper format. The type given only specifies a conversion to take place on the client side (in PHP/YAZ).

Besides conversion of the transfer record to a string/array, PHP/YAZ it is also possible to perform a character set conversion of the record. Especially for USMARC/MARC21 that is recommended since these are typically returned in the character set MARC-8 that is not supported by browsers, etc. To specify a conversion, add ; charset=from, to where from is the original character set of the record and to is the resulting character set (as seen by PHP).

string

The record is returned as a string for simple display. In this mode, all MARC records are converted to a line-by-line format since ISO2709 is hardly readable. XML records and SUTRS are returned in their original format. GRS-1 are returned in a (ugly) line-by-line format.

This format is suitable if records are to be displayed in a quick way - for debugging - or because it is not feasible to perform proper display.

xml

The record is returned as an XML string if possible. In this mode, all MARC records are converted to MARCXML. XML records and SUTRS are returned in their original format. GRS-1 is not supported.

This format is similar to string except that MARC records are converted to MARCXML

This format is suitable if records are processed by an XML parser or XSLT processor afterwards.

raw

The record is returned as a string in its original form. This type is suitable for MARC, XML and SUTRS. It does not work for GRS-1.

MARC records are returned as a ISO2709 string. XML and SUTRS are returned as strings.

syntax

The syntax of the record is returned as a string, i.e. USmarc, GRS-1, XML, etc.

database

The name of database associated with record at the position is returned as a string.

array

The record is returned as an array that reflects the GRS-1 structure. This type is suitable for MARC and GRS-1. XML, SUTRS are not supported and if the actual record is XML or SUTRS an empty string will be returned.

The array returned consists of a list corresponding to each leaf/internal node of GRS-1. Each list item consists a sub list with first element path and data (if data is available).

The path which is a string holds a list of each tree component (of the structured GRS-1 record) from root to leaf. Each component is a tag type, tag value pair of the form (type, value

String tags normally has a corresponding tag type 3. MARC can also be returned as an array (they are converted to GRS-1 internally).

Valori restituiti

Returns the record at position pos or an empty string if no record exists at the given position.

If no database record exists at the given position an empty string is returned.

Esempi

Esempio 1. Array for GRS-1 record

Consider this GRS-1 record:
(4,52)Robert M. Pirsig
(4,70)
      (4,90)
            (2,7)Transworld Publishers, ltd.
This record has two nodes at root level. First element at root level is (4,52) [tag type 4, tag value 52], and has data Robert M. Pirsig. Second element at root level (4,70) has a subtree with a single element (4,90). (4,90) has yet another sub tree (2,7) with data Transworld Publishers, ltd..

If this record is present at position $p, then
<?php

$ar = yaz_record($id, $p, "array");
print_r($ar);

?>
will output:
Array
(
    [0] => Array
        (
            [0] => (4,52)
            [1] => Robert M. Pirsig
        )
    [1] => Array
        (
            [0] => (4,70)
        )
    [2] => Array
        (
            [0] => (4,70)(4,90)
        )
    [3] => Array
        (
            [0] => (4,70)(4,90)(2,7)
            [1] => Transworld Publishers, ltd.
        )
)

Esempio 2. Working with MARCXML

The following PHP snippet returns a MARC21/USMARC record as MARCXML. The original record is returned in marc-8 (unknown to most XML parsers), so we convert it to UTF-8 (which all XML parsers must support).
<?php
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");
?>

The record $rec can be processed with the Sablotron XSLT processor as follows:

<?php

$xslfile = 'display.xsl';
$processor = xslt_create();
$parms = array('/_xml' => $rec);
$res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
xslt_free($processor);
$res = preg_replace("'</?html[^>]*>'", '', $res);
echo $res;

?>

For PHP 5 the XSL extension must be used instead of Sablotron XSLT.

yaz_scan_result

(PHP 4 >= 4.0.5, PECL)

yaz_scan_result -- Returns Scan Response result

Descrizione

array yaz_scan_result ( resource id [, array &result] )

yaz_scan_result() returns terms and associated information as received from the server in the last performed yaz_scan().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

result

If given, this array will be modified to hold additional information taken from the Scan Response:

  • number - Number of entries returned

  • stepsize - Step size

  • position - Position of term

  • status - Scan status

Valori restituiti

Returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where the first item is the term, and the second item is the result-count.

yaz_scan

(PHP 4 >= 4.0.5, PECL)

yaz_scan -- Prepares for a scan

Descrizione

void yaz_scan ( resource id, string type, string startterm [, array flags] )

This function prepares for a Z39.50 Scan Request on the specified connection.

To actually transfer the Scan Request to the server and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

type

Currently only type rpn is supported.

startterm

Starting term point for the scan.

The form in which the starting term is specified is given by parameter type.

The syntax this parameter is similar to the RPN query as described in yaz_search(). It consists of zero or more @attr-operator specifications, then followed by exactly one token.

flags

This optional parameter specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags array: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size).

Valori restituiti

No value is returned.

Esempi

Esempio 1. PHP function that scans titles

<?php
function scan_titles($id, $startterm) 
{
  yaz_scan($id, "rpn", "@attr 1=4 " . $startterm);
  yaz_wait();
  $errno = yaz_errno($id);
  if ($errno == 0) {
    $ar = yaz_scan_result($id, &$options);
    echo 'Scan ok; ';
    foreach ($options as $key => $val) {
      echo "$key = $val &nbsp;";
    }
    echo '<br /><table>';
    while (list($key, list($k, $term, $tcount)) = each($ar)) {
      if (empty($k)) continue;
      echo "<tr><td>$term</td><td>$tcount</td></tr>";
    }
    echo '</table>';
  } else {
    echo "Scan failed. Error: " . yaz_error($id) . "<br />";
  }
}
?>

yaz_schema

(PHP 4 >= 4.2.0, PECL)

yaz_schema --  Specifies schema for retrieval

Descrizione

void yaz_schema ( resource id, string schema )

yaz_schema() specifies the schema for retrieval.

This function should be called before yaz_search() or yaz_present().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

schema

Must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ...

Valori restituiti

No value is returned.

yaz_search

(PHP 4 >= 4.0.1, PECL)

yaz_search -- Prepares for a search

Descrizione

bool yaz_search ( resource id, string type, string query )

yaz_search() prepares for a search on the given connection.

Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

type

This parameter represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation.

query

The RPN query is a textual representation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operator precedes the operands. The query string is a sequence of tokens where white space is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.

Tabella 1. RPN Operators

ConstructDescription
@and query1 query2intersection of query1 and query2
@or query1 query2union of query1 and query2
@not query1 query2query1 and not query2
@set nameresult set reference
@attrset set query specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr [set] type=value query applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set.

You can find information about attributes at the Z39.50 Maintenance Agency site.

Nota: If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempi

Esempio 1. Query Examples

You can search for simple terms, like this:
computer
which matches documents where "computer" occur. No attributes are specified.

The query
"knuth donald"
matches documents where "knuth donald" occur (provided that the server supports phrase search).

This query applies two attributes for the same phrase.
@attr 1=1003 @attr 4=1 "knuth donald"
First attribute is type 1 (Bib-1 use), attribute value is 1003 (Author). Second attribute has is type 4 (structure), value 1 (phrase), so this should match documents where Donald Knuth is author.

The query
@and @or a b @not @or c d e
would in infix notation look like (a or b) and ((c or d) not e).

Another, more complex, one:
@attrset gils @and @attr 1=4 art @attr 1=2000 company
The query as a whole uses the GILS attributeset. The query matches documents where art occur in the title (GILS,BIB-1) and in which company occur as Distributor (GILS).

yaz_set_option

(PECL)

yaz_set_option -- Sets one or more options for connection

Descrizione

void yaz_set_option ( resource id, string name, string value )

void yaz_set_option ( resource id, array options )

Sets one or more options on the given connection.

Elenco dei parametri

id

The connection resource returned by yaz_connect().

name or options

May be either a string or an array.

If given as a string, this will be the name of the option to set. You'll need to give it's value.

If given as an array, this will be an associative array (option name => option value).

Tabella 1. PHP/YAZ Connection Options

NameDescription
implementationNameimplementation name of server
implementationVersionimplementation version of server
implementationIdimplementation ID of server
schema schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntax record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
start offset for first record to be retrieved via yaz_search() or yaz_present(). First record is numbered has a start value of 0. Second record has start value 1. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range()
countmaximum number of records to be retrieved via yaz_search() or yaz_present().
elementSetNameelement-set-name for retrieval. Setting this option is equivalent to calling yaz_element().
value

The new value of the option. Use this only if the previous argument is a string.

Valori restituiti

No value is returned.

yaz_sort

(PHP 4 >= 4.1.0, PECL)

yaz_sort -- Sets sorting criteria

Descrizione

void yaz_sort ( resource id, string criteria )

This function sets sorting criteria and enables Z39.50 Sort.

Call this function before yaz_search(). Using this function alone does not have any effect. When used in conjunction with yaz_search(), a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present (yaz_present().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

criteria

A string that takes the form field1 flags1 field2 flags2 where field1 specifies the primary attributes for sort, field2 seconds, etc..

The field specifies either a numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequence of the following characters which may not be separated by any white space.

Sort Flags

a

Sort ascending

d

Sort descending

i

Case insensitive sorting

s

Case sensitive sorting

Valori restituiti

No value is returned.

Esempi

Esempio 1. Sort Criterias

To sort on Bib1 attribute title, case insensitive, and ascending you would use the following sort criteria:
1=4 ia

If the secondary sorting criteria should be author, case sensitive and ascending you would use:
1=4 ia 1=1003 sa

yaz_syntax

(PHP 4 >= 4.0.1, PECL)

yaz_syntax --  Specifies the preferred record syntax for retrieval

Descrizione

void yaz_syntax ( resource id, string syntax )

yaz_syntax() specifies the preferred record syntax for retrieval

This function should be called before yaz_search() or yaz_present().

Elenco dei parametri

id

The connection resource returned by yaz_connect().

syntax

The syntax must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.).

Valori restituiti

No value is returned.

yaz_wait

(PHP 4 >= 4.0.1, PECL)

yaz_wait -- Wait for Z39.50 requests to complete

Descrizione

mixed yaz_wait ( [array &options] )

This function carries out networked (blocked) activity for outstanding requests which have been prepared by the functions yaz_connect(), yaz_search(), yaz_present(), yaz_scan() and yaz_itemorder().

yaz_wait() returns when all servers have either completed all requests or aborted (in case of errors).

Elenco dei parametri

options

An associative array of options:

timeout

Sets timeout in seconds. If a server has not responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.

event

A boolean.

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. In event mode, returns resource or FALSE in case of an error.

CLXVII. YP/NIS Functions

Introduzione

NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and The Linux NIS(YP)/NYS/NIS+ HOWTO. There is also a book called Managing NFS and NIS by Hal Stern.

Nota: 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.


Requisiti

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).


Installazione

To get these functions to work, you have to configure PHP with --enable-yp.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Costanti predefinite

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.

YPERR_BADARGS (integer)

YPERR_BADDB (integer)

YPERR_BUSY (integer)

YPERR_DOMAIN (integer)

YPERR_KEY (integer)

YPERR_MAP (integer)

YPERR_NODOM (integer)

YPERR_NOMORE (integer)

YPERR_PMAP (integer)

YPERR_RESRC (integer)

YPERR_RPC (integer)

YPERR_YPBIND (integer)

YPERR_YPERR (integer)

YPERR_YPSERV (integer)

YPERR_VERS (integer)

Sommario
yp_all --  Traverse the map and call a function on each entry
yp_cat --  Return an array containing the entire map
yp_err_string --  Returns the error string associated with the given error code
yp_errno --  Returns the error code of the previous operation
yp_first --  Returns the first key-value pair from the named map
yp_get_default_domain -- Fetches the machine's default NIS domain
yp_master --  Returns the machine name of the master NIS server for a map
yp_match -- Returns the matched line
yp_next -- Returns the next key-value pair in the named map
yp_order -- Returns the order number for a map

yp_all

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_all --  Traverse the map and call a function on each entry

Description

void yp_all ( string domain, string map, string callback )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

yp_cat

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_cat --  Return an array containing the entire map

Description

array yp_cat ( string domain, string map )

yp_cat() returns all map entries as an array with the maps key values as array indices and the maps entries as array data.

yp_err_string

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_err_string --  Returns the error string associated with the given error code

Description

string yp_err_string ( int errorcode )

yp_err_string() returns the error message associated with the given error code. Useful to indicate what exactly went wrong.

Esempio 1. Example for NIS errors

<?php
    echo "Error: " . yp_err_string(yp_errno());
?>

See also yp_errno().

yp_errno

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)

yp_errno --  Returns the error code of the previous operation

Description

int yp_errno ( void )

yp_errno() returns the error code of the previous operation.

Possible errors are:

1 args to function are bad
2 RPC failure - domain has been unbound
3 can't bind to server on this domain
4 no such map in server's domain
5 no such key in map
6 internal yp server or client error
7 resource allocation failure
8 no more records in map database
9 can't communicate with portmapper
10 can't communicate with ypbind
11 can't communicate with ypserv
12 local domain name not set
13 yp database is bad
14 yp version mismatch
15 access violation
16 database busy

See also yp_err_string().

yp_first

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_first --  Returns the first key-value pair from the named map

Description

array yp_first ( string domain, string map )

yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.

Esempio 1. Example for the NIS first

<?php
$entry = yp_first($domain, "passwd.byname");

$key = key($entry);
$value = $entry[$key];

echo "First entry in this map has key " . $key . " and value " . $value;
?>

See also yp_next() and yp_get_default_domain().

yp_get_default_domain

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_get_default_domain -- Fetches the machine's default NIS domain

Description

string yp_get_default_domain ( void )

yp_get_default_domain() returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.

A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.

Esempio 1. Example for the default domain

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>

yp_master

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_master --  Returns the machine name of the master NIS server for a map

Description

string yp_master ( string domain, string map )

yp_master() returns the machine name of the master NIS server for a map.

Esempio 1. Example for the NIS master

<?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?>

See also yp_get_default_domain().

yp_match

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_match -- Returns the matched line

Description

string yp_match ( string domain, string map, string key )

yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.

Esempio 1. Example for NIS match

<?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

The above code will produce :

joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

See also yp_get_default_domain().

yp_next

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_next -- Returns the next key-value pair in the named map

Description

array yp_next ( string domain, string map, string key )

yp_next() returns the next key-value pair in the named map after the specified key or FALSE.

Esempio 1. Example for NIS next

<?php
$entry = yp_next($domain, "passwd.byname", "joe");

if (!$entry) {
    echo "No more entries found\n";
    echo "<!--" . yp_errno() . ": " . yp_err_string() . "-->";
}

$key = key($entry);

echo "The next entry after joe has key " . $key 
      . " and value " . $entry[$key];
?>

See also yp_first() and yp_get_default_domain().

yp_order

(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)

yp_order -- Returns the order number for a map

Description

int yp_order ( string domain, string map )

yp_order() returns the order number for a map or FALSE.

Esempio 1. Example for the NIS order

<?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?>

See also yp_get_default_domain().

CLXVIII. Funzioni per File Zip (Accesso di Sola Lettura)

Introduzione

Questo modulo abilita l'accesso trasperente in lettura degli archivi compressi con ZIP e dei file in essi contenuti.


Requisiti

Questo modulo usa le funzioni ZZIPlib della libreria di Guido Draheim. Sono richieste le ZZIPlib versione >= 0.10.6.

Notare che ZZIPlib rende disponbili solo un sottogruppo di quelle funzioni disponibili in una implementazione completa dell'algoritmo di compressione ZIP e può solamente leggere i file in formato ZIP. Una normale utility ZIP è richiesta per creare i file ZIP letti da questa libreria.


Installazione

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/zip.

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 utilizzare questo modulo è necessario usare l'opzione di configurazione --with-zip[=DIR] durante la compilazione di PHP.

Per utilizzare queste funzioni, gli utenti Windows dovranno abilitare php_zip.dll all'interno del php.ini. 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: Il supporto Zip precedentemente alla versione 4.1.0 di PHP è sperimentale. Questa sezione riflette l'estensione Zip così come essa esiste in PHP 4.1.0 e successivi.


Configurazione di Runtime

Questa estensione non definisce alcuna direttiva di configurazione in php.ini


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

Questa estensione non definisce alcuna costante.


Esempi

Questo esempio apre un archivio ZIP, legge tutti i file presenti nell'archivio e stampa il contenuto. L'archivio test2.zip usato in questo esempio è uno degli archivi dimostrativi presenti nella distribuzione di ZZIPlib.

Esempio 1. Esempio di Utilizzo Zip

<?php

$zip = zip_open("/tmp/test2.zip");

if ($zip) {

    while ($zip_entry = zip_read($zip)) {
        echo "Nome:                    " . zip_entry_name($zip_entry) . "\n";
        echo "Dimensione File:         " . zip_entry_filesize($zip_entry) . "\n";
        echo "Dimensione Compressa:    " . zip_entry_compressedsize($zip_entry) . "\n";
        echo "Metodo di Compressione:  " . zip_entry_compressionmethod($zip_entry) . "\n";

        if (zip_entry_open($zip, $zip_entry, "r")) {
            echo "Contenuto File:\n";
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}

?>
Sommario
zip_close -- Chiude un archivio Zip
zip_entry_close -- Chiude il puntatore a una directory
zip_entry_compressedsize -- Ottiene la dimensione compressa di una Directory
zip_entry_compressionmethod -- Ottiene il metodo di compressione di una voce directory
zip_entry_filesize -- Ottiene la dimensione attuale di una directory
zip_entry_name -- Ottiene il nome di una directory
zip_entry_open -- Apre una voce directory in lettura
zip_entry_read -- Legge da una directory aperta
zip_open -- Apre un archivio zip
zip_read -- Legge la prossima voce in un archivio file zip

zip_close

(PHP 4 >= 4.1.0, PECL)

zip_close -- Chiude un archivio Zip

Descrizione

void zip_close ( resource zip )

Chiude un file di archivio Zip. Il parametro zip deve essere un archivio zip precedentemente aperto da zip_open().

Questa funzione non restituisce alcun valore.

Vedere anche zip_open() e zip_read().

zip_entry_close

(PHP 4 >= 4.1.0, PECL)

zip_entry_close -- Chiude il puntatore a una directory

Descrizione

void zip_entry_close ( resource zip_entry )

Chiude il puntatore specificato da zip_entry. Il parametro zip_entry deve essere un puntatore valido aperto in precedenza da zip_entry_open().

Questa funzione non restituisce alcun valore.

Vedere anche zip_entry_open() e zip_entry_read().

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PECL)

zip_entry_compressedsize -- Ottiene la dimensione compressa di una Directory

Descrizione

int zip_entry_compressedsize ( resource zip_entry )

Restituisce la dimensione compressa della voce directory specificata da zip_entry. Il parametro zip_entry è un riferimento alla voce directory valido restituito da zip_read().

Vedere anche zip_open() e zip_read().

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PECL)

zip_entry_compressionmethod -- Ottiene il metodo di compressione di una voce directory

Descrizione

string zip_entry_compressionmethod ( resource zip_entry )

Restituisce il metodo di compressione di una voce directory specificata da zip_entry. Il parametro zip_entry è una voce directory valida restituita da zip_read().

Vedere anche zip_open() e zip_read().

zip_entry_filesize

(PHP 4 >= 4.1.0, PECL)

zip_entry_filesize -- Ottiene la dimensione attuale di una directory

Descrizione

int zip_entry_filesize ( resource zip_entry )

Restituisce la dimensione attuale della directory specificata da zip_entry. Il parametro zip_entry è una voce directory valida restituita da zip_read().

Vedere anche zip_open() e zip_read().

zip_entry_name

(PHP 4 >= 4.1.0, PECL)

zip_entry_name -- Ottiene il nome di una directory

Descrizione

string zip_entry_name ( resource zip_entry )

Restituisce il nome di una voce directory specificata da zip_entry. Il parametro zip_entry è una voce directory valida restituita da zip_read().

Vedere anche zip_open() e zip_read().

zip_entry_open

(PHP 4 >= 4.1.0, PECL)

zip_entry_open -- Apre una voce directory in lettura

Descrizione

bool zip_entry_open ( resource zip, resource zip_entry [, string mode] )

Apre una voce directory in lettura in un file zip. Il parametro zip è un resource handle valido restituito da zip_open(). Il parametro zip_entry è una voce directory restituita da zip_read(). Il parametro opzionale mode può essere uno qualunque dei modi specificati nella documentazione relativa a fopen().

Nota: Attualmente, mode viene ignorato e viene sempre usato "rb". Questo è dato dal fatto che il supporto zip in PHP è di tipo sola lettura. Fare riferimento a fopen() per una spiegazione dei vari modi, incluso "rb".

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: A differenza di fopen() e altre funzioni simili, il valore restituito da zip_entry_open() indica solo il risultato dell'operazione e non è necessario per leggere o chiudere la voce relativa alla directory.

Vedere anche zip_entry_read() e zip_entry_close().

zip_entry_read

(PHP 4 >= 4.1.0, PECL)

zip_entry_read -- Legge da una directory aperta

Descrizione

string zip_entry_read ( resource zip_entry [, int length] )

Legge fino a length byte da una directory aperta. Se length non è specificato, allora zip_entry_read() tenterà di leggere 1024 byte. Il parametro zip_entry è una voce directory valida restituita da zip_read().

Nota: Il parametro length deve essere la lunghezza non compressa che si desidera leggere.

Restituisce i dati letti, o FALSE se viene raggiunta la fine del file.

Vedere anche zip_entry_open(), zip_entry_close() e zip_entry_filesize().

zip_open

(PHP 4 >= 4.1.0, PECL)

zip_open -- Apre un archivio zip

Descrizione

resource zip_open ( string filename )

Apre un nuovo archivio zip in lettura. Il parametro filename è il nome del file dell'archivio zip che si desidera aprire.

Restituisce un resource handle da usarsi di seguito con zip_read() e zip_close() o restituisce FALSE se filename non esiste.

Vedere anche zip_read() e zip_close().

zip_read

(PHP 4 >= 4.1.0, PECL)

zip_read -- Legge la prossima voce in un archivio file zip

Descrizione

resource zip_read ( resource zip )

Legge il prossimo file in un archivio su file di tipo zip. Il parametro zip deve essere un archivio zip precedentemente aperto da zip_open().

Restituisce un puntatore alla risorsa directory da usarsi successivamente con le varie funzioni zip_entry_... oppure FALSE se non vi sono più files da leggere.

Vedere anche zip_open(), zip_close(), zip_entry_open() e zip_entry_read().

CLXIX. Funzioni di compressione Zlib

Introduzione

questo modulo permette di leggere e scrivere in modo trasparente i file compressi con gzip (.gz), attraverso versioni di molte delle funzioni del filesystem in grado di operare su file compressi con gzip (ed anche su file non compressi, ma non con i socket).

Nota: La versione 4.0.4 ha introdotto un wrapper di fopen per i file .gz, che permette di usare una speciale URL 'zlib:' per accedere ai file compressi utilizzando le normali funzioni di accesso ai file [ f*() ], semplicemente anteponendo al nome del file o percorso il prefisso 'zlib:' nella chiamata a fopen().

Nella versione 4.3.0, questo prefisso è stato cambiato in 'zlib://' per evitare ambiguità con i nomi di file contenenti il carattere ':'.

Questa funzionalità richiedere una libreria di runtime C che fornisca la funzione fopencookie(). Al momento sembra che la GNU libc sia l'unica libreria a fornire questa funzionalità.


Requisiti

Questo modulo usa le funzioni di zlib di Jean-loup Gailly e Mark Adler. Si deve utilizzare una versione >= 1.0.9 con questo modulo.


Installazione

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

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: Builtin support for zlib on Windows is available with PHP 4.3.0.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

L'estensione zlib permette di comprimere in modo trasparente le pagine on-the-fly, se il browser supporta questa funzionalità. Quindi ci sono due opzioni nel file di configurazione php.ini.

Tabella 1. Opzioni di configurazione di Zlib

NomeDefaultConfigurabile in
zlib.output_compression"Off"PHP_INI_ALL
zlib.output_compression_level"-1"PHP_INI_ALL
zlib.output_handler""PHP_INI_ALL
Per ulteriori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().

Breve descrizione dei parametri di configurazione.

zlib.output_compression boolean/integer

Decide se comprimere le agine in maniera trasparente. Se questa opzione è impostata a "On" in php.ini o nella configurazione di Apache, le pagine vengono compresse se il browser invia un header "Accept-Encoding: gzip" o "deflate". Gli header "Content-Encoding: gzip" (oppure "deflate") e "Vary: Accept-Encoding" sono aggiunti all'output.

Questa opzione accetta anche valori interi oltre ai booleani "On"/"Off", in questo modo è possibile impostare la dimensione del buffer (il default è 4KB).

Nota: output_handler deve essere vuoto se quest opzione è 'On' ! Altrimenti occorre utilizzare zlib.output_handler.

zlib.output_compression_level integer

Livello di compressione utilizzato per la compressione trasparente dell'output.

zlib.output_handler string

Non si possino specificare ulteriori handler dell'output se zlib.output_compression è attivo. Questa impostazione è come output_handler ma con un ordine differente.


Tipi di risorse

Questa estensione non definisce alcun tipo di risorsa.


Costanti predefinite

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.

FORCE_GZIP (integer)

FORCE_DEFLATE (integer)


Esempi

Questo esempio apre un file temporaneo e vi scrive una stringa di prova, quindi stampa il contenuto del file due volte.

Esempio 1. Esempio di Zlib

<?php

$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";

// apre il file in scrittura con la massima compressione
$zp = gzopen($filename, "w9");

// scrive la stringa sul file
gzwrite($zp, $s);

// chiude il file
gzclose($zp);

// apre il file in lettura
$zp = gzopen($filename, "r");

// legge 3 caratteri
echo gzread($zp, 3);

// stampa fino alla fine del file e lo chiude
gzpassthru($zp);
gzclose($zp);

echo "\n";

// apre il file e stampa il contenuto (la seconda volta)
if (readgzfile($filename) != strlen($s)) {
        echo "Errore nelle funzioni zlib!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";

?>
Sommario
gzclose -- Chiude un puntatore a file gz
gzcompress -- Comprime una stringa col metodo COMPRESS
gzdeflate -- Comprime una stringa con il metodo DEFLATE
gzencode -- Crea una stringa compressa con gzip
gzeof -- Test for end-of-file on a gz-file pointer
gzfile -- Read entire gz-file into an array
gzgetc -- Get character from gz-file pointer
gzgets -- Get line from file pointer
gzgetss --  Get line from gz-file pointer and strip HTML tags
gzinflate -- Inflate a deflated string
gzopen -- Open gz-file
gzpassthru --  Output all remaining data on a gz-file pointer
gzputs -- Alias di gzwrite()
gzread -- Binary-safe gz-file read
gzrewind -- Rewind the position of a gz-file pointer
gzseek -- Seek on a gz-file pointer
gztell -- Tell gz-file pointer read/write position
gzuncompress -- Uncompress a compressed string
gzwrite -- Binary-safe gz-file write
readgzfile -- Output a gz-file
zlib_get_coding_type -- Returns the coding type used for output compression

gzclose

(PHP 3, PHP 4, PHP 5)

gzclose -- Chiude un puntatore a file gz

Descrizione

int gzclose ( resource zp )

Il file gz puntato da zp viene chiuso.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Il puntatore al file gz deve essere valido, e deve puntare ad un file già aperto da gzopen().

Vedere anche gzopen().

gzcompress

(PHP 4 >= 4.0.1, PHP 5)

gzcompress -- Comprime una stringa col metodo COMPRESS

Descrizione

string gzcompress ( string dati [, int livello] )

Questa funzione restituisce una versione compressa di dati utilizzanto il formato dati ZLIB, oppure FALSE se si verifica un errore. Il parametro opzionale livello varia tra 0 (nessuna compressione) fino a 9 (compressione massima).

Per i dettagli sull'algoritmo di compressione ZLIB vedere il documento "ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Nota: Questa non è la compressione gzip, che include alcuni dati di header. Vedere gzencode() per la compressione gzip.

Vedere anche gzdeflate(), gzinflate(), gzuncompress(), gzencode().

gzdeflate

(PHP 4 >= 4.0.4, PHP 5)

gzdeflate -- Comprime una stringa con il metodo DEFLATE

Descrizione

string gzdeflate ( string dati [, int livello] )

Questa funzione restituisce una versione compressa di dati utilizzando il formato dati DEFLATE, oppure FALSE se si verifica un errore. Il parametro opzionale livello varia tra 0 (nessuna compressione) fino a 9 (compressione massima). Se livello inon viene specificato, il livello di compressione di default sarà quello di default della libreria zlib.

Per i dettagli sull'algoritmo di compressione DEFLATE vedere il documento "DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

Vedere anche gzinflate(), gzcompress(), gzuncompress(), gzencode().

gzencode

(PHP 4 >= 4.0.4, PHP 5)

gzencode -- Crea una stringa compressa con gzip

Descrizione

string gzencode ( string dati [, int livello [, int encoding_mode]] )

Questa funzione restituisce una versione compressa di dati compatibile con l'output del programma gzip, oppure FALSE se si verifica un errore. Il parametro opzionale livello varia da 0 (nessuna compressione) a 9 (compressione massima), se il livello di compressione non viene specificato verrà adottato quello di default della libreria zlib.

Si può anche impostare FORCE_GZIP (il default) o FORCE_DEFLATE come terzo parametro opzionale encoding_mode. Se si utilizza FORCE_DEFLATE, si ottiene una stringa compressa col DEFLATE standard di zlib (comprendente gli header zlib) dopo l'header del file gzip ma senza il checksum crc32 finale.

Nota: livello è stato aggiunto nel PHP 4.2, prima di questa versione gzencode() aveva solo i parametri dati e (opzionale) encoding_mode.

I dati risultanti contengono gli header e la struttura adeguati per creare un file .gz standard, ad esempio:

Esempio 1. Creare un file gzip

<?php
    $data = implode("", file("bigfile.txt"));
    $gzdata = gzencode($data, 9);
    $fp = fopen("bigfile.txt.gz", "w");
    fwrite($fp, $gzdata);
    fclose($fp);
?>

Per ulteriori informazioni sul formato dei file GZIP, consultare il documento: GZIP file format specification version 4.3 (RFC 1952).

Vedere anche gzcompress(). gzuncompress(), gzdeflate(), gzinflate().

gzeof

(PHP 3, PHP 4, PHP 5)

gzeof -- Test for end-of-file on a gz-file pointer

Descrizione

int gzeof ( resource zp )

Tests the given GZ file pointer for EOF (end-of-file).

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valori restituiti

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

Esempi

Esempio 1. gzeof() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

gzfile

(PHP 3, PHP 4, PHP 5)

gzfile -- Read entire gz-file into an array

Descrizione

array gzfile ( string filename [, int use_include_path] )

This function is identical to readgzfile(), except that it returns the file in an array.

Elenco dei parametri

filename

The file name.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Valori restituiti

An array containing the file, one line per cell.

Esempi

Esempio 1. gzfile() example

<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
    echo $line;
}
?>

Vedere anche:

readgzfile()
gzopen()

gzgetc

(PHP 3, PHP 4, PHP 5)

gzgetc -- Get character from gz-file pointer

Descrizione

string gzgetc ( resource zp )

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valori restituiti

The uncompressed character or FALSE on EOF (unlike gzeof()).

Esempi

Esempio 1. gzgetc() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

Vedere anche:

gzopen()
gzgets()

gzgets

(PHP 3, PHP 4, PHP 5)

gzgets -- Get line from file pointer

Descrizione

string gzgets ( resource zp, int length )

Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

Valori restituiti

The uncompressed string, or FALSE on error.

Esempi

Esempio 1. gzgets() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgets($handle, 4096);
   echo $buffer;
}
gzlose($handle);
?>

gzgetss

(PHP 3, PHP 4, PHP 5)

gzgetss --  Get line from gz-file pointer and strip HTML tags

Descrizione

string gzgetss ( resource zp, int length [, string allowable_tags] )

Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

allowable_tags

You can use this optional parameter to specify tags which should not be stripped.

Valori restituiti

The uncompressed and striped string, or FALSE on error.

Log delle modifiche

VersioneDescrizione
3.0.13 and 4.0b3 allowable_tags was added.

Esempi

Esempio 1. gzgetss() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgetss($handle, 4096);
   echo $buffer;
}
gzlose($handle);
?>

gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate -- Inflate a deflated string

Descrizione

string gzinflate ( string data [, int length] )

This function inflate a deflated string.

Elenco dei parametri

data

The data compressed by gzdeflate().

length

The maximum length of data to decode.

Valori restituiti

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Esempi

Esempio 1. gzinflate() example

<?php
$compressed   = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>

gzopen

(PHP 3, PHP 4, PHP 5)

gzopen -- Open gz-file

Descrizione

resource gzopen ( string filename, string mode [, int use_include_path] )

Opens a gzip (.gz) file for reading or writing.

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

Elenco dei parametri

filename

The file name.

mode

As in fopen() (rb or wb) but can also include a compression level (wb9) or a strategy: f for filtered data as in wb6f, h for Huffman only compression as in wb1h. (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Valori restituiti

Returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns FALSE.

Esempi

Esempio 1. gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

Vedere anche:

gzclose()

gzpassthru

(PHP 3, PHP 4, PHP 5)

gzpassthru --  Output all remaining data on a gz-file pointer

Descrizione

int gzpassthru ( resource zp )

Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.

Nota: You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.

Suggerimento: If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valori restituiti

The number of uncompressed characters read from gz and passed through to the input, or FALSE on error.

Esempi

Esempio 1. gzpassthru() example

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>

gzputs

(PHP 3, PHP 4, PHP 5)

gzputs -- Alias di gzwrite()

Descrizione

This function is an alias of: gzwrite().

gzread

(PHP 3, PHP 4, PHP 5)

gzread -- Binary-safe gz-file read

Descrizione

string gzread ( resource zp, int length )

gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The number of bytes to read.

Valori restituiti

The data that have been read.

Esempi

Esempio 1. gzread() example

<?php
// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen($filename, "r");
$contents = gzread($zd, 10000);
gzclose($zd);
?>

gzrewind

(PHP 3, PHP 4, PHP 5)

gzrewind -- Rewind the position of a gz-file pointer

Descrizione

bool gzrewind ( resource zp )

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Vedere anche:

gzseek()
gztell()

gzseek

(PHP 3, PHP 4, PHP 5)

gzseek -- Seek on a gz-file pointer

Descrizione

int gzseek ( resource zp, int offset )

Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek() then compresses a sequence of zeroes up to the new starting position.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

offset

The seeked offset.

Valori restituiti

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Esempi

Esempio 1. gzseek() example

<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>

Vedere anche:

gztell()
gzrewind()

gztell

(PHP 3, PHP 4, PHP 5)

gztell -- Tell gz-file pointer read/write position

Descrizione

int gztell ( resource zp )

Gets the position of the given file pointer; i.e., its offset into the file stream.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Valori restituiti

The position of the file pointer or FALSE if an error occurs.

gzuncompress

(PHP 4 >= 4.0.1, PHP 5)

gzuncompress -- Uncompress a compressed string

Descrizione

string gzuncompress ( string data [, int length] )

This function uncompress a compressed string.

Elenco dei parametri

data

The data compressed by gzcompress().

length

The maximum length of data to decode.

Valori restituiti

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Esempi

Esempio 1. gzuncompress() example

<?php
$compressed   = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>

gzwrite

(PHP 3, PHP 4, PHP 5)

gzwrite -- Binary-safe gz-file write

Descrizione

int gzwrite ( resource zp, string string [, int length] )

gzwrite() writes the contents of string to the given gz-file.

Elenco dei parametri

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

string

The string to write.

length

The number of uncompressed bytes to write. If supplied, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

Nota: Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Valori restituiti

Returns the number of (uncompressed) bytes written to the given gz-file stream.

Esempi

Esempio 1. gzwrite() example

<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>

Vedere anche:

gzread()
gzopen()

readgzfile

(PHP 3, PHP 4, PHP 5)

readgzfile -- Output a gz-file

Descrizione

int readgzfile ( string filename [, int use_include_path] )

Reads a file, decompresses it and writes it to standard output.

readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.

Elenco dei parametri

filename

The file name. This file will be opened from the filesystem and its contents written to standard output.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Valori restituiti

Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5)

zlib_get_coding_type -- Returns the coding type used for output compression

Descrizione

string zlib_get_coding_type ( void )

Returns the coding type used for output compression.

Valori restituiti

Possible return values are gzip, deflate, or FALSE.

Vedere anche:

The zlib.output_compression directive

VII. PHP and Zend Engine Internals

If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somewhat outdated, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL in addition to the manual.


Capitolo 44. Streams API for PHP Extension Authors

Overview

The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.

The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.

The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. An additional context parameter, accepted by most stream creation functions, is passed to the wrapper's stream_opener method to fine-tune the behavior of the wrapper.

Any stream, once opened, can also have any number of filters applied to it, which process data as it is read from/written to the stream.

Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() or funopen() function, you can even pass any PHP stream to any library that uses ANSI stdio!

Nota: The functions in this chapter are for use in the PHP source code and are not PHP functions. Userland stream functions can be found in the Stream Reference.


Streams Basics

Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:

Esempio 44-1. simple stream example that displays the PHP home page

php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
if (stream) {
    while(!php_stream_eof(stream)) {
        char buf[1024];
        
        if (php_stream_gets(stream, buf, sizeof(buf))) {
            printf(buf);
        } else {
            break;
        }
    }
    php_stream_close(stream);
}

The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.

Tabella 44-1. ANSI stdio equivalent functions in the Streams API

ANSI Stdio FunctionPHP Streams FunctionNotes
fopenphp_stream_open_wrapperStreams includes additional parameters
fclosephp_stream_close 
fgetsphp_stream_gets 
freadphp_stream_readThe nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwritephp_stream_writeThe nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseekphp_stream_seek 
ftellphp_stream_tell 
rewindphp_stream_rewind 
feofphp_stream_eof 
fgetcphp_stream_getc 
fputcphp_stream_putc 
fflushphp_stream_flush 
putsphp_stream_putsSame semantics as puts, NOT fputs
fstatphp_stream_statStreams has a richer stat structure


Streams as Resources

All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:

Esempio 44-2. How to accept a stream as a parameter

PHP_FUNCTION(example_write_hello)
{
    zval *zstream;
    php_stream *stream;
    
    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream))
        return;
    
    php_stream_from_zval(stream, &zstream);

    /* you can now use the stream.  However, you do not "own" the
        stream, the script does.  That means you MUST NOT close the
        stream, because it will cause PHP to crash! */

    php_stream_write(stream, "hello\n");
        
    RETURN_TRUE();
}

Esempio 44-3. How to return a stream from a function

PHP_FUNCTION(example_open_php_home_page)
{
    php_stream *stream;
    
    stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
    
    php_stream_to_zval(stream, return_value);

    /* after this point, the stream is "owned" by the script.
        If you close it now, you will crash PHP! */
}

Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.

Nota: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.

In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the trouble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use php_stream_auto_cleanup().


Streams Common API Reference

Sommario
php_stream_stat_path -- Gets the status for a file or URL
php_stream_stat -- Gets the status for the underlying storage associated with a stream
php_stream_open_wrapper -- Opens a stream on a file or URL
php_stream_read -- Read a number of bytes from a stream into a buffer
php_stream_write -- Write a number of bytes from a buffer to a stream
php_stream_eof -- Check for an end-of-file condition on a stream
php_stream_getc -- Read a single byte from a stream
php_stream_gets -- Read a line of data from a stream into a buffer
php_stream_close -- Close a stream
php_stream_flush -- Flush stream buffers to storage
php_stream_seek -- Reposition a stream
php_stream_tell -- Determine the position of a stream
php_stream_copy_to_stream -- Copy data from one stream to another
php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer
php_stream_make_seekable -- Convert a stream into a stream is seekable
php_stream_cast -- Convert a stream into another form, such as a FILE* or socket
php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket
php_stream_is_persistent -- Determines if a stream is a persistent stream
php_stream_is -- Determines if a stream is of a particular type
php_stream_passthru -- Outputs all remaining data from a stream
php_register_url_stream_wrapper -- Registers a wrapper with the Streams API
php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams API
php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context
php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*
php_stream_filter_register_factory -- Registers a filter factory with the Streams API
php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams API

php_stream_stat_path

(no version information, might be only in CVS)

php_stream_stat_path -- Gets the status for a file or URL

Description

int php_stream_stat_path ( char * path, php_stream_statbuf * ssb )

php_stream_stat_path() examines the file or URL specified by path and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

php_stream_stat

(no version information, might be only in CVS)

php_stream_stat -- Gets the status for the underlying storage associated with a stream

Description

int php_stream_stat ( php_stream * stream, php_stream_statbuf * ssb )

php_stream_stat() examines the storage to which stream is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.

php_stream_open_wrapper

(no version information, might be only in CVS)

php_stream_open_wrapper -- Opens a stream on a file or URL

Description

php_stream * php_stream_open_wrapper ( char * path, char * mode, int options, char ** opened )

php_stream_open_wrapper() opens a stream on the file, URL or other wrapped resource specified by path. Depending on the value of mode, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode.

The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important.

Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under Unix based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server.

r

Open text file for reading. The stream is positioned at the beginning of the file.

r+

Open text file for reading and writing. The stream is positioned at the beginning of the file.

w

Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file.

w+

Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

a

Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

a+

Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.

options affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See Stream open options for more information about options.

If opened is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include USE_PATH, which causes the include_path to be searched for the file. You, the caller, are responsible for calling efree() on the filename returned in this parameter.

Nota: If you specified STREAM_MUST_SEEK in options, the path returned in opened may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured.

php_stream_read

(no version information, might be only in CVS)

php_stream_read -- Read a number of bytes from a stream into a buffer

Description

size_t php_stream_read ( php_stream * stream, char * buf, size_t count )

php_stream_read() reads up to count bytes of data from stream and copies them into the buffer buf.

php_stream_read() returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use php_stream_eof() to test for an EOF.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

If less than count bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the EOF php_stream_read() will return a value less than count, and 0 on subsequent reads.

php_stream_write

(no version information, might be only in CVS)

php_stream_write -- Write a number of bytes from a buffer to a stream

Description

size_t php_stream_write ( php_stream * stream, const char * buf, size_t count )

php_stream_write() writes count bytes of data from buf into stream.

php_stream_write() returns the number of bytes that were written successfully. If there was an error, the number of bytes written will be less than count.

The internal position of the stream is advanced by the number of bytes that were written, so that subsequent writes will continue writing from that point.

php_stream_eof

(no version information, might be only in CVS)

php_stream_eof -- Check for an end-of-file condition on a stream

Description

int php_stream_eof ( php_stream * stream )

php_stream_eof() checks for an end-of-file condition on stream.

php_stream_eof() returns the 1 to indicate EOF, 0 if there is no EOF and -1 to indicate an error.

php_stream_getc

(no version information, might be only in CVS)

php_stream_getc -- Read a single byte from a stream

Description

int php_stream_getc ( php_stream * stream )

php_stream_getc() reads a single character from stream and returns it as an unsigned char cast as an int, or EOF if the end-of-file is reached, or an error occurred.

php_stream_getc() may block in the same way as php_stream_read() blocks.

The internal position of the stream is advanced by 1 if successful.

php_stream_gets

(no version information, might be only in CVS)

php_stream_gets -- Read a line of data from a stream into a buffer

Description

char * php_stream_gets ( php_stream * stream, char * buf, size_t maxlen )

php_stream_gets() reads up to count-1 bytes of data from stream and copies them into the buffer buf. Reading stops after an EOF or a newline. If a newline is read, it is stored in buf as part of the returned data. A NUL terminating character is stored as the last character in the buffer.

php_stream_read() returns buf when successful or NULL otherwise.

The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.

This function may block in the same way as php_stream_read().

php_stream_close

(no version information, might be only in CVS)

php_stream_close -- Close a stream

Description

int php_stream_close ( php_stream * stream )

php_stream_close() safely closes stream and releases the resources associated with it. After stream has been closed, it's value is undefined and should not be used.

php_stream_close() returns 0 if the stream was closed or EOF to indicate an error. Regardless of the success of the call, stream is undefined and should not be used after a call to this function.

php_stream_flush

(no version information, might be only in CVS)

php_stream_flush -- Flush stream buffers to storage

Description

int php_stream_flush ( php_stream * stream )

php_stream_flush() causes any data held in write buffers in stream to be committed to the underlying storage.

php_stream_flush() returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns EOF to indicate an error.

php_stream_seek

(no version information, might be only in CVS)

php_stream_seek -- Reposition a stream

Description

int php_stream_seek ( php_stream * stream, off_t offset, int whence )

php_stream_seek() repositions the internal position of stream. The new position is determined by adding the offset to the position indicated by whence. If whence is set to SEEK_SET, SEEK_CUR or SEEK_END the offset is relative to the start of the stream, the current position or the end of the stream, respectively.

php_stream_seek() returns 0 on success, but -1 if there was an error.

Nota: Not all streams support seeking, although the streams API will emulate a seek if whence is set to SEEK_CUR and offset is positive, by calling php_stream_read() to read (and discard) offset bytes.

The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller.

php_stream_tell

(no version information, might be only in CVS)

php_stream_tell -- Determine the position of a stream

Description

off_t php_stream_tell ( php_stream * stream )

php_stream_tell() returns the internal position of stream, relative to the start of the stream. If there is an error, -1 is returned.

php_stream_copy_to_stream

(no version information, might be only in CVS)

php_stream_copy_to_stream -- Copy data from one stream to another

Description

size_t php_stream_copy_to_stream ( php_stream * src, php_stream * dest, size_t maxlen )

php_stream_copy_to_stream() attempts to read up to maxlen bytes of data from src and write them to dest, and returns the number of bytes that were successfully copied.

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

Nota: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

php_stream_copy_to_mem

(no version information, might be only in CVS)

php_stream_copy_to_mem -- Copy data from stream and into an allocated buffer

Description

size_t php_stream_copy_to_mem ( php_stream * src, char ** buf, size_t maxlen, int persistent )

php_stream_copy_to_mem() allocates a buffer maxlen+1 bytes in length using pemalloc() (passing persistent). It then reads maxlen bytes from src and stores them in the allocated buffer.

The allocated buffer is returned in buf, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and persistent to pefree().

If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.

Nota: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.

php_stream_make_seekable

(no version information, might be only in CVS)

php_stream_make_seekable -- Convert a stream into a stream is seekable

Description

int php_stream_make_seekable ( php_stream * origstream, php_stream ** newstream, int flags )

php_stream_make_seekable() checks if origstream is seekable. If it is not, it will copy the data into a new temporary stream. If successful, newstream is always set to the stream that is valid to use, even if the original stream was seekable.

flags allows you to specify your preference for the seekable stream that is returned: use PHP_STREAM_NO_PREFERENCE to use the default seekable stream (which uses a dynamically expanding memory buffer, but switches to temporary file backed storage when the stream size becomes large), or use PHP_STREAM_PREFER_STDIO to use "regular" temporary file backed storage.

Tabella 44-1. php_stream_make_seekable() return values

ValueMeaning
PHP_STREAM_UNCHANGEDOriginal stream was seekable anyway. newstream is set to the value of origstream.
PHP_STREAM_RELEASEDOriginal stream was not seekable and has been released. newstream is set to the new seekable stream. You should not access origstream anymore.
PHP_STREAM_FAILEDAn error occurred while attempting conversion. newstream is set to NULL; origstream is still valid.
PHP_STREAM_CRITICALAn error occurred while attempting conversion that has left origstream in an indeterminate state. newstream is set to NULL and it is highly recommended that you close origstream.

Nota: If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream.

Nota: If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is SEEK_CUR.

Nota: If origstream is network based, this function will block until the whole contents have been downloaded.

Nota: NEVER call this function with an origstream that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer!

Nota: In many cases, this function can only succeed when origstream is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use php_stream_open_wrapper() and pass in PHP_STREAM_MUST_SEEK in your options instead of calling this function directly.

php_stream_cast

(no version information, might be only in CVS)

php_stream_cast -- Convert a stream into another form, such as a FILE* or socket

Description

int php_stream_cast ( php_stream * stream, int castas, void ** ret, int flags )

php_stream_cast() attempts to convert stream into a resource indicated by castas. If ret is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If flags is set to REPORT_ERRORS, an error message will be displayed is there is an error during conversion.

Nota: This function returns SUCCESS for success or FAILURE for failure. Be warned that you must explicitly compare the return value with SUCCESS or FAILURE because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended.

Tabella 44-1. Resource types for castas

ValueMeaning
PHP_STREAM_AS_STDIORequests an ANSI FILE* that represents the stream
PHP_STREAM_AS_FDRequests a POSIX file descriptor that represents the stream
PHP_STREAM_AS_SOCKETDRequests a network socket descriptor that represents the stream

In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values:

Tabella 44-2. Resource types for castas

ValueMeaning
PHP_STREAM_CAST_TRY_HARDTries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds
PHP_STREAM_CAST_RELEASEInforms the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the stream to be closed in such a way the underlying handle is preserved and returned in ret. If this function succeeds, stream should be considered closed and should no longer be used.

Nota: If your system supports fopencookie() (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not desirable, you should query the stream to see if it naturally supports FILE* by using php_stream_is()

Nota: If you ask a socket based stream for a FILE*, the streams API will use fdopen() to create it for you. Be warned that doing so may cause data that was buffered in the streams layer to be lost if you intermix streams API calls with ANSI stdio calls.

See also php_stream_is() and php_stream_can_cast().

php_stream_can_cast

(no version information, might be only in CVS)

php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socket

Description

int php_stream_can_cast ( php_stream * stream, int castas )

This function is equivalent to calling php_stream_cast() with ret set to NULL and flags set to 0. It returns SUCCESS if the stream can be converted into the form requested, or FAILURE if the conversion cannot be performed.

Nota: Although this function will not perform the conversion, some internal stream state *might* be changed by this call.

Nota: You must explicitly compare the return value of this function with one of the constants, as described in php_stream_cast().

See also php_stream_cast() and php_stream_is().

php_stream_is_persistent

(no version information, might be only in CVS)

php_stream_is_persistent -- Determines if a stream is a persistent stream

Description

int php_stream_is_persistent ( php_stream * stream )

php_stream_is_persistent() returns 1 if the stream is a persistent stream, 0 otherwise.

php_stream_is

(no version information, might be only in CVS)

php_stream_is -- Determines if a stream is of a particular type

Description

int php_stream_is ( php_stream * stream, int istype )

php_stream_is() returns 1 if stream is of the type specified by istype, or 0 otherwise.

Tabella 44-1. Values for istype

ValueMeaning
PHP_STREAM_IS_STDIOThe stream is implemented using the stdio implementation
PHP_STREAM_IS_SOCKETThe stream is implemented using the network socket implementation
PHP_STREAM_IS_USERSPACEThe stream is implemented using the userspace object implementation
PHP_STREAM_IS_MEMORYThe stream is implemented using the grow-on-demand memory stream implementation

Nota: The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison.

Nota: This function is implemented as a simple (and fast) pointer comparison, and does not change the stream state in any way.

See also php_stream_cast() and php_stream_can_cast().

php_stream_passthru

(no version information, might be only in CVS)

php_stream_passthru -- Outputs all remaining data from a stream

Description

size_t php_stream_passthru ( php_stream * stream )

php_stream_passthru() outputs all remaining data from stream to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance.

php_register_url_stream_wrapper

(no version information, might be only in CVS)

php_register_url_stream_wrapper -- Registers a wrapper with the Streams API

Description

int php_register_url_stream_wrapper ( char * protocol, php_stream_wrapper * wrapper, TSRMLS_DC )

php_register_url_stream_wrapper() registers wrapper as the handler for the protocol specified by protocol.

Nota: If you call this function from a loadable module, you *MUST* call php_unregister_url_stream_wrapper() in your module shutdown function, otherwise PHP will crash.

php_unregister_url_stream_wrapper

(no version information, might be only in CVS)

php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams API

Description

int php_unregister_url_stream_wrapper ( char * protocol, TSRMLS_DC )

php_unregister_url_stream_wrapper() unregisters the wrapper associated with protocol.

php_stream_open_wrapper_ex

(no version information, might be only in CVS)

php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying context

Description

php_stream * php_stream_open_wrapper_ex ( char * path, char * mode, int options, char ** opened, php_stream_context * context )

php_stream_open_wrapper_ex() is exactly like php_stream_open_wrapper(), but allows you to specify a php_stream_context object using context. To find out more about stream contexts, see Stream Contexts.

php_stream_open_wrapper_as_file

(no version information, might be only in CVS)

php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*

Description

FILE * php_stream_open_wrapper_as_file ( char * path, char * mode, int options, char ** opened )

php_stream_open_wrapper_as_file() is exactly like php_stream_open_wrapper(), but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries.

php_stream_filter_register_factory

(no version information, might be only in CVS)

php_stream_filter_register_factory -- Registers a filter factory with the Streams API

Description

int php_stream_filter_register_factory ( const char * filterpattern, php_stream_filter_factory * factory )

Use this function to register a filter factory with the name given by filterpattern. filterpattern can be either a normal string name (i.e. myfilter) or a global pattern (i.e. myfilterclass.*) to allow a single filter to perform different operations depending on the exact name of the filter invoked (i.e. myfilterclass.foo, myfilterclass.bar, etc...)

Nota: Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN.

php_stream_filter_unregister_factory

(no version information, might be only in CVS)

php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams API

Description

int php_stream_filter_unregister_factory ( const char * filterpattern )

Deregisters the filterfactory specified by the filterpattern making it no longer available for use.

Nota: Filters registered by a loadable extension must be certain to call php_stream_filter_unregister_factory() during MSHUTDOWN.


Streams Dir API Reference

Sommario
php_stream_opendir -- Open a directory for file enumeration
php_stream_readdir -- Fetch the next directory entry from an opened dir
php_stream_rewinddir -- Rewind a directory stream to the first entry
php_stream_closedir -- Close a directory stream and release resources

The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!).

php_stream_opendir

(no version information, might be only in CVS)

php_stream_opendir -- Open a directory for file enumeration

Description

php_stream * php_stream_opendir ( char * path, php_stream_context * context )

php_stream_opendir() returns a stream that can be used to list the files that are contained in the directory specified by path. This function is functionally equivalent to POSIX opendir(). Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams.

php_stream_readdir

(no version information, might be only in CVS)

php_stream_readdir -- Fetch the next directory entry from an opened dir

Description

php_stream_dirent * php_stream_readdir ( php_stream * dirstream, php_stream_dirent * ent )

php_stream_readdir() reads the next directory entry from dirstream and stores it into ent. If the function succeeds, the return value is ent. If the function fails, the return value is NULL. See php_stream_dirent for more details about the information returned for each directory entry.

php_stream_rewinddir

(no version information, might be only in CVS)

php_stream_rewinddir -- Rewind a directory stream to the first entry

Description

int php_stream_rewinddir ( php_stream * dirstream )

php_stream_rewinddir() rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure.

php_stream_closedir

(no version information, might be only in CVS)

php_stream_closedir -- Close a directory stream and release resources

Description

int php_stream_closedir ( php_stream * dirstream )

php_stream_closedir() closes a directory stream and releases resources associated with it. Returns 0 on success, but -1 on failure.


Streams File API Reference

Sommario
php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream
php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream
php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

php_stream_fopen_from_file

(no version information, might be only in CVS)

php_stream_fopen_from_file -- Convert an ANSI FILE* into a stream

Description

php_stream * php_stream_fopen_from_file ( FILE * file, char * mode )

php_stream_fopen_from_file() returns a stream based on the file. mode must be the same as the mode used to open file, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file.

php_stream_fopen_tmpfile

(no version information, might be only in CVS)

php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a stream

Description

php_stream * php_stream_fopen_tmpfile ( void )

php_stream_fopen_tmpfile() returns a stream based on a temporary file opened with a mode of "w+b". The temporary file will be deleted automatically when the stream is closed or the process terminates.

php_stream_fopen_temporary_file

(no version information, might be only in CVS)

php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on it

Description

php_stream * php_stream_fopen_temporary_file ( const char * dir, const char * pfx, char ** opened )

php_stream_fopen_temporary_file() generates a temporary file name in the directory specified by dir and with a prefix of pfx. The generated file name is returns in the opened parameter, which you are responsible for cleaning up using efree(). A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it.


Streams Socket API Reference

Sommario
php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream
php_stream_sock_open_host -- Open a connection to a host and return a stream
php_stream_sock_open_unix -- Open a Unix domain socket and convert into a stream

php_stream_sock_open_from_socket

(no version information, might be only in CVS)

php_stream_sock_open_from_socket -- Convert a socket descriptor into a stream

Description

php_stream * php_stream_sock_open_from_socket ( int socket, int persistent )

php_stream_sock_open_from_socket() returns a stream based on the socket. persistent is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

php_stream_sock_open_host

(no version information, might be only in CVS)

php_stream_sock_open_host -- Open a connection to a host and return a stream

Description

php_stream * php_stream_sock_open_host ( const char * host, unsigned short port, int socktype, struct timeval * timeout, int persistent )

php_stream_sock_open_host() establishes a connect to the specified host and port. socktype specifies the connection semantics that should apply to the connection. Values for socktype are system dependent, but will usually include (at a minimum) SOCK_STREAM for sequenced, reliable, two-way connection based streams (TCP), or SOCK_DGRAM for connectionless, unreliable messages of a fixed maximum length (UDP).

persistent is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.

If not NULL, timeout specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened.

Nota: The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup.

The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use php_stream_sock_set_timeout() to configure the timeout duration for your stream once it has been opened.

The streams API places no restrictions on the values you use for socktype, but encourages you to consider the portability of values you choose before you release your extension.

php_stream_sock_open_unix

(no version information, might be only in CVS)

php_stream_sock_open_unix -- Open a Unix domain socket and convert into a stream

Description

php_stream * php_stream_sock_open_unix ( const char * path, int pathlen, int persistent, struct timeval * timeout )

php_stream_sock_open_unix() attempts to open the Unix domain socket specified by path. pathlen specifies the length of path. If timeout is not NULL, it specifies a timeout period for the connection attempt. persistent indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0.

Nota: This function will not work under Windows, which does not implement Unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release.

Nota: This function treats path in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character.


Streams Structures

Sommario
struct php_stream_statbuf -- Holds information about a file or URL
struct php_stream_dirent -- Holds information about a single file during dir scanning
struct php_stream_ops -- Holds member functions for a stream implementation
struct php_stream_wrapper -- Holds wrapper properties and pointer to operations
struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementation
struct php_stream_filter -- Holds filter properties and pointer to operations
struct php_stream_filter_ops -- Holds member functions for a stream filter implementation

struct php_stream_statbuf

(no version information, might be only in CVS)

struct php_stream_statbuf -- Holds information about a file or URL

Description

php_stream_statbuf
     struct stat sb

sb is a regular, system defined, struct stat.

struct php_stream_dirent

(no version information, might be only in CVS)

struct php_stream_dirent -- Holds information about a single file during dir scanning

Description

php_stream_dirent
     char d_name[MAXPATHLEN]

d_name holds the name of the file, relative to the directory being scanned.

struct php_stream_ops

(no version information, might be only in CVS)

struct php_stream_ops -- Holds member functions for a stream implementation

Description

typedef struct _php_stream_ops {
             /* all streams MUST implement these operations */
             size_t (*write)(php_stream *stream, const char *buf, size_t count TSRMLS_DC);
             size_t (*read)(php_stream *stream, char *buf, size_t count TSRMLS_DC);
             int (*close)(php_stream *stream, int close_handle TSRMLS_DC);
             int (*flush)(php_stream *stream TSRMLS_DC);
             
             const char *label; /* name describing this class of stream */
             
             /* these operations are optional, and may be set to NULL if the stream does not
              * support a particular operation */
            int (*seek)(php_stream *stream, off_t offset, int whence TSRMLS_DC);
            char *(*gets)(php_stream *stream, char *buf, size_t size TSRMLS_DC);
            int (*cast)(php_stream *stream, int castas, void **ret TSRMLS_DC);
            int (*stat)(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC);
        } php_stream_ops;

struct php_stream_wrapper

(no version information, might be only in CVS)

struct php_stream_wrapper -- Holds wrapper properties and pointer to operations

Description

struct _php_stream_wrapper  {
            php_stream_wrapper_ops *wops;   /* operations the wrapper can perform */
            void *abstract;                 /* context for the wrapper */
            int is_url;                     /* so that PG(allow_url_fopen) can be respected */

            /* support for wrappers to return (multiple) error messages to the stream opener */
            int err_count;
            char **err_stack;
        } php_stream_wrapper;

struct php_stream_wrapper_ops

(no version information, might be only in CVS)

struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementation

Description

typedef struct _php_stream_wrapper_ops {
            /* open/create a wrapped stream */
            php_stream *(*stream_opener)(php_stream_wrapper *wrapper, char *filename, char *mode,
                    int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC);
            /* close/destroy a wrapped stream */
            int (*stream_closer)(php_stream_wrapper *wrapper, php_stream *stream TSRMLS_DC);
            /* stat a wrapped stream */
            int (*stream_stat)(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb TSR$
            /* stat a URL */
            int (*url_stat)(php_stream_wrapper *wrapper, char *url, php_stream_statbuf *ssb TSRMLS_DC);
            /* open a "directory" stream */
            php_stream *(*dir_opener)(php_stream_wrapper *wrapper, char *filename, char *mode,
                    int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC);

            const char *label;

            /* Delete/Unlink a file */
            int (*unlink)(php_stream_wrapper *wrapper, char *url, int options, php_stream_context *context TSRMLS_DC);
        } php_stream_wrapper_ops;

struct php_stream_filter

(no version information, might be only in CVS)

struct php_stream_filter -- Holds filter properties and pointer to operations

Description

struct _php_stream_filter {
            php_stream_filter_ops *fops;
            void *abstract; /* for use by filter implementation */
            php_stream_filter *next;
            php_stream_filter *prev;
            int is_persistent;

            /* link into stream and chain */
            php_stream_filter_chain *chain;

            /* buffered buckets */
            php_stream_bucket_brigade buffer;
        } php_stream_filter;

struct php_stream_filter_ops

(no version information, might be only in CVS)

struct php_stream_filter_ops -- Holds member functions for a stream filter implementation

Description

typedef struct _php_stream_filter_ops {
            php_stream_filter_status_t (*filter)(
                    php_stream *stream,
                    php_stream_filter *thisfilter,
                    php_stream_bucket_brigade *buckets_in,
                    php_stream_bucket_brigade *buckets_out,
                    size_t *bytes_consumed,
                    int flags
                    TSRMLS_DC);

            void (*dtor)(php_stream_filter *thisfilter TSRMLS_DC);

            const char *label;
} php_stream_filter_ops;

Streams Constants

Sommario
Stream open options -- Affects the operation of stream factory functions

Stream open options

(no version information, might be only in CVS)

Stream open options -- Affects the operation of stream factory functions

Description

One or more of these values can be combined using the OR operator.

IGNORE_PATH

This is the default option for streams; it requests that the include_path is not to be searched for the requested file.

USE_PATH

Requests that the include_path is to be searched for the requested file.

IGNORE_URL

Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.

IGNORE_URL_WIN

On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.

ENFORCE_SAFE_MODE

Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.

REPORT_ERRORS

If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.

STREAM_MUST_SEEK

This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.

Nota: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.

STREAM_WILL_CAST

If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires.

The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream.

Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.


Capitolo 45. PDO Driver How-To


A brief note about this How-To

The original version of this PDO driver specification was written by Bill Abt and Rick McGuire of IBM and contributed to the PHP community to assist in the development of drivers for more databases and to encourage the emerging standard for database access in PHP.


Prerequisites

The following is list of prerequisites and assumptions needed for writing a PDO database driver:

  1. A working target database, examples, demos, etc. working as per vendor specifications;

  2. A working development environment:

    1. Other Unix: standard development tools supplied by vendor plus the GNU development tool set;

    2. Win32: Visual Studio compiler suite;

    3. Linux: standard development tools, gcc, ld, make, autoconf, automake, etc., versions dependent on distribution;

  3. A working PHP environment version 5.0.3 or higher with a working PEAR extension version 1.3.5 or higher;

  4. A working PDO environment (can be installed using 'sudo pear install PDO'), including the headers which will be needed to access the PDO type definitions and function declarations;

  5. A good working knowledge of the 'C' programming language;

  6. A good working knowledge of the way to write a PHP extension; George Schlossnagle's Advanced PHP Programming (published by Developer's Library, chapters 21 and 22) is recommended;

  7. Finally, a familiarity with the Zend API that forms the heart of PHP, in particular paying attention to the memory management aspects.


Preparation and Housekeeping

Source directory layout

The source directory for a typical PDO driver is laid out as follows, where SKEL represents a shortened form of the name of the database that the driver is going to connect to. Even though SKEL is presented here in uppercase (for clarity), the convention is to use lowercase characters.

pdo_SKEL/          
  config.m4                  (1)
  config.w32                 (2)
  CREDITS
  package.xml                (3)
  pdo_SKEL.c           (4)
  php_pdo_SKEL.h
  php_pdo_SKEL_int.h   (5)
  SKEL_dbh.c           (6)
  SKEL_stmt.c          (7)
(1)
unix build script
(2)
win32 build script
(3)
meta information about the package
(4)
standard PHP extension glue
(5)
driver private header
(6)
contains the implementation of the PDO driver interface
(7)
contains the implementation of the PDO statement interface

The contents of these files are defined later in this document.


Creating a skeleton

The easiest way to get started is to use the ext_skel shell script found in the PHP build tree in the ext directory. This will build a skeleton directory containing a lot of the files listed above. It can be build by executing the following command from within the ext directory:

./ext_skel --extname=pdo_SKEL

This will generate a directory called pdo_SKEL containing the skeleton files that you can then modify. This directory should then be moved out of the php extension directory . PDO is a PECL extension and should not be included in the standard extension directory. As long as you have PHP and PDO installed, you should be able to build from any directory.


Standard Includes

Build Specific Headers

The header file config.h is generated by the configure process for the platform for the which the driver is being built. If this header is present, the HAVE_CONFIG_H compiler variable is set. This variable should be tested for and if set, the file config.h should be included in the compilation unit.


PHP Headers

The following standard public php headers should be included in each source module:

  1. php.h

  2. php_ini.h

  3. ext/standard/info.h


PDO Interface Headers

The following standard public PDO header files are also included in each source module:

pdo/php_pdo.h

This header file contains definitions of the initialization and shutdown functions in the main driver as well as definitions of global PDO variables.

pdo/php_pdo_driver.h

This header contains the types and API contracts that are used to write a PDO driver. It also contains method signature for calling back into the PDO layer and registering/unregistering your driver with PDO. Most importantly, this header file contains the type definitions for PDO database handles and statements. The two main structures a driver has to deal with, pdo_dbh_t and pdo_stmt_t, are described in more detail in Appendix A and B.


Driver Specific Headers

The typical PDO driver has two header files that are specific to the database implementation. This does not preclude the use of more depending on the implementation. The following two headers are, by convention, standard:

php_pdo_SKEL.h

This header file is virtually an exact duplicate in functionality and content of the previously defined pdo/php_pdo.h that has been specifically tailored for your database. If your driver requires the use of global variables they should be defined using the ZEND_BEGIN_MODULE_GLOBALS and ZEND_END_MODULE_GLOBALS macros. Macros are then used to access these variables. This macro is usually named PDO_SKEL_G(v) where v is global variable to be accessed. Consult the Zend programmer documentation for more information.

php_pdo_SKEL_int.h

This header file typically contains type definitions and function declarations specific to the driver implementation. It also should contain the db specicfic definitions of a pdo_SKEL_handle and pdo_SKEL_stmt structures. These are the names of the private data structures that are then referenced by the driver_data members of the handle and statement structures.


Optional Headers

Depending on the implementation details for a particular driver it may be necessary to include the following header:

#include <zend_exceptions.h>

Fleshing out your skeleton

Major Structures and Attributes

The major structures, pdo_dbh_t and pdo_stmt_t are defined and explained in Appendix A and B respectively. Database and Statement attributes are defined in Appendix C. Error handling is explained in Appendix D.


pdo_SKEL.c: PHP extension glue

function entries

static function_entry pdo_SKEL_functions[] = {
  { NULL, NULL, NULL }
};

This structure is used to register functions into the global php function namespace. PDO drivers should try to avoid doing this, so it is recommended that you leave this structure initialized to NULL, as shown in the synopsis above.


Module entry

/* {{{ pdo_SKEL_module_entry */
#if ZEND_EXTENSION_API_NO >= 220050617
static zend_module_dep pdo_SKEL_deps[] = {
    ZEND_MOD_REQUIRED("pdo")
    {NULL, NULL, NULL}
};
#endif
/* }}} */

zend_module_entry pdo_SKEL_module_entry = {
#if ZEND_EXTENSION_API_NO >= 220050617
    STANDARD_MODULE_HEADER_EX, NULL,
    pdo_SKEL_deps,
#else
    STANDARD_MODULE_HEADER,
#endif
    "pdo_SKEL",
    pdo_SKEL_functions,
    PHP_MINIT(pdo_SKEL),
    PHP_MSHUTDOWN(pdo_SKEL),
    NULL,
    NULL,
    PHP_MINFO(pdo_SKEL),
    PHP_PDO_<DB>_MODULE_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_PDO_<DB>
ZEND_GET_MODULE(pdo_db)
#endif

A structure of type zend_module_entry called pdo_SKEL_module_entry must be declared and should include reference to the pdo_SKEL_functions table defined previously.


Standard PHP Module Extension Functions

PHP_MINIT_FUNCTION
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(pdo_SKEL)
{
    return php_pdo_register_driver(&pdo_SKEL_driver);
}
/* }}} */

This standard PHP extension function should be used to register your driver with the PDO layer. This is done by calling the php_pdo_register_driver() function passing a pointer to a structure of type pdo_driver_t typically named pdo_SKEL_driver. A pdo_driver_t contains a header that is generated using the PDO_DRIVER_HEADER(SKEL) macro and pdo_SKEL_handle_factory() function pointer. The actual function is described during the discussion of the SKEL_dbh.c unit.


PHP_MSHUTDOWN_FUNCTION
/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(pdo_SKEL)
{
    php_pdo_unregister_driver(&pdo_SKEL_driver);
    return SUCCESS;
}
/* }}} */

This standard PHP extension function is used to unregister your driver from the PDO layer. This is done by calling the php_pdo_unregister_driver() function, passing the same pdo_SKEL_driver structure that was passed in the init function above.


PHP_MINFO_FUNCTION

This is again a standard PHP extension function. Its purpose is to display information regarding the module when the phpinfo() is called from a script. The convention is to display the version of the module and also what version of the db you are dependent on, along with any other configuration style information that might be relevant.


SKEL_driver.c: Driver implementation

This unit implements all of the database handling methods that support the PDO database handle object. It also contains the error fetching routines. All of these functions will typically need to access the global variable pool. Therefore, it is necessary to use the Zend macro TSRMLS_DC macro at the end of each of these statements. Consult the Zend programmer documentation for more information on this macro.


pdo_SKEL_error

static int pdo_SKEL_error(pdo_dbh_t *dbh,
  pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC)

The purpose of this function is to be used as a generic error handling function within the driver. It is called by the driver when an error occurs within the driver. If an error occurs that is not related to SQLSTATE, the driver should set either dbh->error_code or stmt->error_code to an SQLSTATE that most closely matches the error or the generic SQLSTATE error "HY000". The file pdo_sqlstate.c in the PDO source contains a table of commonly used SQLSTATE codes that the PDO code explicitly recognizes. This setting of the error code should be done prior to calling this function.; This function should set the global pdo_err variable to the error found in either the dbh or the stmt (if the variable stmt is not NULL).

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the current statement or NULL. If NULL, the error is derived by error code found in the dbh.

file

The source file where the error occurred or NULL if not available.

line

The line number within the source file if available.

If the dbh member methods is NULL (which implies that the error is being raised from within the PDO constructor), this function should call the zend_throw_exception_ex() function otherwise it should return the error code. This function is usually called using a helper macro that customizes the calling sequence for either database handling errors or statement handling errors.

Esempio 45-1. Example macros for invoking pdo_SKEL_error

#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)
#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)

For more info on error handling, see la Sezione Error handling.

Nota: Despite being documented here, the PDO driver interface does not specify that his function be present; it is merely a convenient way to handle errors, and it just happens to be equally convenient for the majority of database client library APIs to structure your driver implementation in this way.


pdo_SKEL_fetch_error_func

static int pdo_SKEL_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt,
    zval *info TSRMLS_DC)

The purpose of this function is to obtain additional information about the last error that was triggered. This includes the driver specific error code and a human readable string. It may also include additional information if appropriate. This function is called as a result of the PHP script calling the PDO::errorInfo() method.

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the most current statement or NULL. If NULL, the error translated is derived by error code found in the dbh.

info

A hash table containing error codes and messages.

The error_func should return two pieces of information as successive array elements. The first item is expected to be a numeric error code, the second item is a descriptive string. The best way to set this item is by using add_next_index. Note that the type of the first argument need not be long; use whichever type most closely matches the error code returned by the underlying database API.

/* now add the error information. */
/* These need to be added in a specific order */
add_next_index_long(info, error_code);   /* driver specific error code */
add_next_index_string(info, message, 0); /* readable error message */

This function should return 1 if information is available, 0 if the driver does not have additional info.


SKEL_handle_closer

static int SKEL_handle_closer(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to close an open database.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to close the open database. PDO ignores the return value from this function.


SKEL_handle_preparer

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)

This function will be called by PDO in response to PDO::query() and PDO::prepare() calls from the PHP script. The purpose of the function is to prepare raw SQL for execution, storing whatever state is appropriate into the stmt that is passed in.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

Stmt

Pointer to the returned statement or NULL if an error occurs.

driver_options

Any driver specific/defined options.

This function is essentially the constructor for a stmt object. This function is responsible for processing statement options, and setting driver-specific option fields in the pdo_stmt_t structure.

PDO does not process any statement options on the driver's behalf before calling the preparer function. It is your responsibility to process them before you return, raising an error for any unknown options that are passed.

One very important responsibility of this function is the processing of SQL statement parameters. At the time of this call, PDO does not if your driver supports binding parameters into prepared statements, nor does it know if it supports named or positional parameter naming conventions.

Your driver is responsible for setting stmt->supports_placeholders as appropriate for the underlying database. This may involved some run-time determination on the part of your driver, if this setting depends on the version of the database server to which it is connected. If your driver doesn't directly support both named and positional parameter conventions, you should use the pdo_parse_params() API to have PDO rewrite the query to take advantage of the support provided by your database.

Esempio 45-2. Using pdo_parse_params

int ret;
    char *nsql = NULL;
    int nsql_len = 0;

    /* before we prepare, we need to peek at the query; if it uses named parameters,
     * we want PDO to rewrite them for us */
    stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;
    ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);

    if (ret == 1) {
        /* query was re-written */
        sql = nsql;
    } else if (ret == -1) {
        /* couldn't grok it */
        strcpy(dbh->error_code, stmt->error_code);
        return 0;
    }

    /* now proceed to prepare the query in "sql" */

Possible values for supports_placeholders are: PDO_PLACEHOLDER_NAMED, PDO_PLACEHOLDER_POSITIONAL and PDO_PLACEHOLDER_NONE. If the driver doesn't support prepare statements at all, then this function should simply allocate any state that it might need, and then return:

Esempio 45-3. implementing preparer for drivers that don't support native prepared statements

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
    long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
{
    pdo_SKEL_db_handle *H = (pdo_SKEL_db_handle *)dbh->driver_data;
    pdo_SKEL_stmt *S = ecalloc(1, sizeof(pdo_SKEL_stmt));

    S->H = H;
    stmt->driver_data = S;
    stmt->methods = &SKEL_stmt_methods;
    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;

    return 1;
}

This function returns 1 on success or 0 on failure.


SKEL_handle_doer

static long SKEL_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)

This function will be called by PDO to execute a raw SQL statement. No pdo_stmt_t is created.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

This function returns 1 on success or 0 on failure.


SKEL_handle_quoter

static int SKEL_handle_quoter(pdo_dbh_t *dbh, const char *unquoted,
  int unquoted_len, char **quoted, int quoted_len, enum pdo_param_type param_type TSRMLS_DC)

This function will be called by PDO to turn an unquoted string into a quoted string for use in a query.

dbh

Pointer to the database handle initialized by the handle factory

unquoted

Pointer to a character string containing the string to be quoted.

unquoted_len

The length of the string to be quoted.

quoted

Pointer to the address where a pointer to the newly quoted string will be returned.

quoted_len

The length of the new string.

param_type

A driver specific hint for driver that have alternate quoting styles

This function is called in response to a call to PDO::quote() or when the driver has set supports_placeholder to PDO_PLACEHOLDER_NONE. The purpose is to quote a parameter when building SQL statements.

If your driver does not support native prepared statements, implementation of this function is required.

This function returns 1 if the quoting process reformatted the string, and 0 if it was not necessary to change the string. The original string will be used unchanged with a 0 return.


SKEL_handle_begin

static int SKEL_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to begin a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to begin a transaction. This function returns 1 for success or 0 if an error occurred.


SKEL_handle_commit

static int SKEL_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to end a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to commit a transaction. This function returns 1 for success or 0 if an error occurred.


SKEL_handle_rollback

static int SKEL_handle_rollback( pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to rollback a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to rollback a transaction. This function returns 1 for success or 0 if an error occurred.


SKEL_handle_get_attribute

static int SKEL_handle_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)

This function will be called by PDO to retrieve a database attribute.

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.

return_value

The returned value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to supply this function. PDO driver handles the PDO_ATTR_PERSISTENT, PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.


SKEL_handle_set_attribute

static int SKEL_handle_set_attribute(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to set a database attribute, usually in response to a script calling PDO::setAttribute().

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.

val

The new value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to provide this function if it does not need to support additional attributes. The PDO driver handles the PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.


SKEL_handle_last_id

static char * SKEL_handle_last_id(pdo_dbh_t *dbh, const char *name, unsigned int len TSRMLS_DC)

This function will be called by PDO to retrieve the ID of the last inserted row.

dbh

Pointer to the database handle initialized by the handle factory

name

string representing a table or sequence name.

len

the length of the name parameter.

This function returns a character string containing the id of the last inserted row on success or NULL on failure. This is an optional function.


SKEL_check_liveness

static int SKEL_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to test whether or not a persistent connection to a database is alive and ready for use.

dbh

Pointer to the database handle initialized by the handle factory

This function returns 1 if the database connection is alive and ready for use, otherwise it should return 0 to indicate failure or lack of support.

Nota: This is an optional function.


SKEL_get_driver_methods

static function_entry *SKEL_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)

This function will be called by PDO in response to a call to any method that is not a part of either the PDO or PDOStatement classes. It's purpose is to allow the driver to provide additional driver specific methods to those classes.

dbh

Pointer to the database handle initialized by the handle factory

kind

One of the following:

PDO_DBH_DRIVER_METHOD_KIND_DBH

Set when the method call was attempted on an instance of the PDO class. The driver should return a pointer a function_entry table for any methods it wants to add to that class, or NULL if there are none.

PDO_DBH_DRIVER_METHOD_KIND_STMT

Set when the method call was attempted on an instance of the PDOStatement class. The driver should return a pointer to a function_entry table for any methods it wants to add to that class, or NULL if there are none.

This function returns a pointer to the function_entry table requested, or NULL there are no driver specific methods.


SKEL_handle_factory

static int SKEL_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC)

This function will be called by PDO to create a database handle. For most databases this involves establishing a connection to the database. In some cases, a persistent connection may be requested, in other cases connection pooling may be requested. All of these are database/driver dependent.

dbh

Pointer to the database handle initialized by the handle factory

driver_options

An array of driver options, keyed by integer option number. See Tabella 45-1 for a list of possible attributes.

This function should fill in the passed database handle structure with its driver specific information on success and return 1, otherwise it should return 0 to indicate failure.

PDO processes the AUTOCOMMIT and PERSISTENT driver options before calling the handle_factory. It is the handle factory's responsibility to process other options.


Driver method table

A static structure of type pdo_dbh_methods named SKEL_methods must be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.


pdo_SKEL_driver

A structure of type pdo_driver_t named pdo_SKEL_driver should be declared. The PDO_DRIVER_HEADER(SKEL) macro should be used to declare the header and the function pointer to the handle factory function should set.


SKEL_statement.c: Statement implementation

This unit implements all of the database statement handling methods that support the PDO statement object.


SKEL_stmt_dtor

static int SKEL_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to destroy a previously constructed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This should do whatever is necessary to free up any driver specific storage allocated for the statement. The return value from this function is ignored.


SKEL_stmt_execute

static int SKEL_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to execute the prepared SQL statement in the passed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This function returns 1 for success or 0 in the event of failure.


SKEL_stmt_fetch

static int SKEL_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori,
   long offset TSRMLS_DC)

This function will be called by PDO to fetch a row from a previously executed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

ori

One of PDO_FETCH_ORI_xxx which will determine which row will be fetched.

offset

If ori is set to PDO_FETCH_ORI_ABS or PDO_FETCH_ORI_REL, offset represents the row desired or the row relative to the current position, respectively. Otherwise, this value is ignored.

The results of this fetch are driver dependent and the data is usually stored in the driver_data member of pdo_stmt_t object. The ori and offset parameters are only meaningful if the statement represents a scrollable cursor. This function returns 1 for success or 0 in the event of failure.


SKEL_stmt_param_hook

static int SKEL_stmt_param_hook(pdo_stmt_t *stmt,
  struct pdo_bound_param_data *param, enum pdo_param_event event_type TSRMLS_DC)

This function will be called by PDO for handling of both bound parameters and bound columns.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

param

The structure describing either a statement parameter or a bound column.

event_type

The type of event to occur for this parameter, one of the following:

PDO_PARAM_EVT_ALLOC

Called when PDO allocates the binding. Occurs as part of PDOStatement::bindParam(), PDOStatement::bindValue() or as part of an implicit bind when calling PDOStatement::execute(). This is your opportunity to take some action at this point; drivers that implement native prepared statements will typically want to query the parameter information, reconcile the type with that requested by the script, allocate an appropriately sized buffer and then bind the parameter to that buffer. You should not rely on the type or value of the zval at param->parameter at this point in time.

PDO_PARAM_EVT_FREE

Called once per parameter as part of cleanup. You should release any resources associated with that parameter now.

PDO_PARAM_EXEC_PRE

Called once for each parameter immediately before calling SKEL_stmt_execute; take this opportunity to make any final adjustments ready for execution. In particular, you should note that variables bound via PDOStatement::bindParam() are only legal to touch now, and not any sooner.

PDO_PARAM_EXEC_POST

Called once for each parameter immediately after calling SKEL_stmt_execute; take this opportunity to make any post-execution actions that might be required by your driver.

PDO_PARAM_FETCH_PRE

Called once for each parameter immediately prior to calling SKEL_stmt_fetch.

PDO_PARAM_FETCH_POST

Called once for each parameter immediately after calling SKEL_stmt_fetch.

This hook will be called for each bound parameter and bound column in the statement. For ALLOC and FREE events, a single call will be made for each parameter or column. The param structure contains a driver_data field that the driver can use to store implementation specific information about each of the parameters.

For all other events, PDO may call you multple times as the script issues PDOStatement::execute() and PDOStatement::fetch() calls.

If this is a bound parameter, the is_param flag in the param structure, otherwise, the param structure refers to a bound column.

This function returns 1 for success or 0 in the event of failure.


SKEL_stmt_describe_col

static int SKEL_stmt_describe_col(pdo_stmt_t *stmt, int colno TSRMLS_DC)

This function will be called by PDO to query information about a particular column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

The driver should populate the pdo_stmt_t member columns(colno) with the appropriate information. This function returns 1 for success or 0 in the event of failure.


SKEL_stmt_get_col_data

static int SKEL_stmt_get_col_data(pdo_stmt_t *stmt, int colno,
  char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)

This function will be called by PDO to retrieve data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

ptr

Pointer to the retrieved data.

len

The length of the data pointed to by ptr.

caller_frees

If set, ptr should point to emalloc'd memory and the main PDO driver will free it as soon as it is done with it. Otherwise, it will be the responsibility of the driver to free any allocated memory as a result of this call.

The driver should return the resultant data and length of that data in the ptr and len variables respectively. It should be noted that the main PDO driver expects the driver to manage the lifetime of the data. This function returns 1 for success or 0 in the event of failure.


SKEL_stmt_set_attr

static int SKEL_stmt_set_attr(pdo_stmt_t *stmt, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to allow the setting of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.

val

The new value for the attribute.

This function is driver dependent and allows the driver the capability to set database specific attributes for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional settable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.


SKEL_stmt_get_attr

static int SKEL_stmt_get_attr(pdo_stmt_t *stmt, long attr, zval
   *return_value TSRMLS_DC)

This function will be called by PDO to allow the retrieval of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.

return_value

The returned value for the attribute.

This function is driver dependent and allows the driver the capability to retrieve a previously set database specific attribute for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional gettable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.


SKEL_stmt_get_col_meta

static int SKEL_stmt_get_col_meta(pdo_stmt_t *stmt, int colno,
   zval *return_value TSRMLS_DC)

Avvertimento

This function is not well defined and is subject to change.

This function will be called by PDO to retrieve meta-data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number for which data is to be retrieved.

return_value

Holds the returned meta data.

The driver author should consult the documentation for this function that can be found in the php_pdo_driver.h header as this will be the most current. This function returns 1 for success or 0 in the event of failure. The database driver does not need to provide this function.


Statement handling method table

A static structure of type pdo_stmt_methods named SKEL_stmt_methods should be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.


Building

The build process is designed to work with PEAR (see http://pear.php.net/ for more information about PEAR). There are two files that are used to assist in configuring your package for building. The first is config.m4 which is the autoconf configuration file for all platforms except Win32. The second is config.w32 which a build configuration file for use on Win32. Skeleton files for these are built for you when you first set up your project. You then need to customize them to fit the needs of your project. Once you've customized your config files, you can build your driver using the following sequence of commands:

Before first build:

$ sudo pear install PDO

For each build:

$ cd pdo_SKEL
$ phpize
$ ./configure
$ make
$ sudo make install

The process can then be repeated as necessary during the development process.


Testing

PDO has a set of "core" tests that all drivers should pass before being released. They're designed to run from the PHP source distribution, so running the tests for your driver requires moving things around a bit. The suggested procedure is to obtain the latest PHP 5.1 snapshot and perform the following step:

$ cp -r pdo_SKEL /path/to/php-5.1/ext

This will allow the test harness to run your tests. The next thing you need to do is create a test that will redirect into the PDO common core tests. The convention is to name this file common.phpt; it should be placed in the tests subdirectory that was created by ext_skel when you created your extension skeleton. The content of this file should look something like the following:

--TEST--
SKEL
--SKIPIF--
<?php # vim:ft=php
if (!extension_loaded('pdo_SKEL')) print 'skip'; ?>
--REDIRECTTEST--
if (false !== getenv('PDO_SKEL_TEST_DSN')) {
# user set them from their shell
   $config['ENV']['PDOTEST_DSN'] = getenv('PDO_SKEL_TEST_DSN');
   $config['ENV']['PDOTEST_USER'] = getenv('PDO_SKEL_TEST_USER');
   $config['ENV']['PDOTEST_PASS'] = getenv('PDO_SKEL_TEST_PASS');
   if (false !== getenv('PDO_SKEL_TEST_ATTR')) {
      $config['ENV']['PDOTEST_ATTR'] = getenv('PDO_SKEL_TEST_ATTR');
   }
   return $config;
}
return array(
   'ENV' => array(
           'PDOTEST_DSN' => 'SKEL:dsn',
           'PDOTEST_USER' => 'username',
           'PDOTEST_PASS' => 'password'
       ),
   'TESTS' => 'ext/pdo/tests'
   );

This will cause the common core tests to be run, passing the values of PDOTEST_DSN, PDOTEST_USER and PDOTEST_PASS to the PDO constructor as the dsn, username and password parameters. It will first check the environment, so that appropriate values can be passed in when the test harness is run, rather than hard-coding the database credentials into the test file.

The test harness can be invoked as follows:

$ cd /path/to/php-5.1
$ make TESTS=ext/pdo_SKEL/tests PDO_SKEL_TEST_DSN="skel:dsn" \
 PDO_SKEL_TEST_USER=user PDO_SKEL_TEST_PASS=pass test

Packaging and distribution

Creating a package

PDO drivers are released via PECL; all the usual rules for PECL extensions apply. Packaging is accomplished by creating a valid package.xml file and then running:

$ pear package

This will create a tarball named PDO_SKEL-X.Y.Z.tgz.

Before releasing the package, you should test that it builds correctly; if you've made a mistake in your config.m4 or package.xml files, the package may not function correctly. You can test the build, without installing anything, using the following invocation:

$ pear build package.xml

Once this is proven to work, you can test installation:

$ pear package
$ sudo pear install PDO_SKEL-X.Y.X.tgz

Full details about package.xml can be found in the PEAR Programmer's documentation (http://pear.php.net/manual/).


Releasing the package

A PDO driver is released via the PHP Extension Community Library (PECL). Information about PECL can be found at http://pecl.php.net/index.php.


pdo_dbh_t definition

All fields should be treated as read-only by the driver, unless explicitly stated otherwise.

Figura 45-1. pdo_dbh_t

/* represents a connection to a database */
struct _pdo_dbh_t {
    /* driver specific methods */
    struct pdo_dbh_methods *methods;    (1)
    /* driver specific data */
    void *driver_data;                  (2)

    /* credentials */
    char *username, *password;          (3)

    /* if true, then data stored and pointed at by this handle must all be
     * persistently allocated */
    unsigned is_persistent:1;           (4)

    /* if true, driver should act as though a COMMIT were executed between
     * each executed statement; otherwise, COMMIT must be carried out manually
     * */
    unsigned auto_commit:1;             (5)

    /* if true, the driver requires that memory be allocated explicitly for
     * the columns that are returned */
    unsigned alloc_own_columns:1;       (6)

    /* if true, commit or rollBack is allowed to be called */
    unsigned in_txn:1;                  

    /* max length a single character can become after correct quoting */
    unsigned max_escaped_char_length:3;   (7)

    /* data source string used to open this handle */
    const char *data_source;            (8)
    unsigned long data_source_len;

    /* the global error code. */
    pdo_error_type error_code;          (9)

    enum pdo_case_conversion native_case(10), desired_case;
};
(1)
The driver must set this during SKEL_handle_factory().
(2)
This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
(3)
The username and password that were passed into the PDO constructor. The driver should use these values when it initiates a connection to the database.
(4)
If this is set to 1, then any data that is referenced by the dbh, including whatever structure your driver allocates, MUST be allocated persistently. This is easy to achieve; rather than using the usual emalloc() simply use pemalloc() and pass the value of this flag as the last parameter. Failure to use the appropriate kind of memory can lead to serious memory faults, resulting (in the best case) a hard crash, and in the worst case, an exploitable memory problem.

If, for whatever reason, your driver is not suitable to run persistently, you MUST check this flag in your SKEL_handle_factory() and raise an appropriate error.

(5)
You should check this value in your SKEL_handle_doer() and SKEL_stmt_execute() functions; if it evaluates to true, you must attempt to commit the query now. Most database implementations offer an auto-commit mode that handles this automatically.
(6)
If your database client library API operates by fetching data into a caller-supplied buffer, you should set this flag to 1 during your SKEL_handle_factory(). When set, PDO will call your SKEL_stmt_describer() earlier that it would otherwise. This early call allows you to determine those buffer sizes and issue appropriate calls to the database client library.

If your database client library API simply returns pointers to its own internal buffers for you to copy after each fetch call, you should leave this value set to 0.

(7)
If your driver doesn't support native prepared statements (supports_placeholders is set to PDO_PLACEHOLDER_NONE), you must set this value to the maximum length that can be taken up by a single character when it is quoted by your SKEL_handle_quoter() function. This value is used to calculate the amount of buffer space required when PDO it executes the statement.
(8)
This holds the value of the DSN that was passed into the PDO constructor. If your driver implementation needed to modify the DSN for whatever reason, it should update this member during SKEL_handle_factory(). Modifying this member should be avoided. If you do change it, you must ensure that data_source_len is also correct.
(9)
Whenever an error occurs during a call to one of your driver methods, you should set this member to the SQLSTATE code that best describes the error and return an error. In this HOW-TO, the suggested practice is to call SKEL_handle_error() when an error is detected, and have it set the error code.
(10)
Your driver should set this during SKEL_handle_factory(); the value should reflect how the database returns the names of the columns in result sets. If the name matches the case that was used in the query, set it to PDO_CASE_NATURAL (this is actually the default). If the column names are always returned in upper case, set it to PDO_CASE_UPPER. If the column names are always return in lower case, set it to PDO_CASE_LOWER. The value you set it used to determine if PDO should perform case folding when the user sets the PDO_ATTR_CASE attribute.

pdo_stmt_t definition

All fields should be treated as read-only unless explicitly stated otherwise.

Figura 45-2. pdo_stmt_t

/* represents a prepared statement */
struct _pdo_stmt_t {
    /* driver specifics */
    struct pdo_stmt_methods *methods;   (1)
    void *driver_data;                  (2)

    /* if true, we've already successfully executed this statement at least
     * once */
    unsigned executed:1;                (3)
    /* if true, the statement supports placeholders and can implement
     * bindParam() for its prepared statements, if false, PDO should
     * emulate prepare and bind on its behalf */
    unsigned supports_placeholders:2;   (4)

    /* the number of columns in the result set; not valid until after
     * the statement has been executed at least once.  In some cases, might
     * not be valid until fetch (at the driver level) has been called at least once.
     * */
    int column_count;                   (5)
    struct pdo_column_data *columns;    (6)

    /* points at the dbh that this statement was prepared on */
    pdo_dbh_t *dbh;

    /* keep track of bound input parameters.  Some drivers support
     * input/output parameters, but you can't rely on that working */
    HashTable *bound_params;
    /* When rewriting from named to positional, this maps positions to names */
    HashTable *bound_param_map; 
    /* keep track of PHP variables bound to named (or positional) columns
     * in the result set */
    HashTable *bound_columns;

    /* not always meaningful */
    long row_count;

    /* used to hold the statement's current query */
    char *query_string;
    int query_stringlen;

    /* the copy of the query with expanded binds ONLY for emulated-prepare drivers */
    char *active_query_string;
    int active_query_stringlen;

    /* the cursor specific error code. */
    pdo_error_type error_code;

    /* used by the query parser for driver specific
     * parameter naming (see pgsql driver for example) */
    const char *named_rewrite_template;
};
(1)
The driver must set this during SKEL_handle_preparer().
(2)
This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
(3)
This is set by PDO after the statement has been executed for the first time. Your driver can inspect this value to determine if it can skip one-time actions as an optimization.
(4)
Discussed in more detail in la Sezione SKEL_handle_preparer
(5)
Your driver is responsible for setting this field to the number of columns available in a result set. This is usually set during SKEL_stmt_execute() but with some database implementations, the column count may not be available until SKEL_stmt_fetch() has been called at least once. Drivers that SKEL_stmt_next_rowset() should update the column count when a new rowset is available.
(6)
PDO will allocate this field based on the value that you set for the column count. You are responsible for populating each column during SKEL_stmt_describe(). You must set the precision, maxlen, name, namelen and param_type members for each column. The name is expected to be allocated using emalloc(); PDO will efree() at the appropriate time.

Constants

Tabella 45-1. Database and Statement Attributes Table

Attribute

Valid value(s)

PDO_ATTR_AUTOCOMMIT

BOOL

TRUE if autocommit is set, FALSE otherwise.

dbh->auto_commit contains value. Processed by PDO directly.

PDO_ATTR_PREFETCH

LONG

Value of the prefetch size in drivers that support it.

PDO_ATTR_TIMEOUT

LONG

How long to wait for a db operation before timing out.

PDO_ATTR_ERRMODE

LONG

Processed and handled by PDO

PDO_ATTR_SERVER_VERSION

STRING

The "human-readable" string representing the Server/Version this driver is currently connected to.

PDO_ATTR_CLIENT_VERSION

STRING

The "human-readable" string representing the Client/Version this driver supports.

PDO_ATTR_SERVER_INFO

STRING

The "human-readable" description of the Server.

PDO_ATTR_CONNECTION_STATUS

LONG

Values not yet defined

PDO_ATTR_CASE

LONG

Processed and handled by PDO.

PDO_ATTR_CURSOR_NAME

STRING

String representing the name for a database cursor for use in "where current in <name>" SQL statements.

PDO_ATTR_CURSOR

LONG

PDO_CURSOR_FWDONLY

Forward only cursor

PDO_CURSOR_SCROLL

Scrollable cursor

The values for the attributes above are all defined in terms of the Zend API. The Zend API contains macros that can be used to convert a *zval to a value. These macros are defined in the Zend header file, zend_API.h in the Zend directory of your PHP build directory. Some of these attributes can be used with the statement attribute handlers such as the PDO_ATTR_CURSOR and PDO_ATTR_CURSOR_NAME. See the statement attribute handling functions for more information.


Error handling

Error handling is implemented using a hand-shaking protocol between PDO and the database driver code. The database driver code signals PDO than an error has occurred via a failure (0) return from any of the interface functions. If a zero is returned, the field error_code in the control block appropriate to the context (either the pdo_dbh_t or pdo_stmt_t block). In practice, it is probably a good idea to set the field in both blocks to the same value to ensure the correct one is getting used.

The error_mode field is a six-byte field containing a 5 character ASCIIZ SQLSTATE identifier code. This code drives the error message process. The SQLSTATE code is used to look up an error message in the internal PDO error message table (see pdo_sqlstate.c for a list of error codes and their messages). If the code is not known to PDO, a default "Unknown Message" value will be used.

In addition to the SQLSTATE code and error message, PDO will call the driver-specific fetch_err() routine to obtain supplemental data for the particular error condition. This routine is passed an array into which the driver may place additional information. This array has slot positions assigned to particular types of supplemental info:

  1. A native error code. This will frequently be an error code obtained from the database API.

  2. A descriptive string. This string can contain anything additional information related to the failure. Database drivers typically include information such as an error message, code location of the failure, and any additional descriptive information the driver developer feels worthy of inclusion. It is generally a good idea to include all diagnostic information obtainable from the database interface at the time of the failure. For driver-detected errors (such as memory allocation problems), the driver developer can define whatever error information that seems appropriate.


Capitolo 46. Zend API: Hacking the Core of PHP


Introduction

Those who know don't talk.

Those who talk don't know.

Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.

As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.


Overview

"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.

Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.


What Is Zend? and What Is PHP?

The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated (see Figura 46-1). To implement a Web script interpreter, you need three parts:

  1. The interpreter part analyzes the input code, translates it, and executes it.

  2. The functionality part implements the functionality of the language (its functions, etc.).

  3. The interface part talks to the Web server, etc.

Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities.

Figura 46-1. The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.


Extension Possibilities

As shown in Figura 46-1 above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.


External Modules

External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:

AdvantagesDisadvantages
External modules don't require recompiling of PHP. The shared objects need to be loaded every time a script is being executed (every hit), which is very slow.
The size of PHP remains small by "outsourcing" certain functionality. External additional files clutter up the disk.
  Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution).

To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages.

Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.


Built-in Modules

Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:

AdvantagesDisadvantages
No need to load the module specifically; the functionality is instantly available. Changes to built-in modules require recompiling of PHP.
No external files clutter up the disk; everything resides in the PHP binary. The PHP binary grows and consumes more memory.

Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.


The Zend Engine

Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.


Source Layout

Nota: Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at http://www.apache.org/) and, of course, with PHP (available at http://www.php.net/ - does it need to be said?).

Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.

Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.

The following table describes the contents of the major directories.

DirectoryContents
php-src Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory.
php-src/ext Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
php-src/main This directory contains the main php macros and definitions. (important)
php-src/pear Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php-src/sapi Contains the code for the different server abstraction layers.
TSRM Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
ZendEngine2 Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php-src/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php-src/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php-src/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.

You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style.


Extension Conventions

Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.


Macros

For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)


Memory Management

Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:

FunctionDescription
emalloc()Serves as replacement for malloc().
efree()Serves as replacement for free().
estrdup()Serves as replacement for strdup().
estrndup()Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.
ecalloc()Serves as replacement for calloc().
erealloc()Serves as replacement for realloc().

emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these previously allocated blocks. Memory handled by the e*() functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated.

Avvertimento

To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks.

Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it is not yet extensively covered here.


Directory and File Functions

The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.

Zend FunctionRegular C Function
V_GETCWD()getcwd()
V_FOPEN()fopen()
V_OPEN()open()
V_CHDIR()chdir()
V_GETWD()getwd()
V_CHDIR_FILE() Takes a file path as an argument and changes the current working directory to that file's directory.
V_STAT()stat()
V_LSTAT()lstat()


String Handling

Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)


Complex Types

Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.

Nota: To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.


PHP's Automatic Build System

PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see http://www.gnu.org/software/m4/manual/m4.html)

All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.

Step by step, the process looks like this:
:~/cvs/php4/ext:> ./ext_skel --extname=my_module
Creating directory my_module
Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/my_module/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-my_module
5.  $ make
6.  $ ./php -f ext/my_module/my_module.php
7.  $ vi ext/my_module/my_module.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run buildconf, which regenerates the configure script by searching through the ext directory and including all found config.m4 files.

The default config.m4 shown in Esempio 46-1 is a bit more complex:

Esempio 46-1. The default config.m4.

dnl $Id: build.xml,v 1.1 2005/08/21 16:27:06 goba Exp $
dnl config.m4 for extension my_module

dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.

dnl If your extension references something external, use with:

dnl PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
dnl [  --with-my_module             Include my_module support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(my_module, whether to enable my_module support,
dnl Make sure that the comment is aligned:
dnl [  --enable-my_module           Enable my_module support])

if test "$PHP_MY_MODULE" != "no"; then
  dnl Write more examples of tests here...

  dnl # --with-my_module -> check with-path
  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this
  dnl SEARCH_FOR="/include/my_module.h"  # you most likely want to change this
  dnl if test -r $PHP_MY_MODULE/; then # path given as parameter
  dnl   MY_MODULE_DIR=$PHP_MY_MODULE
  dnl else # search default path list
  dnl   AC_MSG_CHECKING([for my_module files in default path])
  dnl   for i in $SEARCH_PATH ; do
  dnl     if test -r $i/$SEARCH_FOR; then
  dnl       MY_MODULE_DIR=$i
  dnl       AC_MSG_RESULT(found in $i)
  dnl     fi
  dnl   done
  dnl fi
  dnl
  dnl if test -z "$MY_MODULE_DIR"; then
  dnl   AC_MSG_RESULT([not found])
  dnl   AC_MSG_ERROR([Please reinstall the my_module distribution])
  dnl fi

  dnl # --with-my_module -> add include path
  dnl PHP_ADD_INCLUDE($MY_MODULE_DIR/include)

  dnl # --with-my_module -> chech for lib and symbol presence
  dnl LIBNAME=my_module # you may want to change this
  dnl LIBSYMBOL=my_module # you most likely want to change this 

  dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
  dnl [
  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD)
  dnl   AC_DEFINE(HAVE_MY_MODULELIB,1,[ ])
  dnl ],[
  dnl   AC_MSG_ERROR([wrong my_module lib version or lib not found])
  dnl ],[
  dnl   -L$MY_MODULE_DIR/lib -lm -ldl
  dnl ])
  dnl
  dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD)

  PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
fi

If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.

Note: Everything prefixed with dnl is treated as a comment and is not parsed.

The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.

The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.

By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":
if test "$PHP_MY_MODULE" == "yes"; then dnl
    Action.. PHP_EXTENSION(my_module, $ext_shared)
    fi
This would require you to use --enable-my_module each time when reconfiguring and recompiling PHP.

Note: Be sure to run buildconf every time you change config.m4!

We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.


Creating Extensions

We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. Esempio 46-2 shows the source.

Esempio 46-2. A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, 
    NULL, 
    NULL, 
    NULL, 
    NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Nota: The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.


Compiling Modules

There are basically two ways to compile modules:

  • Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.

  • Compile the sources manually.

The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files.

The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.

Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.

After you run buildconf, configure --help shows the following additional modules:

--enable-array_experiments   BOOK: Enables array experiments
  --enable-call_userland       BOOK: Enables userland module
  --enable-cross_conversion    BOOK: Enables cross-conversion module
  --enable-first_module        BOOK: Enables first module
  --enable-infoprint           BOOK: Enables infoprint module
  --enable-reference_test      BOOK: Enables reference test module
  --enable-resource_test       BOOK: Enables resource test module
  --enable-variable_creation   BOOK: Enables variable-creation module

The module shown earlier in Esempio 46-2 can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually. To compile your modules manually, you need the following commands:

ActionCommand
Compilingcc -fpic -DCOMPILE_DL=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linkingcc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>

The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.

Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.

The link command is also a plain vanilla command instructing linkage as a dynamic module.

You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).

Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)


Using Extensions

Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in Esempio 46-3. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

Avvertimento

For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments.

Esempio 46-3. A test file for first_module.so.

<?php
    
// remove next comment if necessary
// dl("first_module.so"); 

$param = 2;
$return = first_module($param);

print("We sent '$param' and got '$return'");

?>

Calling this PHP file in your Web browser should give you the output shown in Figura 46-2.

Figura 46-2. Output of first_module.php.

If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.

If you've gotten this far, congratulations! You just built your first extension to PHP.


Troubleshooting

Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.

PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.


Source Discussion

Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.


Module Structure

All PHP modules follow a common structure:

  • Header file inclusions (to include all required macros, API definitions, etc.)

  • C declaration of exported functions (required to declare the Zend function block)

  • Declaration of the Zend function block

  • Declaration of the Zend module block

  • Implementation of get_module()

  • Implementation of all exported functions


Header File Inclusions

The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.

Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.


Declaring Exported Functions

To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:
ZEND_FUNCTION ( my_function );

ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:
void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );
Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:
void zif_my_function( int ht
                    , zval * return_value
                    , zval * this_ptr
                    , int return_value_used
                    , zend_executor_globals * executor_globals
                    );

Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.

The parameter list of this declaration is very important; you should keep these parameters in mind (see Tabella 46-1 for descriptions).

Tabella 46-1. Zend's Parameters to Functions Called from PHP

ParameterDescription
ht The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value.
return_value This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below.
this_ptr Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer.
return_value_used This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this).
executor_globals This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH().


Declaration of the Zend Function Block

Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Esempio 46-4.

Esempio 46-4. Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;

EntryDescription
fname Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.

In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

Nota: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!

The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

Tabella 46-2 shows a list of all the macros that you can use to define functions.

Tabella 46-2. Macros for Defining Functions

Macro NameDescription
ZEND_FE(name, arg_types) Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types) Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types) Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead.
PHP_FE(name, arg_types) Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) Old PHP API equivalent of ZEND_NAMED_FE.

Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.


Declaration of the Zend Module Block

This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Esempio 46-5.

Esempio 46-5. Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;
     
    struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;

[ Rest of the structure is not interesting here ]

};

EntryDescription
size, zend_api, zend_debug and zts Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS).
name Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules."
functions Points to the Zend function block, discussed in the preceding section.
module_startup_func This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT.
module_shutdown_func This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN.
request_startup_func This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT.
request_shutdown_func This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN.
info_func When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO.
version The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3".
Remaining structure elements These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly.

In our example, this structure is implemented as follows:
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set to First Module, then the function list is referenced, after which all startup and shutdown functions are marked as being unused.

For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Tabella 46-3. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.

Tabella 46-3. Macros to Declare Startup and Shutdown Functions

MacroDescription
ZEND_MINIT(module) Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module) Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module) Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module) Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_MINFO(module) Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION.

Creation of get_module()

This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:

#if COMPILE_DL_FIRSTMOD
     ZEND_GET_MODULE(firstmod) 
#endif

The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.

get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.

If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.


Implementation of All Exported Functions

Implementing the exported functions is the final step. The example function in first_module looks like this:
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function entry table (discussed earlier).

After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).


Summary

That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.

Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.


Accepting Arguments

One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.

PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.


Determining the Number of Arguments

Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.

The following code checks for the correct number of arguments:
if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error message (see Figura 46-3).

Figura 46-3. WRONG_PARAM_COUNT in action.

This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:
ZEND_API void wrong_param_count(void);

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }
As you can see, it calls an internal function named wrong_param_count() that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information."


Retrieving Arguments

New parameter parsing API: This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0 .

Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameteres, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.

The prototype for parameter parsing function looks like this:
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number of actual parameters passed to your function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters.

zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.

If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.

Here are some sample error messages:
Warning - ini_get_all() requires at most 1 parameter, 2 given
     Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and line number on which it occurs.

Here is the full list of type specifiers:

  • l - long

  • d - double

  • s - string (with possible null bytes) and its length

  • b - boolean

  • r - resource, stored in zval*

  • a - array, stored in zval*

  • o - object (of any class), stored in zval*

  • O - object (of class specified by class entry), stored in zval*

  • z - the actual zval*

The following characters also have a meaning in the specifier string:

  • | - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.

  • / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.

  • ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.

The best way to illustrate the usage of this function is through examples:
/* Gets a long, a string and its length, and a zval. */
long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "lsz", &l, &s, &s_len, &param) == FAILURE) {
    return;
}

/* Gets an object of class specified by my_ce, and an optional double. */
zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "O|d", &obj, my_ce, &d) == FAILURE) {
    return;
}

/* Gets an object or null, and an array.
   If null is passed for object, obj will be set to NULL. */
zval *obj;
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) {
    return;
}

/* Gets a separated array. */
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
    return;
}

/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
    return;
}

Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.

The parsing function has an extended version that allows for an additional flags argument that controls its actions.
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.

For example, here is how you would get either a set of three longs or a string:
long l1, l2, l3;
char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                             ZEND_NUM_ARGS() TSRMLS_CC,
                             "lll", &l1, &l2, &l3) == SUCCESS) {
    /* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                                    ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
    /* manipulate string */
} else {
    php_error(E_WARNING, "%s() takes either three long values or a string as argument",
              get_active_function_name(TSRMLS_C));
    return;
}

With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.


Old way of retrieving arguments (deprecated)

Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND parameter parsing API.

After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():
zval **parameter;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
  WRONG_PARAM_COUNT;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries to retrieve one argument and make it available to us via the parameter pointer.

zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.

The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.

To retrieve more than one argument, you can use a similar snippet:
zval **param1, **param2, **param3, **param4;
     
if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
    WRONG_PARAM_COUNT;

zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.


Dealing with a Variable Number of Arguments/Optional Parameters

If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.

For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:
zval **parameter_array[4];

/* get the number of arguments */
argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */
/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 4)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
First, the number of arguments is checked to make sure that it's in the accepted range. After that, zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument values.

A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in Esempio 46-6. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Esempio 46-6. PHP's implementation of variable arguments in fsockopen().

pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) {
    CLOSE_SOCK(1);
    WRONG_PARAM_COUNT;
}

switch(arg_count) {
    case 5:
        convert_to_double_ex(args[4]);
        conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0);
        timeout.tv_sec = conv / 1000000;
        timeout.tv_usec = conv % 1000000;
        /* fall-through */
    case 4:
        if (!PZVAL_IS_REF(*args[3])) {
            php_error(E_WARNING,"error string argument to fsockopen not passed by reference");
        }
        pval_copy_constructor(*args[3]);
        ZVAL_EMPTY_STRING(*args[3]);
        /* fall-through */
    case 3:
        if (!PZVAL_IS_REF(*args[2])) {
            php_error(E_WARNING,"error argument to fsockopen not passed by reference");
            return;
        }
        ZVAL_LONG(*args[2], 0);
        break;
}

convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);

key = emalloc(Z_STRLEN_P(args[0]) + 10);

fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.

This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.


Accessing Arguments

To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.

To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Tabella 46-4).

Note: All conversion functions expect a **zval as parameter.

Tabella 46-4. Argument Conversion Functions

FunctionDescription
convert_to_boolean_ex() Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE).
convert_to_long_ex() Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise.
convert_to_double_ex() Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise.
convert_to_string_ex() Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object".
convert_to_array_ex(value) Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0.
convert_to_object_ex(value) Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content.
convert_to_null_ex(value)Forces the type to become a NULL value, meaning empty.

Nota: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. Figura 46-4 shows the output.

Figura 46-4. Cross-conversion behavior of PHP.

Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.

Following is a quote from the sample module discussed previously, which makes use of the conversion functions:
zval **parameter;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

convert_to_long_ex(parameter);

RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the zval type, whose definition is shown in Esempio 46-7.

Esempio 46-7. PHP/Zend zval type definition.

typedef pval zval;
     
typedef struct _zval_struct zval;

typedef union _zvalue_value {
	long lval;					/* long value */
	double dval;				/* double value */
	struct {
		char *val;
		int len;
	} str;
	HashTable *ht;				/* hash table value */
	struct {
		zend_class_entry *ce;
		HashTable *properties;
	} obj;
} zvalue_value;

struct _zval_struct {
	/* Variable information */
	zvalue_value value;		/* value */
	unsigned char type;	/* active type */
	unsigned char is_ref;
	short refcount;
};

Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Tabella 46-5, Tabella 46-6 and Tabella 46-7.

Tabella 46-5. Zend zval Structure

EntryDescription
value Union containing this variable's contents. See Tabella 46-6 for a description.
type Contains this variable's type. For a list of available types, see Tabella 46-7.
is_ref 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.

Tabella 46-6. Zend zvalue_value Structure

EntryDescription
lvalUse this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dvalUse this property if the variable is of the type IS_DOUBLE.
str This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00.
htThis entry points to the variable's hash table entry if the variable is an array.
objUse this property if the variable is of the type IS_OBJECT.

Tabella 46-7. Zend Variable Type Constants

ConstantDescription
IS_NULLDenotes a NULL (empty) value.
IS_LONGA long (integer) value.
IS_DOUBLEA double (floating point) value.
IS_STRINGA string.
IS_ARRAYDenotes an array.
IS_OBJECTAn object.
IS_BOOLA Boolean value.
IS_RESOURCEA resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANTA constant (defined) value.

To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.

Accessing arrays and objects is a bit more complicated and is discussed later.


Dealing with Arguments Passed by Reference

If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.

What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!

We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.

Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).

zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.

This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.

To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:
my_function(&$parameter);

But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.

This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Esempio 46-8.

Esempio 46-8. Testing for referenced parameter passing.

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;

/* check for parameter being passed by reference */
if (!PZVAL_IS_REF(parameter)) {
{
    zend_error(E_WARNING, "Parameter wasn't passed by reference");
    RETURN_NULL();
}

/* make changes to the parameter */
ZVAL_LONG(parameter, 10);


Assuring Write Safety for Other Parameters

You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:
zval **parameter;
     
/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */
/* to Zend's internal data buffers */

/* make <parameter> write-safe */
SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */
/* without implying global changes */
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.

Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.


Creating Variables

When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.


Overview

To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:

zval *new_variable; 

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable); 

/* set type and variable contents here, see the following sections */ 

/* introduce this variable by the name "new_variable_name" into the symbol table */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable); 

/* the variable is now accessible to the script by using $new_variable_name */

The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.

ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.

Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.

If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():
zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
This is actually the standard method used in most modules.

The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:
zval *new_variable;
     
// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by referring EG(symbol_table).

Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.

Similarly, to get a more efficient version, you can hardcode the symbol table update:
zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
zend_hash_update(
    &EG(symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
Esempio 46-9 shows a sample source that creates two variables - local_variable with a local scope and global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.

Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.

Esempio 46-9. Creating variables with different scopes.

ZEND_FUNCTION(variable_creation)
{
    zval *new_var1, *new_var2;

    MAKE_STD_ZVAL(new_var1);
    MAKE_STD_ZVAL(new_var2);

    ZVAL_LONG(new_var1, 10);
    ZVAL_LONG(new_var2, 5);

    ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);
    ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

    RETURN_NULL();

}


Longs (Integers)

Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Esempio 46-10).

Esempio 46-10. Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long->type = IS_LONG;
new_long->value.lval = 10;
Alternatively, you can use the macro ZVAL_LONG:
zval *new_long;

MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);


Doubles (Floats)

Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.
zval *new_double;

MAKE_STD_ZVAL(new_double);

new_double->type = IS_DOUBLE;
new_double->value.dval = 3.45;
Alternatively, you can use the macro ZVAL_DOUBLE:
zval *new_double;

MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);


Strings

Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);

new_string->type = IS_STRING;
new_string->value.str.len = strlen(string_contents);
new_string->value.str.val = estrdup(string_contents);
Note the usage of Zend's estrdup() here. Of course, you can also use the predefined macro ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory.

If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.

To create empty strings, set the string length to 0 and use empty_string as contents:
new_string->type = IS_STRING;
new_string->value.str.len = 0;
new_string->value.str.val = empty_string;
Of course, there's a macro for this as well (ZVAL_EMPTY_STRING):
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);


Booleans

Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:
zval *new_bool;

MAKE_STD_ZVAL(new_bool);

new_bool->type = IS_BOOL;
new_bool->value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).


Arrays

Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.

There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().
zval *new_array;

MAKE_STD_ZVAL(new_array);

array_init(new_array);
array_init() always returns SUCCESS.

To add new elements to the array, you can use numerous functions, depending on what you want to do. Tabella 46-8, Tabella 46-9 and Tabella 46-10 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Tabella 46-8. Zend's API for Associative Arrays

FunctionDescription
add_assoc_long(zval *array, char *key, long n);() Adds an element of type long.
add_assoc_unset(zval *array, char *key);()Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int r);() Adds a resource to the array.
add_assoc_double(zval *array, char *key, double d);() Adds a floating-point value.
add_assoc_string(zval *array, char *key, char *str, int duplicate);() Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string().
add_assoc_zval(zval *array, char *key, zval *value);()Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

Tabella 46-9. Zend's API for Indexed Arrays, Part 1

FunctionDescription
add_index_long(zval *array, uint idx, long n);()Adds an element of type long.
add_index_unset(zval *array, uint idx);()Adds an unset element.
add_index_bool(zval *array, uint idx, int b);()Adds a Boolean element.
add_index_resource(zval *array, uint idx, int r);()Adds a resource to the array.
add_index_double(zval *array, uint idx, double d);()Adds a floating-point value.
add_index_string(zval *array, uint idx, char *str, int duplicate);()Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);()Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()().
add_index_zval(zval *array, uint idx, zval *value);()Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

Tabella 46-10. Zend's API for Indexed Arrays, Part 2

FunctionDescription
add_next_index_long(zval *array, long n);()Adds an element of type long.
add_next_index_unset(zval *array);()Adds an unset element.
add_next_index_bool(zval *array, int b);()Adds a Boolean element.
add_next_index_resource(zval *array, int r);()Adds a resource to the array.
add_next_index_double(zval *array, double d);()Adds a floating-point value.
add_next_index_string(zval *array, char *str, int duplicate);()Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);()Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()().
add_next_index_zval(zval *array, zval *value);()Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update()() for associative arrays (see Esempio 46-11) and zend_hash_index_update() for indexed arrays (see Esempio 46-12):

Esempio 46-11. Adding an element to an associative array.

zval *new_array, *new_element;
char *key = "element_key";
      
MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_update(new_array->value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

Esempio 46-12. Adding an element to an indexed array.

zval *new_array, *new_element;
int key = 2;

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_index_update(new_array->value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.

Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.


Objects

Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.

To initialize an object, you use the function object_init():
zval *new_object;

MAKE_STD_ZVAL(new_object);

if(object_init(new_object) != SUCCESS)
{
    // do error handling here
}
You can use the functions described in Tabella 46-11 to add members to your object.

Tabella 46-11. Zend's API for Object Creation

FunctionDescription
add_property_long(zval *object, char *key, long l);()Adds a long to the object.
add_property_unset(zval *object, char *key);()Adds an unset property to the object.
add_property_bool(zval *object, char *key, int b);()Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);()Adds a resource to the object.
add_property_double(zval *object, char *key, double d);()Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);()Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);()Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe.
add_property_zval(zval *obect, char *key, zval *container):() Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects.

Resources

Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.

For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.

Nota: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.

To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.

The Zend function to register your resource handler is defined as:
ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);

There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.

zend_register_list_destructors_ex() accepts the following parameters:

ldNormal resource destruction handler callback
pldPesistent resource destruction handler callback
type_nameA string specifying the name of your resource. It's always a good thing to specify a unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_numberThe module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.

The return value is a unique integer ID for your resource type.

The resource destruction handler (either normal or persistent resources) has the following prototype:
void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);
The passed rsrc is a pointer to the following structure:
typedef struct _zend_rsrc_list_entry {
     
    void *ptr;
    int type;
    int refcount;

} zend_rsrc_list_entry;
The member void *ptr is the actual pointer to your resource.

Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:
typedef struct {
     
    int resource_link;
    int resource_type;

} my_resource;
Our resource destruction handler is probably going to look something like this:
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

    // You most likely cast the void pointer to your structure type

    my_resource *my_rsrc = (my_resource *) rsrc->ptr;

    // Now do whatever needs to be done with you resource. Closing
    // Files, Sockets, freeing additional memory, etc.
    // Also, don't forget to actually free the memory for your resource too!

    do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

Nota: One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!

Now that we have defined

  1. what our resource is and

  2. our resource destruction handler

we can go on and do the rest of the steps:

  1. create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it

  2. define the resource name

  3. write the resource destruction handler

  4. and finally register the handler

// Somewhere in your extension, define the variable for your registered resources.
    // If you wondered what 'le' stands for: it simply means 'list entry'.
    static int le_myresource;

    // It's nice to define your resource name somewhere
    #define le_myresource_name  "My type of resource"

    [...]

    // Now actually define our resource destruction handler
    void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

        my_resource *my_rsrc = (my_resource *) rsrc->ptr;
        do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
    }

    [...]

    PHP_MINIT_FUNCTION(my_extension) {

        // Note that 'module_number' is already provided through the
        // PHP_MINIT_FUNCTION() function definition.

        le_myresource = zend_register_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);

rsrc_resultThis is an already initialized zval * container.
rsrc_pointerYour resource pointer you want to store.
rsrc_typeThe type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource.

The return value is a unique integer identifier for that resource.

What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:
rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);
     
    if (rsrc_result) {
        rsrc_result->value.lval = rsrc_id;
        rsrc_result->type = IS_RESOURCE;
    }

    return rsrc_id;
The returned rsrc_id uniquly identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
RETURN_RESOURCE(rsrc_id)

Nota: It is common practice that if you want to return the resource immidiately to the user you specify the return_value as the zval * container.

Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.

Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:
ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)

rsrcThis is your pointer which will point to your previously registered resource.
rsrc_typeThis is the typecast argument for your pointer, e.g. myresource *.
rsrc_idThis is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given.
default_rsrc_idThis integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_nameThis is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.
resource_typeThe resource_type you got back when registering the resource destruction handler. In our example this was le_myresource.

This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with NULL if there was a problem retrieving the resource.

To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.


Macros for Automatic Global Variable Creation

In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table Tabella 46-12 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Tabella 46-12. Macros for Global Variable Creation

MacroDescription
SET_VAR_STRING(name, value)Creates a new string.
SET_VAR_STRINGL(name, value, length)Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe.
SET_VAR_LONG(name, value)Creates a new long.
SET_VAR_DOUBLE(name, value)Creates a new double.

Creating Constants

Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.

To create your own constants, you can use the macros in Tabella 46-13. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

To use the flags, combine them using a inary OR:
// register a new constant of type "long"
     REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS |
     CONST_PERSISTENT);
There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module.

Tabella 46-13. Macros for Creating Constants

MacroDescription
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) Registers a new constant of type long.
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) Registers a new constant of type double.
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) Registers a new constant of type string. The specified string must reside in Zend's internal memory.
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory.

Duplicating Variable Contents: The Copy Constructor

Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).

To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:

zval *parameter;
   
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
   return;
}
   
// do modifications to the parameter here

// now we want to return the modified container:
*return_value = *parameter;
zval_copy_ctor(return_value);

The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.

If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.

The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.


Returning Values

Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.

To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Tabella 46-14 and Tabella 46-15.

Nota: The macros in Tabella 46-14 automatically return from your function, those in Tabella 46-15 only set the return value; they don't return from your function.

Tabella 46-14. Predefined Macros for Returning Values from a Function

MacroDescription
RETURN_RESOURCE(resource)Returns a resource.
RETURN_BOOL(bool)Returns a Boolean.
RETURN_NULL()Returns nothing (a NULL value).
RETURN_LONG(long)Returns a long.
RETURN_DOUBLE(double)Returns a double.
RETURN_STRING(string, duplicate) Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup().
RETURN_STRINGL(string, length, duplicate) Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however.
RETURN_EMPTY_STRING()Returns an empty string.
RETURN_FALSEReturns Boolean false.
RETURN_TRUEReturns Boolean true.

Tabella 46-15. Predefined Macros for Setting the Return Value of a Function

MacroDescription
RETVAL_RESOURCE(resource)Sets the return value to the specified resource.
RETVAL_BOOL(bool)Sets the return value to the specified Boolean value.
RETVAL_NULLSets the return value to NULL.
RETVAL_LONG(long) Sets the return value to the specified long.
RETVAL_DOUBLE(double) Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING).
RETVAL_STRINGL(string, length, duplicate) Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known.
RETVAL_EMPTY_STRING Sets the return value to an empty string.
RETVAL_FALSE Sets the return value to Boolean false.
RETVAL_TRUE Sets the return value to Boolean true.

Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.


Printing Information

Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.


zend_printf()

zend_printf() works like the standard printf(), except that it prints to Zend's output stream.


zend_error()

zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.
zend_error(E_WARNING, "This function has been called with empty arguments");
Tabella 46-16 shows a list of possible values (see Figura 46-5). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.

Tabella 46-16. Zend's Predefined Error Messages.

ErrorDescription
E_ERROR Signals an error and terminates execution of the script immediately .
E_WARNING Signals a generic warning. Execution continues.
E_PARSE Signals a parser error. Execution continues.
E_NOTICE Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini.
E_CORE_ERROR Internal error by the core; shouldn't be used by user-written modules.
E_COMPILE_ERROR Internal error by the compiler; shouldn't be used by user-written modules.
E_COMPILE_WARNING Internal warning by the compiler; shouldn't be used by user-written modules.

Figura 46-5. Display of warning messages in the browser.


Including Output in phpinfo()

After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().

PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.

Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Esempio 46-13 shows a source example and its output. To print the table footer, use php_info_print_table_end().

Esempio 46-13. Source code and screenshot for output in phpinfo().

php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();


Execution Information

You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.

Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Esempio 46-14.

Esempio 46-14. Printing execution information.

zend_printf("The name of the current function is %s<br>", get_active_function_name(TSRMLS_C));
zend_printf("The file currently executed is %s<br>", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i<br>", zend_get_executed_lineno(TSRMLS_C));


Startup and Shutdown Functions

Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.

The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).

For dynamic extensions, module and request startup/shutdown events happen at the same time.

Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.


Calling User Functions

You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.

User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.

ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,
zval *function_name, zval **retval_ptr_ptr,
int param_count, zval **params[],
int no_separation);

Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.

Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.

The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.

The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!

Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.

Esempio 46-15 shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

Esempio 46-15. Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
    zend_error(E_ERROR, "Function requires string argument");
}

TSRMSLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS)
{
    zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type<br>", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{

    print("We are in the test function!<br>");

    return("hello");

}

$return_value = call_userland("test_function");

print("Return value: \"$return_value\"<br>");
?>


Initialization File Support

PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.

To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.
PHP_INI_BEGIN()
PHP_INI_ENTRY("first_ini_entry",  "has_string_value", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("second_ini_entry", "2",                PHP_INI_SYSTEM, OnChangeSecond)
PHP_INI_ENTRY("third_ini_entry",  "xyz",              PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers.

The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.

The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:
PHP_INI_MH(OnChangeSecond);             // handler for ini-entry "second_ini_entry"

// specify ini-entries here

PHP_INI_MH(OnChangeSecond)
{

    zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value);

    return(SUCCESS);

}
The new value is given to the change handler as string in the variable new_value. When looking at the definition of PHP_INI_MH, you actually have a few parameters to use:
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,
                                  uint new_value_length, void *mh_arg1,
                                  void *mh_arg2, void *mh_arg3)
All these definitions can be found in php_ini.h. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing three additional arguments).

The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.

Access to initialization entries can also be handled with the macros shown in Tabella 46-17.

Tabella 46-17. Macros to Access Initialization Entries in PHP

MacroDescription
INI_INT(name)Returns the current value of entry name as integer (long).
INI_FLT(name)Returns the current value of entry name as float (double).
INI_STR(name)Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_BOOL(name)Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).
INI_ORIG_INT(name)Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name)Returns the original value of entry name as float (double).
INI_ORIG_STR(name)Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_ORIG_BOOL(name)Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).

Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():
ZEND_MINIT_FUNCTION(mymodule)
{

    REGISTER_INI_ENTRIES();

}

ZEND_MSHUTDOWN_FUNCTION(mymodule)
{

    UNREGISTER_INI_ENTRIES();

}


Where to Go from Here

You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.

Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.


Reference: Some Configuration Macros

config.m4

The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in Tabella 46-18.

Tabella 46-18. M4 Macros for config.m4

MacroDescription
AC_MSG_CHECKING(message)Prints a "checking <message>" text during configure.
AC_MSG_RESULT(value)Gives the result to AC_MSG_CHECKING; should specify either yes or no as value.
AC_MSG_ERROR(message)Prints message as error message during configure and aborts the script.
AC_DEFINE(name,value,description)Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module).
AC_ADD_INCLUDE(path)Adds a compiler include path; for example, used if the module needs to add search paths for header files.
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath)Specifies an additional library to link.
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest)Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest.
PHP_EXTENSION(modulename, [shared])This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>.

API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see Tabella 46-19).

Tabella 46-19. API Macros for Accessing zval Containers

MacroRefers to
Z_LVAL(zval)(zval).value.lval
Z_DVAL(zval)(zval).value.dval
Z_STRVAL(zval)(zval).value.str.val
Z_STRLEN(zval)(zval).value.str.len
Z_ARRVAL(zval)(zval).value.ht
Z_LVAL_P(zval)(*zval).value.lval
Z_DVAL_P(zval)(*zval).value.dval
Z_STRVAL_P(zval_p)(*zval).value.str.val
Z_STRLEN_P(zval_p)(*zval).value.str.len
Z_ARRVAL_P(zval_p)(*zval).value.ht
Z_LVAL_PP(zval_pp)(**zval).value.lval
Z_DVAL_PP(zval_pp)(**zval).value.dval
Z_STRVAL_PP(zval_pp)(**zval).value.str.val
Z_STRLEN_PP(zval_pp)(**zval).value.str.len
Z_ARRVAL_PP(zval_pp)(**zval).value.ht

API Functions (work in progress)

Sommario
_array_init -- ...
_object_and_properties_init -- ...
_object_init_ex -- ...
_object_init -- ...
_zend_bailout -- ...
_zend_get_parameters_array_ex -- ...
_zend_get_parameters_array -- ...
_zend_hash_add_or_update -- ...
_zend_hash_index_update_or_next_insert -- ...
_zend_hash_init_ex -- ...
_zend_hash_init -- ...
_zend_hash_merge -- ...
_zend_hash_quick_add_or_update -- ...
Z_ARRVAL_P -- 
Z_ARRVAL_PP -- 
Z_ARRVAL -- 
Z_BVAL_P -- 
Z_BVAL_PP -- 
Z_BVAL -- 
Z_DVAL_P -- 
Z_DVAL_PP -- 
Z_DVAL -- 
Z_LVAL_P -- 
Z_LVAL_PP -- 
Z_LVAL -- 
Z_OBJ_CLASS_NAME_P -- 
Z_OBJ_HANDLE_P -- 
Z_OBJ_HANDLE_PP -- 
Z_OBJ_HANDLE -- 
Z_OBJ_HANDLER_P -- 
Z_OBJ_HANDLER_PP -- 
Z_OBJ_HANDLER -- 
Z_OBJ_HT_P -- 
Z_OBJ_HT_PP -- 
Z_OBJ_HT -- 
Z_OBJCE_P -- 
Z_OBJCE_PP -- 
Z_OBJCE -- 
Z_OBJPROP_P -- 
Z_OBJPROP_PP -- 
Z_OBJPROP -- 
Z_RESVAL_P -- 
Z_RESVAL_PP -- 
Z_RESVAL -- 
Z_STRLEN_P -- 
Z_STRLEN_PP -- 
Z_STRLEN -- 
Z_STRVAL_P -- 
Z_STRVAL_PP -- 
Z_STRVAL -- 
Z_TYPE_P -- 
Z_TYPE_PP -- 
Z_TYPE -- 
ZEND_WRONG_PARAM_COUNT_WITH_RETVAL -- Generate standard error message and return custom value
add_assoc_bool_ex -- ...
add_assoc_bool -- ...
add_assoc_double_ex -- ...
add_assoc_double -- ...
add_assoc_function -- ...
add_assoc_long_ex -- ...
add_assoc_long -- ...
add_assoc_null_ex -- ...
add_assoc_null -- ...
add_assoc_resource_ex -- ...
add_assoc_resource -- ...
add_assoc_string_ex -- ...
add_assoc_string -- ...
add_assoc_stringl_ex -- ...
add_assoc_stringl -- ...
add_assoc_zval_ex -- ...
add_assoc_zval -- ...
add_get_assoc_string_ex -- ...
add_get_assoc_string -- ...
add_get_assoc_stringl_ex -- ...
add_get_assoc_stringl -- ...
add_get_index_double -- ...
add_get_index_long -- ...
add_get_index_string -- ...
add_get_index_stringl -- ...
add_index_bool -- ...
add_index_double -- ...
add_index_long -- ...
add_index_null -- ...
add_index_resource -- ...
add_index_string -- ...
add_index_stringl -- ...
add_index_zval -- ...
add_next_index_bool -- ...
add_next_index_double -- ...
add_next_index_long -- ...
add_next_index_null -- ...
add_next_index_resource -- ...
add_next_index_string -- ...
add_next_index_stringl -- ...
add_next_index_zval -- ...
add_property_bool_ex -- ...
add_property_bool -- ...
add_property_double_ex -- ...
add_property_double -- ...
add_property_long_ex -- ...
add_property_long -- ...
add_property_null_ex -- ...
add_property_null -- ...
add_property_resource_ex -- ...
add_property_resource -- ...
add_property_string_ex -- ...
add_property_string -- ...
add_property_stringl_ex -- ...
add_property_stringl -- ...
add_property_zval_ex -- ...
add_property_zval -- ...
array_init -- ...
call_user_function_ex -- ...
call_user_function -- ...
free_estring -- ...
get_zend_version -- ...
ZEND_WRONG_PARAM_COUNT -- Generate standard error message for wrong parameter count in function or method call
object_and_properties_init -- ...
object_init_ex -- ...
object_init -- ...
zend_call_function -- ...
zend_check_magic_method_implementation -- ...
zend_class_implements -- ...
zend_copy_parameters_array -- ...
zend_declare_property_bool -- ...
zend_declare_property_double -- ...
zend_declare_property_ex -- ...
zend_declare_property_long -- ...
zend_declare_property_null -- ...
zend_declare_property_string -- ...
zend_declare_property_stringl -- ...
zend_declare_property -- ...
zend_delete_global_variable -- ...
zend_disable_class -- ...
zend_disable_function -- ...
zend_error -- ...
zend_get_class_entry -- ...
zend_get_configuration_directive -- ...
zend_get_hash_value -- ...
zend_get_module_started -- ...
zend_get_module_version -- ...
zend_get_object_classname -- ...
zend_get_parameters_array_ex -- ...
zend_get_parameters_array -- ...
zend_get_parameters_ex -- ...
zend_get_parameters -- ...
zend_get_std_object_handlers -- ...
zend_hash_add_empty_element -- ...
zend_hash_add -- ...
zend_hash_apply_with_argument -- ...
zend_hash_apply_with_arguments -- ...
zend_hash_apply -- ...
zend_hash_clean -- ...
zend_hash_compare -- ...
zend_hash_copy -- ...
zend_hash_del_key_or_index -- ...
zend_hash_destroy -- ...
zend_hash_exists -- ...
zend_hash_find -- ...
zend_hash_func -- ...
zend_hash_get_current_data_ex -- ...
zend_hash_get_current_key_ex -- ...
zend_hash_get_current_key_type_ex -- ...
zend_hash_graceful_destroy -- ...
zend_hash_graceful_reverse_destroy -- ...
zend_hash_index_exists -- ...
zend_hash_index_find -- ...
zend_hash_init_ex -- ...
zend_hash_init -- ...
zend_hash_internal_pointer_end_ex -- ...
zend_hash_internal_pointer_reset_ex -- ...
zend_hash_merge_ex -- ...
zend_hash_minmax -- ...
zend_hash_move_backwards_ex -- ...
zend_hash_move_forward_ex -- ...
zend_hash_next_free_element -- ...
zend_hash_num_elements -- ...
zend_hash_quick_add -- ...
zend_hash_quick_exists -- ...
zend_hash_quick_find -- ...
zend_hash_quick_update -- ...
zend_hash_rehash -- ...
zend_hash_reverse_apply -- ...
zend_hash_sort -- ...
zend_hash_update_current_key_ex -- ...
zend_hash_update -- ...
zend_is_callable_ex -- ...
zend_is_callable -- ...
zend_make_callable -- ...
zend_make_printable_zval -- ...
zend_merge_properties -- ...
zend_message_dispatcher -- ...
zend_object_create_proxy -- ...
zend_object_store_ctor_failed -- ...
zend_object_store_get_object -- ...
zend_object_store_set_object -- ...
zend_objects_store_add_ref -- ...
zend_objects_store_call_destructors -- ...
zend_objects_store_clone_obj -- ...
zend_objects_store_del_ref -- ...
zend_objects_store_destroy -- ...
zend_objects_store_free_object_storage -- ...
zend_objects_store_init -- ...
zend_objects_store_mark_destructed -- ...
zend_objects_store_put -- ...
zend_output_debug_string -- ...
zend_parse_method_parameters_ex -- ...
zend_parse_method_parameters -- ...
zend_parse_parameters_ex -- ...
zend_parse_parameters -- ...
zend_print_flat_zval_r -- ...
zend_print_zval_ex -- ...
zend_print_zval_r_ex -- ...
zend_print_zval_r -- ...
zend_print_zval -- ...
zend_read_property -- ...
zend_register_functions -- ...
zend_register_internal_class_ex -- ...
zend_register_internal_class -- ...
zend_register_internal_interface -- ...
zend_register_internal_module -- ...
zend_register_module_ex -- ...
zend_register_module -- ...
zend_reset_all_cv -- ...
zend_startup_module_ex -- ...
zend_startup_module -- ...
zend_startup_modules -- ...
zend_unregister_functions -- ...
zend_update_class_constants -- ...
zend_update_property_bool -- ...
zend_update_property_double -- ...
zend_update_property_long -- ...
zend_update_property_null -- ...
zend_update_property_string -- ...
zend_update_property_stringl -- ...
zend_update_property -- ...
zend_wrong_param_count -- Generate standard error message for wrong parameter count in function or method call
zend_zval_type_name -- Returns the PHP type name for a given zval

_array_init

(no version information, might be only in CVS)

_array_init -- ...

Descrizione

#include <zend_API.h>

int _array_init ( zval* arg ZEND_FILE_LINE_DC )

...

Elenco dei parametri

arg ZEND_FILE_LINE_DC

...

Valori restituiti

...

_object_and_properties_init

(no version information, might be only in CVS)

_object_and_properties_init -- ...

Descrizione

#include <zend_API.h>

int _object_and_properties_init ( zval* arg, zend_class_entry* ce, HashTable* properties ZEND_FILE_LINE_DC TSRMLS_DC )

...

Elenco dei parametri

arg

...

ce

...

properties ZEND_FILE_LINE_DC TSRMLS_DC

...

Valori restituiti

...

_object_init_ex

(no version information, might be only in CVS)

_object_init_ex -- ...

Descrizione

#include <zend_API.h>

int _object_init_ex ( zval* arg, zend_class_entry* ce ZEND_FILE_LINE_DC TSRMLS_DC )

...

Elenco dei parametri

arg

...

ce ZEND_FILE_LINE_DC TSRMLS_DC

...

Valori restituiti

...

_object_init

(no version information, might be only in CVS)

_object_init -- ...

Descrizione

#include <zend_API.h>

int _object_init ( zval* arg ZEND_FILE_LINE_DC TSRMLS_DC )

...

Elenco dei parametri

arg ZEND_FILE_LINE_DC TSRMLS_DC

...

Valori restituiti

...

_zend_bailout

(no version information, might be only in CVS)

_zend_bailout -- ...

Descrizione

#include <zend.h>

void _zend_bailout ( char* filename, uint lineno )

...

Elenco dei parametri

filename

...

lineno

...

Valori restituiti

...

_zend_get_parameters_array_ex

(no version information, might be only in CVS)

_zend_get_parameters_array_ex -- ...

Descrizione

#include <zend_API.h>

int _zend_get_parameters_array_ex ( int param_count, zval*** argument_array TSRMLS_DC )

...

Elenco dei parametri

param_count

...

argument_array TSRMLS_DC

...

Valori restituiti

...

_zend_get_parameters_array

(no version information, might be only in CVS)

_zend_get_parameters_array -- ...

Descrizione

#include <zend_API.h>

int _zend_get_parameters_array ( int ht, int param_count, zval** argument_array TSRMLS_DC )

...

Elenco dei parametri

ht

...

param_count

...

argument_array TSRMLS_DC

...

Valori restituiti

...

_zend_hash_add_or_update

(no version information, might be only in CVS)

_zend_hash_add_or_update -- ...

Descrizione

#include <zend_hash.h>

int _zend_hash_add_or_update ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest, int flag ZEND_FILE_LINE_DC )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

flag ZEND_FILE_LINE_DC

...

Valori restituiti

...

_zend_hash_index_update_or_next_insert

(no version information, might be only in CVS)

_zend_hash_index_update_or_next_insert -- ...

Descrizione

#include <zend_hash.h>

int _zend_hash_index_update_or_next_insert ( HashTable* ht, ulong h, void* pData, uint nDataSize, void** pDest, int flag ZEND_FILE_LINE_DC )

...

Elenco dei parametri

ht

...

h

...

pData

...

nDataSize

...

pDest

...

flag ZEND_FILE_LINE_DC

...

Valori restituiti

...

_zend_hash_init_ex

(no version information, might be only in CVS)

_zend_hash_init_ex -- ...

Descrizione

#include <zend_hash.h>

int _zend_hash_init_ex ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool bApplyProtection ZEND_FILE_LINE_DC )

...

Elenco dei parametri

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

bApplyProtection ZEND_FILE_LINE_DC

...

Valori restituiti

...

_zend_hash_init

(no version information, might be only in CVS)

_zend_hash_init -- ...

Descrizione

#include <zend_hash.h>

int _zend_hash_init ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC )

...

Elenco dei parametri

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent ZEND_FILE_LINE_DC

...

Valori restituiti

...

_zend_hash_merge

(no version information, might be only in CVS)

_zend_hash_merge -- ...

Descrizione

#include <zend_hash.h>

void _zend_hash_merge ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, void* tmp, uint size, int overwrite ZEND_FILE_LINE_DC )

...

Elenco dei parametri

target

...

source

...

pCopyConstructor

...

tmp

...

size

...

overwrite ZEND_FILE_LINE_DC

...

Valori restituiti

...

_zend_hash_quick_add_or_update

(no version information, might be only in CVS)

_zend_hash_quick_add_or_update -- ...

Descrizione

#include <zend_hash.h>

int _zend_hash_quick_add_or_update ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest, int flag ZEND_FILE_LINE_DC )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

flag ZEND_FILE_LINE_DC

...

Valori restituiti

...

Z_ARRVAL_P

(no version information, might be only in CVS)

Z_ARRVAL_P -- 

Descrizione

#include <zend_operators.h>

void Z_ARRVAL_P ( void )

Z_ARRVAL_PP

(no version information, might be only in CVS)

Z_ARRVAL_PP -- 

Descrizione

#include <zend_operators.h>

void Z_ARRVAL_PP ( void )

Z_ARRVAL

(no version information, might be only in CVS)

Z_ARRVAL -- 

Descrizione

#include <zend_operators.h>

void Z_ARRVAL ( void )

Z_BVAL_P

(no version information, might be only in CVS)

Z_BVAL_P -- 

Descrizione

#include <zend_operators.h>

void Z_BVAL_P ( void )

Z_BVAL_PP

(no version information, might be only in CVS)

Z_BVAL_PP -- 

Descrizione

#include <zend_operators.h>

void Z_BVAL_PP ( void )

Z_BVAL

(no version information, might be only in CVS)

Z_BVAL -- 

Descrizione

#include <zend_operators.h>

void Z_BVAL ( void )

Z_DVAL_P

(no version information, might be only in CVS)

Z_DVAL_P -- 

Descrizione

#include <zend_operators.h>

void Z_DVAL_P ( void )

Z_DVAL_PP

(no version information, might be only in CVS)

Z_DVAL_PP -- 

Descrizione

#include <zend_operators.h>

void Z_DVAL_PP ( void )

Z_DVAL

(no version information, might be only in CVS)

Z_DVAL -- 

Descrizione

#include <zend_operators.h>

void Z_DVAL ( void )

Z_LVAL_P

(no version information, might be only in CVS)

Z_LVAL_P -- 

Descrizione

#include <zend_operators.h>

void Z_LVAL_P ( void )

Z_LVAL_PP

(no version information, might be only in CVS)

Z_LVAL_PP -- 

Descrizione

#include <zend_operators.h>

void Z_LVAL_PP ( void )

Z_LVAL

(no version information, might be only in CVS)

Z_LVAL -- 

Descrizione

#include <zend_operators.h>

void Z_LVAL ( void )

Z_OBJ_CLASS_NAME_P

(no version information, might be only in CVS)

Z_OBJ_CLASS_NAME_P -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_CLASS_NAME_P ( void )

Z_OBJ_HANDLE_P

(no version information, might be only in CVS)

Z_OBJ_HANDLE_P -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HANDLE_P ( void )

Z_OBJ_HANDLE_PP

(no version information, might be only in CVS)

Z_OBJ_HANDLE_PP -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HANDLE_PP ( void )

Z_OBJ_HANDLE

(no version information, might be only in CVS)

Z_OBJ_HANDLE -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HANDLE ( void )

Z_OBJ_HANDLER_P

(no version information, might be only in CVS)

Z_OBJ_HANDLER_P -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HANDLER_P ( void )

Z_OBJ_HANDLER_PP

(no version information, might be only in CVS)

Z_OBJ_HANDLER_PP -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HANDLER_PP ( void )

Z_OBJ_HANDLER

(no version information, might be only in CVS)

Z_OBJ_HANDLER -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HANDLER ( void )

Z_OBJ_HT_P

(no version information, might be only in CVS)

Z_OBJ_HT_P -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HT_P ( void )

Z_OBJ_HT_PP

(no version information, might be only in CVS)

Z_OBJ_HT_PP -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HT_PP ( void )

Z_OBJ_HT

(no version information, might be only in CVS)

Z_OBJ_HT -- 

Descrizione

#include <zend_operators.h>

void Z_OBJ_HT ( void )

Z_OBJCE_P

(no version information, might be only in CVS)

Z_OBJCE_P -- 

Descrizione

#include <zend_operators.h>

void Z_OBJCE_P ( void )

Z_OBJCE_PP

(no version information, might be only in CVS)

Z_OBJCE_PP -- 

Descrizione

#include <zend_operators.h>

void Z_OBJCE_PP ( void )

Z_OBJCE

(no version information, might be only in CVS)

Z_OBJCE -- 

Descrizione

#include <zend_operators.h>

void Z_OBJCE ( void )

Z_OBJPROP_P

(no version information, might be only in CVS)

Z_OBJPROP_P -- 

Descrizione

#include <zend_operators.h>

void Z_OBJPROP_P ( void )

Z_OBJPROP_PP

(no version information, might be only in CVS)

Z_OBJPROP_PP -- 

Descrizione

#include <zend_operators.h>

void Z_OBJPROP_PP ( void )

Z_OBJPROP

(no version information, might be only in CVS)

Z_OBJPROP -- 

Descrizione

#include <zend_operators.h>

void Z_OBJPROP ( void )

Z_RESVAL_P

(no version information, might be only in CVS)

Z_RESVAL_P -- 

Descrizione

#include <zend_operators.h>

void Z_RESVAL_P ( void )

Z_RESVAL_PP

(no version information, might be only in CVS)

Z_RESVAL_PP -- 

Descrizione

#include <zend_operators.h>

void Z_RESVAL_PP ( void )

Z_RESVAL

(no version information, might be only in CVS)

Z_RESVAL -- 

Descrizione

#include <zend_operators.h>

void Z_RESVAL ( void )

Z_STRLEN_P

(no version information, might be only in CVS)

Z_STRLEN_P -- 

Descrizione

#include <zend_operators.h>

void Z_STRLEN_P ( void )

Z_STRLEN_PP

(no version information, might be only in CVS)

Z_STRLEN_PP -- 

Descrizione

#include <zend_operators.h>

void Z_STRLEN_PP ( void )

Z_STRLEN

(no version information, might be only in CVS)

Z_STRLEN -- 

Descrizione

#include <zend_operators.h>

void Z_STRLEN ( void )

Z_STRVAL_P

(no version information, might be only in CVS)

Z_STRVAL_P -- 

Descrizione

#include <zend_operators.h>

void Z_STRVAL_P ( void )

Z_STRVAL_PP

(no version information, might be only in CVS)

Z_STRVAL_PP -- 

Descrizione

#include <zend_operators.h>

void Z_STRVAL_PP ( void )

Z_STRVAL

(no version information, might be only in CVS)

Z_STRVAL -- 

Descrizione

#include <zend_operators.h>

void Z_STRVAL ( void )

Z_TYPE_P

(no version information, might be only in CVS)

Z_TYPE_P -- 

Descrizione

#include <zend_operators.h>

void Z_TYPE_P ( void )

Z_TYPE_PP

(no version information, might be only in CVS)

Z_TYPE_PP -- 

Descrizione

#include <zend_operators.h>

void Z_TYPE_PP ( void )

Z_TYPE

(no version information, might be only in CVS)

Z_TYPE -- 

Descrizione

#include <zend_operators.h>

void Z_TYPE ( void )

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL

(no version information, might be only in CVS)

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL -- Generate standard error message and return custom value

Descrizione

#include <zend_API.h>

void ZEND_WRONG_PARAM_COUNT_WITH_RETVAL ( mixed return_value )

Nota: This macro is part of the API but not used in any bundled or PECL extension

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters and returns its parameter to the calling function. The macro automaticly puts the right function name and class name (if needed) into the error message.

The return_value parameter is returned to the calling function of the current one.

ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() is actually a convenience wrapper for zend_wrong_param_count().

add_assoc_bool_ex

(no version information, might be only in CVS)

add_assoc_bool_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_bool_ex ( zval* arg, char* key, uint key_len, int b )

...

Elenco dei parametri

arg

...

key

...

key_len

...

b

...

Valori restituiti

...

add_assoc_bool

(no version information, might be only in CVS)

add_assoc_bool -- ...

Descrizione

#include <zend_API.h>

int add_assoc_bool ( zval* arg, char* key, int b )

...

Elenco dei parametri

arg

...

key

...

b

...

Valori restituiti

...

add_assoc_double_ex

(no version information, might be only in CVS)

add_assoc_double_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_double_ex ( zval* arg, char* key, uint key_len, double d )

...

Elenco dei parametri

arg

...

key

...

key_len

...

d

...

Valori restituiti

...

add_assoc_double

(no version information, might be only in CVS)

add_assoc_double -- ...

Descrizione

#include <zend_API.h>

int add_assoc_double ( zval* arg, char* key, double d )

...

Elenco dei parametri

arg

...

key

...

d

...

Valori restituiti

...

add_assoc_function

(no version information, might be only in CVS)

add_assoc_function -- ...

Descrizione

#include <zend_API.h>

int add_assoc_function ( zval* arg, char* key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS) )

...

Elenco dei parametri

arg

...

key

...

(*function_ptr)(INTERNAL_FUNCTION_PARAMETERS)

...

Valori restituiti

...

add_assoc_long_ex

(no version information, might be only in CVS)

add_assoc_long_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_long_ex ( zval* arg, char* key, uint key_len, long n )

...

Elenco dei parametri

arg

...

key

...

key_len

...

n

...

Valori restituiti

...

add_assoc_long

(no version information, might be only in CVS)

add_assoc_long -- ...

Descrizione

#include <zend_API.h>

int add_assoc_long ( zval* arg, char* key, long n )

...

Elenco dei parametri

arg

...

key

...

n

...

Valori restituiti

...

add_assoc_null_ex

(no version information, might be only in CVS)

add_assoc_null_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_null_ex ( zval* arg, char* key, uint key_len )

...

Elenco dei parametri

arg

...

key

...

key_len

...

Valori restituiti

...

add_assoc_null

(no version information, might be only in CVS)

add_assoc_null -- ...

Descrizione

#include <zend_API.h>

int add_assoc_null ( zval* arg, char* key )

...

Elenco dei parametri

arg

...

key

...

Valori restituiti

...

add_assoc_resource_ex

(no version information, might be only in CVS)

add_assoc_resource_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_resource_ex ( zval* arg, char* key, uint key_len, int r )

...

Elenco dei parametri

arg

...

key

...

key_len

...

r

...

Valori restituiti

...

add_assoc_resource

(no version information, might be only in CVS)

add_assoc_resource -- ...

Descrizione

#include <zend_API.h>

int add_assoc_resource ( zval* arg, char* key, int r )

...

Elenco dei parametri

arg

...

key

...

r

...

Valori restituiti

...

add_assoc_string_ex

(no version information, might be only in CVS)

add_assoc_string_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate )

...

Elenco dei parametri

arg

...

key

...

key_len

...

str

...

duplicate

...

Valori restituiti

...

add_assoc_string

(no version information, might be only in CVS)

add_assoc_string -- ...

Descrizione

#include <zend_API.h>

int add_assoc_string ( zval* arg, char* str, uint key_len, int duplicate )

...

Elenco dei parametri

arg

...

str

...

key_len

...

duplicate

...

Valori restituiti

...

add_assoc_stringl_ex

(no version information, might be only in CVS)

add_assoc_stringl_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate )

...

Elenco dei parametri

arg

...

key

...

key_len

...

str

...

length

...

duplicate

...

Valori restituiti

...

add_assoc_stringl

(no version information, might be only in CVS)

add_assoc_stringl -- ...

Descrizione

#include <zend_API.h>

int add_assoc_stringl ( zval* arg, char* str, int duplicate )

...

Elenco dei parametri

arg

...

str

...

duplicate

...

Valori restituiti

...

add_assoc_zval_ex

(no version information, might be only in CVS)

add_assoc_zval_ex -- ...

Descrizione

#include <zend_API.h>

int add_assoc_zval_ex ( zval* arg, char* key, uint key_len, zval* value )

...

Elenco dei parametri

arg

...

key

...

key_len

...

value

...

Valori restituiti

...

add_assoc_zval

(no version information, might be only in CVS)

add_assoc_zval -- ...

Descrizione

#include <zend_API.h>

int add_assoc_zval ( zval* arg, char* key, zval* value )

...

Elenco dei parametri

arg

...

key

...

value

...

Valori restituiti

...

add_get_assoc_string_ex

(no version information, might be only in CVS)

add_get_assoc_string_ex -- ...

Descrizione

#include <zend_API.h>

int add_get_assoc_string_ex ( zval* arg, char* key, uint key_len, char* str, void** dest, int duplicate )

...

Elenco dei parametri

arg

...

key

...

key_len

...

str

...

dest

...

duplicate

...

Valori restituiti

...

add_get_assoc_string

(no version information, might be only in CVS)

add_get_assoc_string -- ...

Descrizione

#include <zend_API.h>

int add_get_assoc_string ( zval* arg, char* key, char* str, void* *dest, int duplicate )

...

Elenco dei parametri

arg

...

str

...

*dest

...

duplicate

...

Valori restituiti

...

add_get_assoc_stringl_ex

(no version information, might be only in CVS)

add_get_assoc_stringl_ex -- ...

Descrizione

#include <zend_API.h>

int add_get_assoc_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, void** dest, int duplicate )

...

Elenco dei parametri

arg

...

key

...

key_len

...

str

...

length

...

dest

...

duplicate

...

Valori restituiti

...

add_get_assoc_stringl

(no version information, might be only in CVS)

add_get_assoc_stringl -- ...

Descrizione

#include <zend_API.h>

int add_get_assoc_stringl ( zval* arg, char* str, uint length, void* *dest, int duplicate )

...

Elenco dei parametri

arg

...

str

...

length

...

*dest

...

duplicate

...

Valori restituiti

...

add_get_index_double

(no version information, might be only in CVS)

add_get_index_double -- ...

Descrizione

#include <zend_API.h>

int add_get_index_double ( zval* arg, uint idx, double d, void** dest )

...

Elenco dei parametri

arg

...

idx

...

d

...

dest

...

Valori restituiti

...

add_get_index_long

(no version information, might be only in CVS)

add_get_index_long -- ...

Descrizione

#include <zend_API.h>

int add_get_index_long ( zval* arg, uint idx, long l, void** dest )

...

Elenco dei parametri

arg

...

idx

...

l

...

dest

...

Valori restituiti

...

add_get_index_string

(no version information, might be only in CVS)

add_get_index_string -- ...

Descrizione

#include <zend_API.h>

int add_get_index_string ( zval* arg, uint idx, char* str, void** dest, int duplicate )

...

Elenco dei parametri

arg

...

idx

...

str

...

dest

...

duplicate

...

Valori restituiti

...

add_get_index_stringl

(no version information, might be only in CVS)

add_get_index_stringl -- ...

Descrizione

#include <zend_API.h>

int add_get_index_stringl ( zval* arg, uint idx, char* str, uint length, void** dest, int duplicate )

...

Elenco dei parametri

arg

...

idx

...

str

...

length

...

dest

...

duplicate

...

Valori restituiti

...

add_index_bool

(no version information, might be only in CVS)

add_index_bool -- ...

Descrizione

#include <zend_API.h>

int add_index_bool ( zval* arg, uint idx, int b )

...

Elenco dei parametri

arg

...

idx

...

b

...

Valori restituiti

...

add_index_double

(no version information, might be only in CVS)

add_index_double -- ...

Descrizione

#include <zend_API.h>

int add_index_double ( zval* arg, uint idx, double d )

...

Elenco dei parametri

arg

...

idx

...

d

...

Valori restituiti

...

add_index_long

(no version information, might be only in CVS)

add_index_long -- ...

Descrizione

#include <zend_API.h>

int add_index_long ( zval* arg, uint idx, long n )

...

Elenco dei parametri

arg

...

idx

...

n

...

Valori restituiti

...

add_index_null

(no version information, might be only in CVS)

add_index_null -- ...

Descrizione

#include <zend_API.h>

int add_index_null ( zval* arg, uint idx )

...

Elenco dei parametri

arg

...

idx

...

Valori restituiti

...

add_index_resource

(no version information, might be only in CVS)

add_index_resource -- ...

Descrizione

#include <zend_API.h>

int add_index_resource ( zval* arg, uint idx, int r )

...

Elenco dei parametri

arg

...

idx

...

r

...

Valori restituiti

...

add_index_string

(no version information, might be only in CVS)

add_index_string -- ...

Descrizione

#include <zend_API.h>

int add_index_string ( zval* arg, uint idx, char* str, int duplicate )

...

Elenco dei parametri

arg

...

idx

...

str

...

duplicate

...

Valori restituiti

...

add_index_stringl

(no version information, might be only in CVS)

add_index_stringl -- ...

Descrizione

#include <zend_API.h>

int add_index_stringl ( zval* arg, uint idx, char* str, uint length, int duplicate )

...

Elenco dei parametri

arg

...

idx

...

str

...

length

...

duplicate

...

Valori restituiti

...

add_index_zval

(no version information, might be only in CVS)

add_index_zval -- ...

Descrizione

#include <zend_API.h>

int add_index_zval ( zval* arg, uint index, zval* value )

...

Elenco dei parametri

arg

...

index

...

value

...

Valori restituiti

...

add_next_index_bool

(no version information, might be only in CVS)

add_next_index_bool -- ...

Descrizione

#include <zend_API.h>

int add_next_index_bool ( zval* arg, int b )

...

Elenco dei parametri

arg

...

b

...

Valori restituiti

...

add_next_index_double

(no version information, might be only in CVS)

add_next_index_double -- ...

Descrizione

#include <zend_API.h>

int add_next_index_double ( zval* arg, double d )

...

Elenco dei parametri

arg

...

d

...

Valori restituiti

...

add_next_index_long

(no version information, might be only in CVS)

add_next_index_long -- ...

Descrizione

#include <zend_API.h>

int add_next_index_long ( zval* arg, long n )

...

Elenco dei parametri

arg

...

n

...

Valori restituiti

...

add_next_index_null

(no version information, might be only in CVS)

add_next_index_null -- ...

Descrizione

#include <zend_API.h>

int add_next_index_null ( zval* arg )

...

Elenco dei parametri

arg

...

Valori restituiti

...

add_next_index_resource

(no version information, might be only in CVS)

add_next_index_resource -- ...

Descrizione

#include <zend_API.h>

int add_next_index_resource ( zval* arg, int r )

...

Elenco dei parametri

arg

...

r

...

Valori restituiti

...

add_next_index_string

(no version information, might be only in CVS)

add_next_index_string -- ...

Descrizione

#include <zend_API.h>

int add_next_index_string ( zval* arg, char* str, int duplicate )

...

Elenco dei parametri

arg

...

str

...

duplicate

...

Valori restituiti

...

add_next_index_stringl

(no version information, might be only in CVS)

add_next_index_stringl -- ...

Descrizione

#include <zend_API.h>

int add_next_index_stringl ( zval* arg, char* str, uint length, int duplicate )

...

Elenco dei parametri

arg

...

str

...

length

...

duplicate

...

Valori restituiti

...

add_next_index_zval

(no version information, might be only in CVS)

add_next_index_zval -- ...

Descrizione

#include <zend_API.h>

int add_next_index_zval ( zval* arg, zval* value )

...

Elenco dei parametri

arg

...

value

...

Valori restituiti

...

add_property_bool_ex

(no version information, might be only in CVS)

add_property_bool_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_bool_ex ( zval* arg, char* key, uint key_len, int b TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

b TSRMLS_DC

...

Valori restituiti

...

add_property_bool

(no version information, might be only in CVS)

add_property_bool -- ...

Descrizione

#include <zend_API.h>

int add_property_bool ( zval* arg, char* key, int b )

...

Elenco dei parametri

arg

...

key

...

b

...

Valori restituiti

...

add_property_double_ex

(no version information, might be only in CVS)

add_property_double_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_double_ex ( zval* arg, char* key, uint key_len, double d TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

d TSRMLS_DC

...

Valori restituiti

...

add_property_double

(no version information, might be only in CVS)

add_property_double -- ...

Descrizione

#include <zend_API.h>

int add_property_double ( zval* arg, char* key, double d )

...

Elenco dei parametri

arg

...

key

...

d

...

Valori restituiti

...

add_property_long_ex

(no version information, might be only in CVS)

add_property_long_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_long_ex ( zval* arg, char* key, uint key_len, long l TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

l TSRMLS_DC

...

Valori restituiti

...

add_property_long

(no version information, might be only in CVS)

add_property_long -- ...

Descrizione

#include <zend_API.h>

int add_property_long ( zval* arg, char* key, long l )

...

Elenco dei parametri

arg

...

key

...

l

...

Valori restituiti

...

add_property_null_ex

(no version information, might be only in CVS)

add_property_null_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_null_ex ( zval* arg, char* key, uint key_len TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len TSRMLS_DC

...

Valori restituiti

...

add_property_null

(no version information, might be only in CVS)

add_property_null -- ...

Descrizione

#include <zend_API.h>

int add_property_null ( zval* arg, char* key )

...

Elenco dei parametri

arg

...

key

...

Valori restituiti

...

add_property_resource_ex

(no version information, might be only in CVS)

add_property_resource_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_resource_ex ( zval* arg, char* key, uint key_len, long r TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

r TSRMLS_DC

...

Valori restituiti

...

add_property_resource

(no version information, might be only in CVS)

add_property_resource -- ...

Descrizione

#include <zend_API.h>

int add_property_resource ( zval* arg, char* key, long r )

...

Elenco dei parametri

arg

...

key

...

key_len

...

Valori restituiti

...

add_property_string_ex

(no version information, might be only in CVS)

add_property_string_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

str

...

duplicate TSRMLS_DC

...

Valori restituiti

...

add_property_string

(no version information, might be only in CVS)

add_property_string -- ...

Descrizione

#include <zend_API.h>

int add_property_string ( zval* arg, char* key, char* str, int duplicate )

...

Elenco dei parametri

arg

...

key

...

str

...

duplicate

...

Valori restituiti

...

add_property_stringl_ex

(no version information, might be only in CVS)

add_property_stringl_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

str

...

length

...

duplicate TSRMLS_DC

...

Valori restituiti

...

add_property_stringl

(no version information, might be only in CVS)

add_property_stringl -- ...

Descrizione

#include <zend_API.h>

int add_property_stringl ( zval* arg, char* key, char* str, uint length, int duplicate )

...

Elenco dei parametri

arg

...

key

...

str

...

length

...

duplicate

...

Valori restituiti

...

add_property_zval_ex

(no version information, might be only in CVS)

add_property_zval_ex -- ...

Descrizione

#include <zend_API.h>

int add_property_zval_ex ( zval* arg, char* key, uint key_len, zval* value TSRMLS_DC )

...

Elenco dei parametri

arg

...

key

...

key_len

...

value TSRMLS_DC

...

Valori restituiti

...

add_property_zval

(no version information, might be only in CVS)

add_property_zval -- ...

Descrizione

#include <zend_API.h>

int add_property_zval ( zval* arg, char* key, zval* value )

...

Elenco dei parametri

arg

...

key

...

value

...

Valori restituiti

...

array_init

(no version information, might be only in CVS)

array_init -- ...

Descrizione

#include <zend_API.h>

int array_init ( zval* arg )

...

Elenco dei parametri

arg

...

Valori restituiti

...

call_user_function_ex

(no version information, might be only in CVS)

call_user_function_ex -- ...

Descrizione

#include <zend_API.h>

int call_user_function_ex ( HashTable* function_table, zval** object_pp, zval* function_name, zval** retval_ptr_ptr, zend_uint param_count, zval** params[], int no_separation, HashTable* symbol_table TSRMLS_DC )

...

Elenco dei parametri

function_table

...

object_pp

...

function_name

...

retval_ptr_ptr

...

param_count

...

params[]

...

no_separation

...

symbol_table TSRMLS_DC

...

Valori restituiti

...

call_user_function

(no version information, might be only in CVS)

call_user_function -- ...

Descrizione

#include <zend_API.h>

int call_user_function ( HashTable* function_table, zval** object_pp, zval* function_name, zval* retval_ptr, zend_uint param_count, zval* params[] TSRMLS_DC )

...

Elenco dei parametri

function_table

...

object_pp

...

function_name

...

retval_ptr

...

param_count

...

params[] TSRMLS_DC

...

Valori restituiti

...

free_estring

(no version information, might be only in CVS)

free_estring -- ...

Descrizione

#include <zend.h>

void free_estring ( char** str_p )

...

Elenco dei parametri

str_p

...

Valori restituiti

...

get_zend_version

(no version information, might be only in CVS)

get_zend_version -- ...

Descrizione

#include <zend.h>

char* get_zend_version ( void )

...

Elenco dei parametri

void

...

Valori restituiti

...

ZEND_WRONG_PARAM_COUNT

(no version information, might be only in CVS)

ZEND_WRONG_PARAM_COUNT -- Generate standard error message for wrong parameter count in function or method call

Descrizione

#include <zend_API.h>

void ZEND_WRONG_PARAM_COUNT ( void )

ZEND_WRONG_PARAM_COUNT() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters. The macro automaticly puts the right function name and class name (if needed) into the error message.

ZEND_WRONG_PARAM_COUNT() is actually a convenience wrapper for zend_wrong_param_count().

object_and_properties_init

(no version information, might be only in CVS)

object_and_properties_init -- ...

Descrizione

#include <zend_API.h>

int object_and_properties_init ( zval* arg, zend_class_entry* ce, HashTable* properties )

...

Elenco dei parametri

arg

...

ce

...

properties

...

Valori restituiti

...

object_init_ex

(no version information, might be only in CVS)

object_init_ex -- ...

Descrizione

#include <zend_API.h>

int object_init_ex ( zval* arg, zend_class_entry* ce )

...

Elenco dei parametri

arg

...

ce

...

Valori restituiti

...

object_init

(no version information, might be only in CVS)

object_init -- ...

Descrizione

#include <zend_API.h>

int object_init ( zval* arg )

...

Elenco dei parametri

arg

...

Valori restituiti

...

zend_call_function

(no version information, might be only in CVS)

zend_call_function -- ...

Descrizione

#include <zend_API.h>

int zend_call_function ( zend_fcall_info* fci, zend_fcall_info_cache* fci_cache TSRMLS_DC )

...

Elenco dei parametri

fci

...

fci_cache TSRMLS_DC

...

Valori restituiti

...

zend_check_magic_method_implementation

(no version information, might be only in CVS)

zend_check_magic_method_implementation -- ...

Descrizione

#include <zend_API.h>

void zend_check_magic_method_implementation ( zend_class_entry* ce, zend_function* fptr, int error_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

fptr

...

error_type TSRMLS_DC

...

Valori restituiti

...

zend_class_implements

(no version information, might be only in CVS)

zend_class_implements -- ...

Descrizione

#include <zend_API.h>

void zend_class_implements ( zend_class_entry* class_entry TSRMLS_DC, int num_interfaces, ... )

...

Elenco dei parametri

class_entry TSRMLS_DC

...

num_interfaces

...

...

...

Valori restituiti

...

zend_copy_parameters_array

(no version information, might be only in CVS)

zend_copy_parameters_array -- ...

Descrizione

#include <zend_API.h>

int zend_copy_parameters_array ( int param_count, zval* argument_array TSRMLS_DC )

...

Elenco dei parametri

param_count

...

argument_array TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_bool

(no version information, might be only in CVS)

zend_declare_property_bool -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_bool ( zend_class_entry* ce, char* name, int name_length, long value, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

value

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_double

(no version information, might be only in CVS)

zend_declare_property_double -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_double ( zend_class_entry* ce, char* name, int name_length, double value, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

value

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_ex

(no version information, might be only in CVS)

zend_declare_property_ex -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_ex ( zend_class_entry* ce, char* name, int name_length, zval* property, int access_type, char* doc_comment, int doc_comment_len TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

property

...

access_type

...

doc_comment

...

doc_comment_len TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_long

(no version information, might be only in CVS)

zend_declare_property_long -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_long ( zend_class_entry* ce, char* name, int name_length, long value, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

value

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_null

(no version information, might be only in CVS)

zend_declare_property_null -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_null ( zend_class_entry* ce, char* name, int name_length, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_string

(no version information, might be only in CVS)

zend_declare_property_string -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_string ( zend_class_entry* ce, char* name, int name_length, char* value, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

value

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_declare_property_stringl

(no version information, might be only in CVS)

zend_declare_property_stringl -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property_stringl ( zend_class_entry* ce, char* name, int name_length, char* value, int value_len, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

value

...

value_len

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_declare_property

(no version information, might be only in CVS)

zend_declare_property -- ...

Descrizione

#include <zend_API.h>

int zend_declare_property ( zend_class_entry* ce, char* name, int name_length, zval* property, int access_type TSRMLS_DC )

...

Elenco dei parametri

ce

...

name

...

name_length

...

property

...

access_type TSRMLS_DC

...

Valori restituiti

...

zend_delete_global_variable

(no version information, might be only in CVS)

zend_delete_global_variable -- ...

Descrizione

#include <zend_API.h>

int zend_delete_global_variable ( char* name, int name_len TSRMLS_DC )

...

Elenco dei parametri

name

...

name_len TSRMLS_DC

...

Valori restituiti

...

zend_disable_class

(no version information, might be only in CVS)

zend_disable_class -- ...

Descrizione

#include <zend_API.h>

int zend_disable_class ( char* class_name, uint class_name_length TSRMLS_DC )

...

Elenco dei parametri

class_name

...

class_name_length TSRMLS_DC

...

Valori restituiti

...

zend_disable_function

(no version information, might be only in CVS)

zend_disable_function -- ...

Descrizione

#include <zend_API.h>

int zend_disable_function ( char* function_name, uint function_name_length TSRMLS_DC )

...

Elenco dei parametri

function_name

...

function_name_length TSRMLS_DC

...

Valori restituiti

...

zend_error

(no version information, might be only in CVS)

zend_error -- ...

Descrizione

#include <zend.h>

void zend_error ( int type, const char *format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3 )

...

Elenco dei parametri

type

...

char *format

...

ZEND_ATTRIBUTE_FORMAT(printf

...

2

...

3

...

Valori restituiti

...

zend_get_class_entry

(no version information, might be only in CVS)

zend_get_class_entry -- ...

Descrizione

#include <zend_API.h>

zend_class_entry* zend_get_class_entry ( zval* zobject TSRMLS_DC )

...

Elenco dei parametri

zobject TSRMLS_DC

...

Valori restituiti

...

zend_get_configuration_directive

(no version information, might be only in CVS)

zend_get_configuration_directive -- ...

Descrizione

#include <zend.h>

int zend_get_configuration_directive ( char* name, uint name_length, zval* contents )

...

Elenco dei parametri

name

...

name_length

...

contents

...

Valori restituiti

...

zend_get_hash_value

(no version information, might be only in CVS)

zend_get_hash_value -- ...

Descrizione

#include <zend_hash.h>

ulong zend_get_hash_value ( char* arKey, uint nKeyLength )

...

Elenco dei parametri

arKey

...

nKeyLength

...

Valori restituiti

...

zend_get_module_started

(no version information, might be only in CVS)

zend_get_module_started -- ...

Descrizione

#include <zend_API.h>

int zend_get_module_started ( char* module_name )

...

Elenco dei parametri

module_name

...

Valori restituiti

...

zend_get_module_version

(no version information, might be only in CVS)

zend_get_module_version -- ...

Descrizione

#include <zend_API.h>

char* zend_get_module_version ( char* module_name )

...

Elenco dei parametri

module_name

...

Valori restituiti

...

zend_get_object_classname

(no version information, might be only in CVS)

zend_get_object_classname -- ...

Descrizione

#include <zend_API.h>

int zend_get_object_classname ( zval* object, char** class_name, zend_uint* class_name_len TSRMLS_DC )

...

Elenco dei parametri

object

...

class_name

...

class_name_len TSRMLS_DC

...

Valori restituiti

...

zend_get_parameters_array_ex

(no version information, might be only in CVS)

zend_get_parameters_array_ex -- ...

Descrizione

#include <zend_API.h>

int zend_get_parameters_array_ex ( int param_count, zval*** argument_array )

...

Elenco dei parametri

param_count

...

argument_array

...

Valori restituiti

...

zend_get_parameters_array

(no version information, might be only in CVS)

zend_get_parameters_array -- ...

Descrizione

#include <zend_API.h>

int zend_get_parameters_array ( int ht, int param_count, zval** argument_array )

...

Elenco dei parametri

ht

...

param_count

...

argument_array

...

Valori restituiti

...

zend_get_parameters_ex

(no version information, might be only in CVS)

zend_get_parameters_ex -- ...

Descrizione

#include <zend_API.h>

int zend_get_parameters_ex ( int param_count, ... )

...

Elenco dei parametri

param_count

...

...

...

Valori restituiti

...

zend_get_parameters

(no version information, might be only in CVS)

zend_get_parameters -- ...

Descrizione

#include <zend_API.h>

int zend_get_parameters ( int ht, int param_count, ... )

...

Elenco dei parametri

ht

...

param_count

...

...

...

Valori restituiti

...

zend_get_std_object_handlers

(no version information, might be only in CVS)

zend_get_std_object_handlers -- ...

Descrizione

#include <zend_objects_API.h>

zend_object_handlers* zend_get_std_object_handlers ( )

...

Elenco dei parametri

...

Valori restituiti

...

zend_hash_add_empty_element

(no version information, might be only in CVS)

zend_hash_add_empty_element -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_add_empty_element ( HashTable* ht, char* arKey, uint nKeyLength )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

Valori restituiti

...

zend_hash_add

(no version information, might be only in CVS)

zend_hash_add -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_add ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Valori restituiti

...

zend_hash_apply_with_argument

(no version information, might be only in CVS)

zend_hash_apply_with_argument -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_apply_with_argument ( HashTable* ht, apply_func_arg_t apply_func, void* TSRMLS_DC )

...

Elenco dei parametri

ht

...

apply_func

...

TSRMLS_DC

...

Valori restituiti

...

zend_hash_apply_with_arguments

(no version information, might be only in CVS)

zend_hash_apply_with_arguments -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_apply_with_arguments ( HashTable* ht, apply_func_args_t apply_func, int, ... )

...

Elenco dei parametri

ht

...

apply_func

...

int

...

...

...

Valori restituiti

...

zend_hash_apply

(no version information, might be only in CVS)

zend_hash_apply -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_apply ( HashTable* ht, apply_func_t apply_func TSRMLS_DC )

...

Elenco dei parametri

ht

...

apply_func TSRMLS_DC

...

Valori restituiti

...

zend_hash_clean

(no version information, might be only in CVS)

zend_hash_clean -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_clean ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_compare

(no version information, might be only in CVS)

zend_hash_compare -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_compare ( HashTable* ht1, HashTable* ht2, compare_func_t compar, zend_bool ordered TSRMLS_DC )

...

Elenco dei parametri

ht1

...

ht2

...

compar

...

ordered TSRMLS_DC

...

Valori restituiti

...

zend_hash_copy

(no version information, might be only in CVS)

zend_hash_copy -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_copy ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, void* tmp, uint size )

...

Elenco dei parametri

target

...

source

...

pCopyConstructor

...

tmp

...

size

...

Valori restituiti

...

zend_hash_del_key_or_index

(no version information, might be only in CVS)

zend_hash_del_key_or_index -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_del_key_or_index ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, int flag )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

h

...

flag

...

Valori restituiti

...

zend_hash_destroy

(no version information, might be only in CVS)

zend_hash_destroy -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_destroy ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_exists

(no version information, might be only in CVS)

zend_hash_exists -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_exists ( HashTable* ht, char* arKey, uint nKeyLength )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

Valori restituiti

...

zend_hash_find

(no version information, might be only in CVS)

zend_hash_find -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_find ( HashTable* ht, char* arKey, uint nKeyLength, void** pData )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

pData

...

Valori restituiti

...

zend_hash_func

(no version information, might be only in CVS)

zend_hash_func -- ...

Descrizione

#include <zend_hash.h>

ulong zend_hash_func ( char* arKey, uint nKeyLength )

...

Elenco dei parametri

arKey

...

nKeyLength

...

Valori restituiti

...

zend_hash_get_current_data_ex

(no version information, might be only in CVS)

zend_hash_get_current_data_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_get_current_data_ex ( HashTable* ht, void** pData, HashPosition* pos )

...

Elenco dei parametri

ht

...

pData

...

pos

...

Valori restituiti

...

zend_hash_get_current_key_ex

(no version information, might be only in CVS)

zend_hash_get_current_key_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_get_current_key_ex ( HashTable* ht, char** str_index, uint* str_length, ulong* num_index, zend_bool duplicate, HashPosition* pos )

...

Elenco dei parametri

ht

...

str_index

...

str_length

...

num_index

...

duplicate

...

pos

...

Valori restituiti

...

zend_hash_get_current_key_type_ex

(no version information, might be only in CVS)

zend_hash_get_current_key_type_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_get_current_key_type_ex ( HashTable* ht, HashPosition* pos )

...

Elenco dei parametri

ht

...

pos

...

Valori restituiti

...

zend_hash_graceful_destroy

(no version information, might be only in CVS)

zend_hash_graceful_destroy -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_graceful_destroy ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_graceful_reverse_destroy

(no version information, might be only in CVS)

zend_hash_graceful_reverse_destroy -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_graceful_reverse_destroy ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_index_exists

(no version information, might be only in CVS)

zend_hash_index_exists -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_index_exists ( HashTable* ht, ulong h )

...

Elenco dei parametri

ht

...

h

...

Valori restituiti

...

zend_hash_index_find

(no version information, might be only in CVS)

zend_hash_index_find -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_index_find ( HashTable* ht, ulong h, void** pData )

...

Elenco dei parametri

ht

...

h

...

pData

...

Valori restituiti

...

zend_hash_init_ex

(no version information, might be only in CVS)

zend_hash_init_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_init_ex ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool bApplyProtection )

...

Elenco dei parametri

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

bApplyProtection

...

Valori restituiti

...

zend_hash_init

(no version information, might be only in CVS)

zend_hash_init -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_init ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent )

...

Elenco dei parametri

ht

...

nSize

...

pHashFunction

...

pDestructor

...

persistent

...

Valori restituiti

...

zend_hash_internal_pointer_end_ex

(no version information, might be only in CVS)

zend_hash_internal_pointer_end_ex -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_internal_pointer_end_ex ( HashTable* ht, HashPosition* pos )

...

Elenco dei parametri

ht

...

pos

...

Valori restituiti

...

zend_hash_internal_pointer_reset_ex

(no version information, might be only in CVS)

zend_hash_internal_pointer_reset_ex -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_internal_pointer_reset_ex ( HashTable* ht, HashPosition* pos )

...

Elenco dei parametri

ht

...

pos

...

Valori restituiti

...

zend_hash_merge_ex

(no version information, might be only in CVS)

zend_hash_merge_ex -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_merge_ex ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, uint size, merge_checker_func_t pMergeSource, void* pParam )

...

Elenco dei parametri

target

...

source

...

pCopyConstructor

...

size

...

pMergeSource

...

pParam

...

Valori restituiti

...

zend_hash_minmax

(no version information, might be only in CVS)

zend_hash_minmax -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_minmax ( HashTable* ht, compare_func_t compar, int flag, void** pData TSRMLS_DC )

...

Elenco dei parametri

ht

...

compar

...

flag

...

pData TSRMLS_DC

...

Valori restituiti

...

zend_hash_move_backwards_ex

(no version information, might be only in CVS)

zend_hash_move_backwards_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_move_backwards_ex ( HashTable* ht, HashPosition* pos )

...

Elenco dei parametri

ht

...

pos

...

Valori restituiti

...

zend_hash_move_forward_ex

(no version information, might be only in CVS)

zend_hash_move_forward_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_move_forward_ex ( HashTable* ht, HashPosition* pos )

...

Elenco dei parametri

ht

...

pos

...

Valori restituiti

...

zend_hash_next_free_element

(no version information, might be only in CVS)

zend_hash_next_free_element -- ...

Descrizione

#include <zend_hash.h>

ulong zend_hash_next_free_element ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_num_elements

(no version information, might be only in CVS)

zend_hash_num_elements -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_num_elements ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_quick_add

(no version information, might be only in CVS)

zend_hash_quick_add -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_quick_add ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

Valori restituiti

...

zend_hash_quick_exists

(no version information, might be only in CVS)

zend_hash_quick_exists -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_quick_exists ( HashTable* ht, char* arKey, uint nKeyLength, ulong h )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

h

...

Valori restituiti

...

zend_hash_quick_find

(no version information, might be only in CVS)

zend_hash_quick_find -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_quick_find ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void** pData )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

Valori restituiti

...

zend_hash_quick_update

(no version information, might be only in CVS)

zend_hash_quick_update -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_quick_update ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

h

...

pData

...

nDataSize

...

pDest

...

Valori restituiti

...

zend_hash_rehash

(no version information, might be only in CVS)

zend_hash_rehash -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_rehash ( HashTable* ht )

...

Elenco dei parametri

ht

...

Valori restituiti

...

zend_hash_reverse_apply

(no version information, might be only in CVS)

zend_hash_reverse_apply -- ...

Descrizione

#include <zend_hash.h>

void zend_hash_reverse_apply ( HashTable* ht, apply_func_t apply_func TSRMLS_DC )

...

Elenco dei parametri

ht

...

apply_func TSRMLS_DC

...

Valori restituiti

...

zend_hash_sort

(no version information, might be only in CVS)

zend_hash_sort -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_sort ( HashTable* ht, sort_func_t sort_func, compare_func_t compare_func, int renumber TSRMLS_DC )

...

Elenco dei parametri

ht

...

sort_func

...

compare_func

...

renumber TSRMLS_DC

...

Valori restituiti

...

zend_hash_update_current_key_ex

(no version information, might be only in CVS)

zend_hash_update_current_key_ex -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_update_current_key_ex ( HashTable* ht, int key_type, char* str_index, uint str_length, ulong num_index, HashPosition* pos )

...

Elenco dei parametri

ht

...

key_type

...

str_index

...

str_length

...

num_index

...

pos

...

Valori restituiti

...

zend_hash_update

(no version information, might be only in CVS)

zend_hash_update -- ...

Descrizione

#include <zend_hash.h>

int zend_hash_update ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )

...

Elenco dei parametri

ht

...

arKey

...

nKeyLength

...

pData

...

nDataSize

...

pDest

...

Valori restituiti

...

zend_is_callable_ex

(no version information, might be only in CVS)

zend_is_callable_ex -- ...

Descrizione

#include <zend_API.h>

zend_bool zend_is_callable_ex ( zval* callable, uint check_flags, char** callable_name, int* callable_name_len, zend_function** fptr_ptr, zval*** zobj_ptr_ptr TSRMLS_DC )

...

Elenco dei parametri

callable

...

check_flags

...

callable_name

...

callable_name_len

...

fptr_ptr

...

zobj_ptr_ptr TSRMLS_DC

...

Valori restituiti

...

zend_is_callable

(no version information, might be only in CVS)

zend_is_callable -- ...

Descrizione

#include <zend_API.h>

zend_bool zend_is_callable ( zval* callable, uint check_flags, char** callable_name )

...

Elenco dei parametri

callable

...

check_flags

...

callable_name

...

Valori restituiti

...

zend_make_callable

(no version information, might be only in CVS)

zend_make_callable -- ...

Descrizione

#include <zend_API.h>

zend_bool zend_make_callable ( zval* callable, char** callable_name TSRMLS_DC )

...

Elenco dei parametri

callable

...

callable_name TSRMLS_DC

...

Valori restituiti

...

zend_make_printable_zval

(no version information, might be only in CVS)

zend_make_printable_zval -- ...

Descrizione

#include <zend.h>

void zend_make_printable_zval ( zval* expr, zval* expr_copy, int* use_copy )

...

Elenco dei parametri

expr

...

expr_copy

...

use_copy

...

Valori restituiti

...

zend_merge_properties

(no version information, might be only in CVS)

zend_merge_properties -- ...

Descrizione

#include <zend_API.h>

void zend_merge_properties ( zval* obj, HashTable* properties, int destroy_ht TSRMLS_DC )

...

Elenco dei parametri

obj

...

properties

...

destroy_ht TSRMLS_DC

...

Valori restituiti

...

zend_message_dispatcher

(no version information, might be only in CVS)

zend_message_dispatcher -- ...

Descrizione

#include <zend.h>

void zend_message_dispatcher ( long message, void* data )

...

Elenco dei parametri

message

...

data

...

Valori restituiti

...

zend_object_create_proxy

(no version information, might be only in CVS)

zend_object_create_proxy -- ...

Descrizione

#include <zend_objects_API.h>

zval* zend_object_create_proxy ( zval* object, zval* member TSRMLS_DC )

...

Elenco dei parametri

object

...

member TSRMLS_DC

...

Valori restituiti

...

zend_object_store_ctor_failed

(no version information, might be only in CVS)

zend_object_store_ctor_failed -- ...

Descrizione

#include <zend_objects_API.h>

void zend_object_store_ctor_failed ( zval* zobject TSRMLS_DC )

...

Elenco dei parametri

zobject TSRMLS_DC

...

Valori restituiti

...

zend_object_store_get_object

(no version information, might be only in CVS)

zend_object_store_get_object -- ...

Descrizione

#include <zend_objects_API.h>

void* zend_object_store_get_object ( zval* object TSRMLS_DC )

...

Elenco dei parametri

object TSRMLS_DC

...

Valori restituiti

...

zend_object_store_set_object

(no version information, might be only in CVS)

zend_object_store_set_object -- ...

Descrizione

#include <zend_objects_API.h>

void zend_object_store_set_object ( zval* zobject, void* object TSRMLS_DC )

...

Elenco dei parametri

zobject

...

object TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_add_ref

(no version information, might be only in CVS)

zend_objects_store_add_ref -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_add_ref ( zval* object TSRMLS_DC )

...

Elenco dei parametri

object TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_call_destructors

(no version information, might be only in CVS)

zend_objects_store_call_destructors -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_call_destructors ( zend_objects_store* objects TSRMLS_DC )

...

Elenco dei parametri

objects TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_clone_obj

(no version information, might be only in CVS)

zend_objects_store_clone_obj -- ...

Descrizione

#include <zend_objects_API.h>

zend_object_value zend_objects_store_clone_obj ( zval* object TSRMLS_DC )

...

Elenco dei parametri

object TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_del_ref

(no version information, might be only in CVS)

zend_objects_store_del_ref -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_del_ref ( zval* object TSRMLS_DC )

...

Elenco dei parametri

object TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_destroy

(no version information, might be only in CVS)

zend_objects_store_destroy -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_destroy ( zend_objects_store* objects )

...

Elenco dei parametri

objects

...

Valori restituiti

...

zend_objects_store_free_object_storage

(no version information, might be only in CVS)

zend_objects_store_free_object_storage -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_free_object_storage ( zend_objects_store* objects TSRMLS_DC )

...

Elenco dei parametri

objects TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_init

(no version information, might be only in CVS)

zend_objects_store_init -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_init ( zend_objects_store* objects, zend_uint init_size )

...

Elenco dei parametri

objects

...

init_size

...

Valori restituiti

...

zend_objects_store_mark_destructed

(no version information, might be only in CVS)

zend_objects_store_mark_destructed -- ...

Descrizione

#include <zend_objects_API.h>

void zend_objects_store_mark_destructed ( zend_objects_store* objects TSRMLS_DC )

...

Elenco dei parametri

objects TSRMLS_DC

...

Valori restituiti

...

zend_objects_store_put

(no version information, might be only in CVS)

zend_objects_store_put -- ...

Descrizione

#include <zend_objects_API.h>

zend_object_handle zend_objects_store_put ( void* object, zend_objects_store_dtor_t dtor, zend_objects_free_object_storage_t storage, zend_objects_store_clone_t clone TSRMLS_DC )

...

Elenco dei parametri

object

...

dtor

...

storage

...

clone TSRMLS_DC

...

Valori restituiti

...

zend_output_debug_string

(no version information, might be only in CVS)

zend_output_debug_string -- ...

Descrizione

#include <zend.h>

void zend_output_debug_string ( zend_bool trigger_break, char* format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3 )

...

Elenco dei parametri

trigger_break

...

format

...

ZEND_ATTRIBUTE_FORMAT(printf

...

2

...

3

...

Valori restituiti

...

zend_parse_method_parameters_ex

(no version information, might be only in CVS)

zend_parse_method_parameters_ex -- ...

Descrizione

#include <zend_API.h>

int zend_parse_method_parameters_ex ( int flags, int num_args TSRMLS_DC, zval* this_ptr, char* type_spec, ... )

...

Elenco dei parametri

flags

...

num_args TSRMLS_DC

...

this_ptr

...

type_spec

...

...

...

Valori restituiti

...

zend_parse_method_parameters

(no version information, might be only in CVS)

zend_parse_method_parameters -- ...

Descrizione

#include <zend_API.h>

int zend_parse_method_parameters ( int num_args TSRMLS_DC, zval* this_ptr, char* type_spec, ... )

...

Elenco dei parametri

num_args TSRMLS_DC

...

this_ptr

...

type_spec

...

...

...

Valori restituiti

...

zend_parse_parameters_ex

(no version information, might be only in CVS)

zend_parse_parameters_ex -- ...

Descrizione

#include <zend_API.h>

int zend_parse_parameters_ex ( int num_args TSRMLS_DC, char* type_spec, ... )

...

Elenco dei parametri

num_args TSRMLS_DC

...

type_spec

...

...

...

Valori restituiti

...

zend_parse_parameters

(no version information, might be only in CVS)

zend_parse_parameters -- ...

Descrizione

#include <zend_API.h>

int zend_parse_parameters ( int num_args TSRMLS_DC, char* type_spec, ... )

...

Elenco dei parametri

num_args TSRMLS_DC

...

type_spec

...

...

...

Valori restituiti

...

zend_print_flat_zval_r

(no version information, might be only in CVS)

zend_print_flat_zval_r -- ...

Descrizione

#include <zend.h>

void zend_print_flat_zval_r ( zval* expr TSRMLS_DC )

...

Elenco dei parametri

expr TSRMLS_DC

...

Valori restituiti

...

zend_print_zval_ex

(no version information, might be only in CVS)

zend_print_zval_ex -- ...

Descrizione

#include <zend.h>

int zend_print_zval_ex ( zend_write_func_t write_func, zval* expr, int indent )

...

Elenco dei parametri

write_func

...

expr

...

indent

...

Valori restituiti

...

zend_print_zval_r_ex

(no version information, might be only in CVS)

zend_print_zval_r_ex -- ...

Descrizione

#include <zend.h>

void zend_print_zval_r_ex ( zend_write_func_t write_func, zval* expr, int indent TSRMLS_DC )

...

Elenco dei parametri

write_func

...

expr

...

indent TSRMLS_DC

...

Valori restituiti

...

zend_print_zval_r

(no version information, might be only in CVS)

zend_print_zval_r -- ...

Descrizione

#include <zend.h>

void zend_print_zval_r ( zval* expr, int indent TSRMLS_DC )

...

Elenco dei parametri

expr

...

indent TSRMLS_DC

...

Valori restituiti

...

zend_print_zval

(no version information, might be only in CVS)

zend_print_zval -- ...

Descrizione

#include <zend.h>

int zend_print_zval ( zval* expr, int indent )

...

Elenco dei parametri

expr

...

indent

...

Valori restituiti

...

zend_read_property

(no version information, might be only in CVS)

zend_read_property -- ...

Descrizione

#include <zend_API.h>

zval* zend_read_property ( zend_class_entry* scope, zval* object, char* name, int name_length, zend_bool silent TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

silent TSRMLS_DC

...

Valori restituiti

...

zend_register_functions

(no version information, might be only in CVS)

zend_register_functions -- ...

Descrizione

#include <zend_API.h>

int zend_register_functions ( zend_class_entry* scope, zend_function_entry* functions, HashTable* function_table, int type TSRMLS_DC )

...

Elenco dei parametri

scope

...

functions

...

function_table

...

type TSRMLS_DC

...

Valori restituiti

...

zend_register_internal_class_ex

(no version information, might be only in CVS)

zend_register_internal_class_ex -- ...

Descrizione

#include <zend_API.h>

zend_class_entry* zend_register_internal_class_ex ( zend_class_entry* class_entry, zend_class_entry* parent_ce, char* parent_name TSRMLS_DC )

...

Elenco dei parametri

class_entry

...

parent_ce

...

parent_name TSRMLS_DC

...

Valori restituiti

...

zend_register_internal_class

(no version information, might be only in CVS)

zend_register_internal_class -- ...

Descrizione

#include <zend_API.h>

zend_class_entry* zend_register_internal_class ( zend_class_entry* class_entry TSRMLS_DC )

...

Elenco dei parametri

class_entry TSRMLS_DC

...

Valori restituiti

...

zend_register_internal_interface

(no version information, might be only in CVS)

zend_register_internal_interface -- ...

Descrizione

#include <zend_API.h>

zend_class_entry* zend_register_internal_interface ( zend_class_entry* orig_class_entry TSRMLS_DC )

...

Elenco dei parametri

orig_class_entry TSRMLS_DC

...

Valori restituiti

...

zend_register_internal_module

(no version information, might be only in CVS)

zend_register_internal_module -- ...

Descrizione

#include <zend_API.h>

zend_module_entry* zend_register_internal_module ( zend_module_entry* module_entry TSRMLS_DC )

...

Elenco dei parametri

module_entry TSRMLS_DC

...

Valori restituiti

...

zend_register_module_ex

(no version information, might be only in CVS)

zend_register_module_ex -- ...

Descrizione

#include <zend_API.h>

zend_module_entry* zend_register_module_ex ( zend_module_entry* module TSRMLS_DC )

...

Elenco dei parametri

module TSRMLS_DC

...

Valori restituiti

...

zend_register_module

(no version information, might be only in CVS)

zend_register_module -- ...

Descrizione

int zend_register_module ( zend_module_entry *module_entry )

...

Elenco dei parametri

...

Valori restituiti

...

zend_reset_all_cv

(no version information, might be only in CVS)

zend_reset_all_cv -- ...

Descrizione

#include <zend_API.h>

void zend_reset_all_cv ( HashTable* symbol_table TSRMLS_DC )

...

Elenco dei parametri

symbol_table TSRMLS_DC

...

Valori restituiti

...

zend_startup_module_ex

(no version information, might be only in CVS)

zend_startup_module_ex -- ...

Descrizione

#include <zend_API.h>

int zend_startup_module_ex ( zend_module_entry* module TSRMLS_DC )

...

Elenco dei parametri

module TSRMLS_DC

...

Valori restituiti

...

zend_startup_module

(no version information, might be only in CVS)

zend_startup_module -- ...

Descrizione

#include <zend_API.h>

int zend_startup_module ( zend_module_entry* module_entry )

...

Elenco dei parametri

module_entry

...

Valori restituiti

...

zend_startup_modules

(no version information, might be only in CVS)

zend_startup_modules -- ...

Descrizione

#include <zend_API.h>

int zend_startup_modules ( TSRMLS_D )

...

Elenco dei parametri

TSRMLS_D

...

Valori restituiti

...

zend_unregister_functions

(no version information, might be only in CVS)

zend_unregister_functions -- ...

Descrizione

#include <zend_API.h>

void zend_unregister_functions ( zend_function_entry* functions, int count, HashTable* function_table TSRMLS_DC )

...

Elenco dei parametri

functions

...

count

...

function_table TSRMLS_DC

...

Valori restituiti

...

zend_update_class_constants

(no version information, might be only in CVS)

zend_update_class_constants -- ...

Descrizione

#include <zend_API.h>

void zend_update_class_constants ( zend_class_entry* class_type TSRMLS_DC )

...

Elenco dei parametri

class_type TSRMLS_DC

...

Valori restituiti

...

zend_update_property_bool

(no version information, might be only in CVS)

zend_update_property_bool -- ...

Descrizione

#include <zend_API.h>

void zend_update_property_bool ( zend_class_entry* scope, zval* object, char* name, int name_length, long value TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

value TSRMLS_DC

...

Valori restituiti

...

zend_update_property_double

(no version information, might be only in CVS)

zend_update_property_double -- ...

Descrizione

#include <zend_API.h>

void zend_update_property_double ( zend_class_entry* scope, zval* object, char* name, int name_length, double value TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

value TSRMLS_DC

...

Valori restituiti

...

zend_update_property_long

(no version information, might be only in CVS)

zend_update_property_long -- ...

Descrizione

#include <zend_API.h>

void zend_update_property_long ( zend_class_entry* scope, zval* object, char* name, int name_length, long value TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

value TSRMLS_DC

...

Valori restituiti

...

zend_update_property_null

(no version information, might be only in CVS)

zend_update_property_null -- ...

Descrizione

#include <zend_API.h>

void zend_update_property_null ( zend_class_entry* scope, zval* object, char* name, int name_length TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length TSRMLS_DC

...

Valori restituiti

...

zend_update_property_string

(no version information, might be only in CVS)

zend_update_property_string -- ...

Descrizione

#include <zend_API.h>

void zend_update_property_string ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

value TSRMLS_DC

...

Valori restituiti

...

zend_update_property_stringl

(no version information, might be only in CVS)

zend_update_property_stringl -- ...

Descrizione

#include <zend_API.h>

void zend_update_property_stringl ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, int value_length TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

value

...

value_length TSRMLS_DC

...

Valori restituiti

...

zend_update_property

(no version information, might be only in CVS)

zend_update_property -- ...

Descrizione

#include <zend_API.h>

void zend_update_property ( zend_class_entry* scope, zval* object, char* name, int name_length, zval* value TSRMLS_DC )

...

Elenco dei parametri

scope

...

object

...

name

...

name_length

...

value TSRMLS_DC

...

Valori restituiti

...

zend_wrong_param_count

(no version information, might be only in CVS)

zend_wrong_param_count -- Generate standard error message for wrong parameter count in function or method call

Descrizione

#include <zend_API.h>

void zend_wrong_param_count ( TSRMLS_D )

zend_wrong_param_count() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters. The function automaticly puts the right function name and class name (if needed) into the error message.

Usually the ZEND_WRONG_PARAM_COUNT() and ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() macros are used to invoke this function instead of calling it immediately as this saves typing the TSRMLS_C argument.

Elenco dei parametri

TSRMLS_D

Thread context

zend_zval_type_name

(no version information, might be only in CVS)

zend_zval_type_name -- Returns the PHP type name for a given zval

Descrizione

#include <zend_API.h>

char* zend_zval_type_name ( zval* arg )

zend_zval_type_name() returns the PHP typename for the current value of the zval pointed to by arg.

Elenco dei parametri

arg

A pointer to the zval to be examined.

Valori restituiti

A pointer to a static PHP typename string.


Capitolo 47. Extending PHP 3

This section is rather outdated and demonstrates how to extend PHP 3. If you're interested in PHP 4, please read the section on the Zend API.


Adding functions to PHP

Function Prototype

All functions look like this:
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) {
     
}
Even if your function doesn't take any arguments, this is how it is called.


Function Arguments

Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:

Esempio 47-1. Fetching function arguments

pval *arg1, *arg2;
if (ARG_COUNT(ht) != 2 || getParameters(ht,2,&arg1,&arg2)==FAILURE) {
   WRONG_PARAM_COUNT;
}
NOTE: Arguments can be passed either by value or by reference. In both cases you will need to pass &(pval *) to getParameters. If you want to check if the n'th parameter was sent to you by reference or not, you can use the function, ParameterPassedByReference(ht,n). It will return either 1 or 0.

When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.

Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.


Variable Function Arguments

A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:

Esempio 47-2. Variable function arguments

pval *arg1, *arg2, *arg3;
int arg_count = ARG_COUNT(ht);

if (arg_count < 2 || arg_count > 3 ||
    getParameters(ht,arg_count,&arg1,&arg2,&arg3)==FAILURE) {
    WRONG_PARAM_COUNT;
}


Using the Function Arguments

The type of each argument is stored in the pval type field. This type can be any of the following:

Tabella 47-1. PHP Internal Types

IS_STRINGString
IS_DOUBLEDouble-precision floating point
IS_LONGLong integer
IS_ARRAYArray
IS_EMPTYNone
IS_USER_FUNCTION??
IS_INTERNAL_FUNCTION?? (if some of these cannot be passed to a function - delete)
IS_CLASS??
IS_OBJECT??

If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1);
convert_to_double(arg1);
convert_to_string(arg1); 
convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */
convert_string_to_number(arg1);  /* Converts string to either LONG or DOUBLE depending on string */

These function all do in-place conversion. They do not return anything.

The actual argument is stored in a union; the members are:

  • IS_STRING: arg1->value.str.val

  • IS_LONG: arg1->value.lval

  • IS_DOUBLE: arg1->value.dval


Memory Management in Functions

Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().

There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).

For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.

If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.


Setting Variables in the Symbol Table

A number of macros are available which make it easier to set a variable in the symbol table:

  • SET_VAR_STRING(name,value)

  • SET_VAR_DOUBLE(name,value)

  • SET_VAR_LONG(name,value)

Avvertimento

Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING.

Symbol tables in PHP are implemented as hash tables. At any given time, &symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).

The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.

Esempio 47-3. Checking whether $foo exists in a symbol table

if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... }
else { doesn't exist }

Esempio 47-4. Finding a variable's size in a symbol table

hash_find(active_symbol_table,"foo",sizeof("foo"),&pvalue);
check(pvalue.type);
Arrays in PHP are implemented using the same hashtables as symbol tables. This means the two above functions can also be used to check variables inside arrays.

If you want to define a new array in a symbol table, you should do the following.

First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().

Next, initialize the array:

Esempio 47-5. Initializing a new array

pval arr;
  
if (array_init(&arr) == FAILURE) { failed... };
hash_update(active_symbol_table,"foo",sizeof("foo"),&arr,sizeof(pval),NULL);
This code declares a new array, named $foo, in the active symbol table. This array is empty.

Here's how to add new entries to it:

Esempio 47-6. Adding entries to a new array

pval entry;
  
entry.type = IS_LONG;
entry.value.lval = 5;
  
/* defines $foo["bar"] = 5 */
hash_update(arr.value.ht,"bar",sizeof("bar"),&entry,sizeof(pval),NULL); 

/* defines $foo[7] = 5 */
hash_index_update(arr.value.ht,7,&entry,sizeof(pval),NULL); 

/* defines the next free place in $foo[],
 * $foo[8], to be 5 (works like php2)
 */
hash_next_index_insert(arr.value.ht,&entry,sizeof(pval),NULL);
If you'd like to modify a value that you inserted to a hash, you must first retrieve it from the hash. To prevent that overhead, you can supply a pval ** to the hash add function, and it'll be updated with the pval * address of the inserted element inside the hash. If that value is NULL (like in all of the above examples) - that parameter is ignored.

hash_next_index_insert() uses more or less the same logic as $foo[] = bar; in PHP 2.0.

If you are building an array to return from a function, you can initialize the array just like above by doing:

if (array_init(return_value) == FAILURE) { failed...; }

...and then adding values with the helper functions:

add_next_index_long(return_value,long_value);
add_next_index_double(return_value,double_value);
add_next_index_string(return_value,estrdup(string_value));

Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr;
  
if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... }
else { use arr->value.ht... }

Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.

Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).


Returning simple values

A number of macros are available to make returning values from a function easier.

The RETURN_* macros all set the return value and return from the function:

  • RETURN

  • RETURN_FALSE

  • RETURN_TRUE

  • RETURN_LONG(l)

  • RETURN_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETURN_DOUBLE(d)

The RETVAL_* macros set the return value, but do not return.

  • RETVAL_FALSE

  • RETVAL_TRUE

  • RETVAL_LONG(l)

  • RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string

  • RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).

  • RETVAL_DOUBLE(d)

The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.

If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.


Returning complex values

Your function can also return a complex data type such as an object or an array.

Returning an object:

  1. Call object_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

  3. Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
    add_method( return_value, function_name, function_ptr );

The functions used to populate an object are:

  • add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'

  • add_property_double( return_value, property_name, d ) - Same, only adds a double

  • add_property_string( return_value, property_name, str ) - Same, only adds a string

  • add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'

Returning an array:

  1. Call array_init(return_value).

  2. Fill it up with values. The functions available for this purpose are listed below.

The functions used to populate an array are:

  • add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'

  • add_assoc_double(return_value,key,d)

  • add_assoc_string(return_value,key,str,duplicate)

  • add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length

  • add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'

  • add_index_double(return_value,index,d)

  • add_index_string(return_value,index,str)

  • add_index_stringl(return_value,index,str,length) - specify the string length

  • add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'

  • add_next_index_double(return_value,d)

  • add_next_index_string(return_value,str)

  • add_next_index_stringl(return_value,str,length) - specify the string length


Using the resource list

PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.

Available functions:

  • php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_list_delete(id) - delete the resource with the specified id

  • php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

Typically, these functions are used for SQL drivers but they can be used for anything else; for instance, maintaining file descriptors.

Typical list code would look like this:

Esempio 47-7. Adding a new resource

RESOURCE *resource;

/* ...allocate memory for resource and acquire resource... */
/* add a new resource to the list */
return_value->value.lval = php3_list_insert((void *) resource, LE_RESOURCE_TYPE);
return_value->type = IS_LONG;

Esempio 47-8. Using an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
resource = php3_list_find(resource_id->value.lval, &type);
if (type != LE_RESOURCE_TYPE) {
    php3_error(E_WARNING,"resource index %d has the wrong type",resource_id->value.lval);
    RETURN_FALSE;
}
/* ...use resource... */

Esempio 47-9. Deleting an existing resource

pval *resource_id;
RESOURCE *resource;
int type;

convert_to_long(resource_id);
php3_list_delete(resource_id->value.lval);
The resource types should be registered in php3_list.h, in enum list_entry_type. In addition, one should add shutdown code for any new resource type defined, in list.c's list_entry_destructor() (even if you don't have anything to do on shutdown, you must add an empty case).


Using the persistent resource table

PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:

php3_mysql_do_connect
php3_mysql_connect()
php3_mysql_pconnect()

The general idea of persistence modules is this:

  1. Code all of your module to work with the regular resource list mentioned in section (9).

  2. Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).

If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.

The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':

  • php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource

  • php3_plist_delete(id) - delete the resource with the specified id

  • php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type

However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.

Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.

One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.

When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.


Adding runtime configuration directives

Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.

The steps required to add a new directive:

  1. Add directive to php3_ini_structure struct in mod_php3.h.

  2. In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.

  3. Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.

  4. In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.

  5. In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.

  6. And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.


Calling User Functions

To call user functions from an internal function, you should use the call_user_function() function.

call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.

All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.

call_user_function() takes six arguments:


HashTable *function_table

This is the hash table in which the function is to be looked up.


pval *object

This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.


pval *function_name

The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.


pval *retval

A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.


int param_count

The number of parameters being passed to the function.


pval *params[]

An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.


Reporting Errors

To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:


E_NOTICE

Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.


E_WARNING

Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.


E_ERROR

Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.


E_PARSE

Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.


E_CORE_ERROR

This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.


E_CORE_WARNING

This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.


E_COMPILE_ERROR

This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.


E_COMPILE_WARNING

This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.


E_USER_ERROR

This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.


E_USER_WARNING

This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.


E_USER_NOTICE

This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.


E_ALL

All of the above. Using this error_reporting level will show all error types.


Capitolo 48. Informazioni Generali

Questa sezione contiene le domande più generali riguardanti il PHP: cos'è e cosa fa.

1. Cos'è il PHP?
2. Cosa significa PHP?
3. Qual'è la relazione fra le varie versioni?
4. Si possono avere in esecuzione contemporaneamente diverse versioni di PHP?
5. Quali sono le differenze fra PHP 3 e PHP 4?
6. Credo di avere trovato un bug! A chi lo devo dire?

1. Cos'è il PHP?

Dal manuale:

PHP è un linguaggio di script immerso nel HTML. Molta della sua sintassi è presa in prestito dai linguaggi C, Java e Perl, a cui sono state aggiunte alcune specifiche caratteristiche del PHP. L'obiettivo del linguaggio è di semplificare il lavoro dei webmaster nella realizzazione di pagine dinamiche.

Una buona introduzione al PHP, a cura di Stig Sæther Bakken, può essere trovata http://www.zend.com/zend/art/intro.php sul sito web di Zend. Inoltre, gran parte del materiale usato per le conferenze sul PHP è liberamente disponibile.

2. Cosa significa PHP?

PHP significa PHP: Hypertext Preprocessor. Questo confonde molte persone poiché la prima parola dell'acronimo è l'acronimo stesso. Questo tipo di acronimo è chiamato acronimo ricorsivo. Chi è curioso può visitare Free On-Line Dictionary of Computing per avere maggiori informazioni riguardanti gli acronimi ricorsivi.

3. Qual'è la relazione fra le varie versioni?

PHP/FI 2.0 è una vecchia versione di PHP non più supportata. PHP 3 è il successore di PHP/FI 2.0 ed è molto più gradevole. PHP 4 è l'ultima generazione di PHP, che al suo interno fa uso del motore Zend. Il PHP 5 utilizza il Zend engine 2 che, tra le altre cose offre maggiori funzionalità OOP.

4. Si possono avere in esecuzione contemporaneamente diverse versioni di PHP?

Sì. Fare riferimento al file INSTALL incluso nella distribuzione del codice sorgente di PHP 4. Fare inoltre riferimento alla relativa appendice.

5. Quali sono le differenze fra PHP 3 e PHP 4?

Sono disponibili un paio di articoli scritti dagli autori stessi di PHP 4. Questa è una lista di alcune delle più importanti nuove caratteristiche:

  • Modulo API esteso

  • Sotto UNIX, processo di compilazione generalizzato

  • Interfaccia generica verso i web server, anche verso quelli che supportano il multi-threading

  • Migliore evidenziatore di sintassi

  • Supporto nativo per le sessioni HTTP

  • Supporto per il buffering dell'output

  • Sistema di configurazione più potente

  • Reference counting

Per favore fare riferimento a panoramica delle novità in PHP 4 per un'esposizione dettagliata di queste nuove caratteristiche e altro ancora. Se si è in procinto di migrare dal PHP 3 al PHP 4 si consiglia di leggere la relativa appendice.

6. Credo di avere trovato un bug! A chi lo devo dire?

Dovresti andare a visitare il database dei Bug del PHP e assicurarti che il bug non sia già conosciuto. Se non lo vedi nel database, usa il modulo per inviare il bug. È importante usare il database dei bug invece di mandare una email ad una delle mailing list, perché in questo caso al bug viene assegnato un tracking number e sarà per te possibile tornare più tardi a verificare lo stato del bug. Il database dei bug può essere trovato qui http://bugs.php.net/.


Capitolo 49. Mailing list

Questa sezione contiene domande su come fare per entrare in contatto con la comunità PHP. Il modo migliore è tramite le mailing list.

1. Esistono mailing list dedicate al PHP?
2. Ci sono altre comunità?
3. Aiuto! Non risco a iscrivermi/cancellarmi a/da una delle mailing list!
4. Esiste un archivio delle mailing list?
5. Cosa si può chiedere nelle mailing list?
6. Quali informazioni si dovrebbero includere nel mandare un messaggio a una mailinglist?

1. Esistono mailing list dedicate al PHP?

Certo! Ci sono molte mailing list dedicate a svariati aspetti. Una lista completa di mailing list può essere trovata nella nostra pagina dedicata al Supporto.

La mailing list più generica è php-general. Per iscriversi, inviare una mail a php-general-subscribe@lists.php.net. Non è necessario scrivere nulla come oggetto o come corpo del messaggio. Per cancellarsi, inviare una mail a php-general-unsubscribe@lists.php.net.

Ci si può iscrivere e cancellare usando l'interfaccia web nella nostra pagina di Supporto .

2. Ci sono altre comunità?

Ve ne sono numerosissime in giro per il mondo. Abbiamo link di alcuni server IRC e di mailing list in lingua straniera nella nostra pagina di Support.

3. Aiuto! Non risco a iscrivermi/cancellarmi a/da una delle mailing list!

Se si riscontrano problemi nell'iscriversi o nel cancellarsi dalla mailing list php-general, può essere perché il software che gestisce la mailing list stessa non riesce a individuare l'indirizzo corretto da usare. Se l'indirizzo email è pippo@example.com, si può mandare una richiesta di iscrizione a php-general-subscribe-pippo=example.com@lists.php.net, o la richiesta di cancellazione a php-general-unsubscribe-pippo=example.com@lists.php.net. Utilizzare indirizzi corrispondenti per le altre mailing list.

4. Esiste un archivio delle mailing list?

Sì, una lista dei siti che ospitano gli archivi si trova nella pagina di Supporto. Gli articoli delle mailinglist vengono anche archiviati come messaggi news. Si può accedere al news server news://news.php.net/ usando un client per le news. Esiste anche un'interfaccia web sperimentale verso il news server http://news.php.net/

5. Cosa si può chiedere nelle mailing list?

Poiché PHP cresce di popolarità di giorno in giorno, il traffico sulla mailing list php-general è notevolmente aumentato, attualmente la lista riceve circa 150-200 messaggi al giorno. Considerato ciò, è nell'interesse di tutti usare la lista solo come ultima chance, cioè solo quando si è già cercato in tutti gli altri posti.

Prima di inviare un messaggio alla lista, bisognerebbe dare una lettura a queste FAQ e al manuale per vedere se si può trovare aiuto lì. Se non si trova nulla, si può provare con gli archivi della mailing list (vedere sopra). Se si riscontrano problemi nell'installare o nel configurare PHP, per favore fare riferimento alla documentazione inclusa nella distribuzione e ai vari README. Se anche allora non si riescono a trovare informazioni sufficienti, si è i benvenuti ad usare la mailing list.

Prima di porre domande, può essere una buona idea per tutti leggere Come fare domande, il metodo migliore .

6. Quali informazioni si dovrebbero includere nel mandare un messaggio a una mailinglist?

Messaggi tipo: "Non riesco a installare PHP! Aiuto! Cosa c'è di sbagliato?" non sono di aiuto a nessuno. Se si hanno problemi a installare PHP, si dovrebbero includere il sistema operativo nel quale lo si sta cercando di installare, quale versione di PHP si vuole installare, in quale forma lo si ha a disposizione (pre-compilato, dal CVS, RPM e così via), cosa si è tentato fino ad ora, dove ci si è bloccati e l'esatto messaggio di errore.

Questa regola è applicabile agli altri problemi che si possino incontrare. Si devono includere informazioni su cosa si è fatto, dove si è rimasti bloccati, cosa si sta cercando di fare e , se possibile, fornire gli esatti messaggi di errore. Se avete problemi con il vostro codice sorgente, dovreste includere la parte di codice che non è funzionante. Non includere più codice di quello che è strettamente necessario! Quello renderebbe il messaggio difficile da leggere e molte persone lo salterebbero proprio a causa di questo. Se siete poco sicuri su quante informazioni includere nel messaggio, meglio includerne di più che di meno.

Un'altra cosa importante da ricordare è quella di sintetizzare il vostro problema nell'oggetto del messaggio. Un oggetto del tipo "AIUTATEMIIIIIIIII!!!" oppure "Dove sta problema?" verrà ignorato dalla maggioranza dei lettori.

Infine si incoraggia la lettura di Come fare domande, il metodo migliore , può essere di aiuto per chiunque .


Capitolo 50. Ottenere PHP

Questa sezione contiene dettagli riguardanti le modalità di download di PHP e argomenti relativi ai Sistemi Operativi.

1. Dove posso ottenere PHP?
2. Sono disponibili versioni binarie pre-compilate?
3. Dove posso prendere le librerie necessarie a compilare alcune delle estensioni opzionali di PHP?
4. Come faccio a far funzionare queste librerie?
5. Ho sulla mia macchina Windows l'ultimissima versione del codice sorgente di PHP preso dal repository CVS, di cosa ho bisogno per compilarlo?
6. Dove trovo il Browser Capabilities File?

1. Dove posso ottenere PHP?

Si può scaricare PHP da uno qualunque dei membri del network di siti PHP. Questi possono essere trovati qui http://www.php.net/. Si può anche usare il CVS anonymous per ottenere l'ultimissima versione del sorgente. Per maggiori informazioni, andare qui http://www.php.net/anoncvs.php.

2. Sono disponibili versioni binarie pre-compilate?

Noi distribuiamo binari precompilati per i sistemi Windows, poiché non siamo in grado di compilare PHP per ognuna delle maggiori piattaforme Linux/Unix con ogni possibile combinazione di estensioni. Si noti che al giorno d'oggi molte distribuzioni Linux dispongono di PHP precompilato. I binari Windows possono essere scaricati dalla nostra pagina dei Download, per i binari per Linux, fare riferimento al sito web della vostra distribuzione.

3. Dove posso prendere le librerie necessarie a compilare alcune delle estensioni opzionali di PHP?

Nota: Quelle segnate con * sono librerie non thread-safe e non dovrebbero essere usate con PHP installato come modulo nei web server multi-threaded sotto Windows (IIS, Netscape). Questo non è per il momento applicabile all'ambiente Unix.

4. Come faccio a far funzionare queste librerie?

È necessario seguire le istruzioni presenti nella distribuzione della libreria. Alcune di queste librerie vengono trovate automaticamente quando si esegue lo script 'configure' di PHP (ad esempio nel caso della libreria GD), altre dovranno invece essere abilitate usando le opzioni '--with-ESTENSIONE' per 'configure'. Eseguire 'configure --help' per un elenco di esse.

5. Ho sulla mia macchina Windows l'ultimissima versione del codice sorgente di PHP preso dal repository CVS, di cosa ho bisogno per compilarlo?

Per prima cosa è necessario Microsoft Visual C++ v6 (v5 potrebbe funzionare, ma noi lo facciamo con v6), saranno anche necessari alcuni file di supporto. Fare riferimento alla sezione del manuale dedicata a compilare PHP sotto Windows a partire dal sorgente.

6. Dove trovo il Browser Capabilities File?

Un file browscap.ini può essere trovato qui http://www.garykeith.com/browsers/downloads.asp.


Capitolo 51. Database issues

This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.

1. I heard it's possible to access Microsoft SQL Server from PHP. How?
2. Can I access Microsoft Access databases?
3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?
4. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?
5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
6. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?

1. I heard it's possible to access Microsoft SQL Server from PHP. How?

On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.

On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.

2. Can I access Microsoft Access databases?

Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.

If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.

Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:

Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other Unix platforms. Please visit our website for a free download.

One option that has proved successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:

  • Install MySQL on your platform according to instructions with MySQL. Latest available from www.mysql.com (get it from your mirror!). No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.

  • Download the MyODBC for Windows driver from the MySQL site. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). Install it on your Windows machine. You can test the operation with the utilities included with this program.

  • Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.

  • Install Access with a full install, this makes sure you get the proper add-ins.. at the least you will need ODBC support and the linked table manager.

  • Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press OK, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.

Tips and Tricks:

  • You can construct your tables in Access and export them to MySQL, then link them back in. That makes table creation quick.

  • When creating tables in Access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access

  • If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing OK.

3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?

Most likely what has happened is, PHP 4 was compiled with the --with-mysql option, without specifying the path to MySQL. This means PHP is using its built-in MySQL client library. If your system is running applications, such as PHP 3 as a concurrent Apache module, or auth-mysql, that use other versions of MySQL clients, then there is a conflict between the two differing versions of those clients.

Recompiling PHP 4, and adding the path to MySQL to the flag, '--with-mysql=/your/path/to/mysql' usually solves the problem.

4. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?

Yes. There will always be MySQL support in PHP of one kind or another. The only change in PHP 5 is that we are no longer bundling the client library itself. Some reasons in no particular order:

  • Most systems these days already have the client library installed.

  • Given the above, having multiple versions of the library can get messy. For example, if you link mod_auth_mysql against one version and PHP against another, and then enable both in Apache, you get a nice fat crash. Also, the bundled library didn't always play well with the installed server version. The most obvious symptom of this being disagreement over where to find the mysql.socket Unix domain socket file.

  • Maintenance was somewhat lax and it was falling further and further behind the released version.

  • Future versions of the library are under the GPL and thus we don't have an upgrade path since we cannot bundle a GPL'ed library in a BSD/Apache-style licensed project. A clean break in PHP 5 seemed like the best option.

This won't actually affect that many people. Unix users, at least the ones who know what they are doing, tend to always build PHP against their system's libmyqlclient library simply by adding the --with-mysql=/usr option when building PHP. Windows users may enable the extension php_mysql.dll inside php.ini. For more details, see the MySQL Reference for installation instructions. Also, be sure libmysql.dll is available to the systems PATH. For more details on how, read the FAQ on setting up the Windows systems PATH. Because libmysql.dll (and many other PHP related files) exist in the PHP folder, you'll want to add the PHP folder to your systems PATH.

5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?

If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.

6. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?

You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:
<?php

$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
?>
or
<?php

$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: " . mysql_error());
?>


Capitolo 52. Installazione

In questa sezione sono presenti le domande più frequenti riguardo l'installazione di PHP. PHP è disponibile per quasi tutti i sitemi operativi, eccetto forse MacOS prima di OSX, e per quasi tutti i webserver.

Per installare PHP, segui le istruzioni del file INSTALL della tua distribuzione. Gli utenti Windows possono anche leggere il file install.txt o visitare questo sito per avere ulteriori suggerimenti.

1. Unix/Windows: dove devo copiare il mio file php.ini?
2. Unix: ho installato PHP, ma ogni volta che carico uno script ricevo un messaggio di errore che dice: 'Document Contains No Data' (Lo script non contiene dati). Che sta succedendo?
3. Unix: ho installato PHP usando dei pacchetti RPM, ma Apache non processa le mie pagine PHP. Che sta succedendo?
4. Unix: ho installato PHP 3 usando dei pacchetti RPM, ma il supporto per database del quale ho bisogno non viene compilato correttamente. Che sta succedendo?
5. Unix: ho installato la patch di Apache per avere compatibilità con le estensioni del server di FrontPage, e improvvisamente PHP ha smesso di funzionare: PHP è quindi incompatibile con le estensioni del server di FrontPage per Apache?
6. Unix/Windows: ho installato PHP, ma se provo ad accedere ai miei script via browser, ricevo una pagina vuota.
7. Unix/Windows: ho installato PHP, ma se provo ad accedere ai miei script via browser, ricevo un errore 500 dal server.
8. Diversi sistemi operativi: ho installato PHP senza ricevere errori, ma se provo a far partire Apache ricevo un errore con strani simboli:
[mybox:user /src/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress
9. Windows: ho installato PHP, ma se provo ad accedere ai miei script via browser, ricevo questo errore:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:
10. Windows: ho seguito tutte le istruzioni, ma proprio non riesco a far convivere PHP con IIS!

1. Unix/Windows: dove devo copiare il mio file php.ini?

Nei sistemi UNIX il percorso predefinito è /usr/local/lib. Molti utenti vorranno cambiare questo percorso durante la fase di compilazione con il flag --with-config-file-path. Per esempio potresti modificare il percorso in un modo simile a questo:
--with-config-file-path=/etc
e quindi dovresti copiare il file php.ini-dist della distribuzione in /etc/php.ini e modificarlo per ottenere tutti i cambiamenti voluti.

Nei sistemi Windows il percorso predefinito corrisponde alla cartella stessa di Windows.

2. Unix: ho installato PHP, ma ogni volta che carico uno script ricevo un messaggio di errore che dice: 'Document Contains No Data' (Lo script non contiene dati). Che sta succedendo?

Probabilmente PHP sta riscontrando un qualche tipo di problema e sta generando un core dump. Controlla il file log degli errori del tuo server ed individua il problema, quindi cerca di riprodurre il problema in un piccolo script. Se sai come usare 'gdb', sarebbe di aiuto fornire agli sviluppatori una copia dei messaggi di errore per consentire agli stessi di localizzare il problema. Se usi PHP come modulo di Apache prova ad eseguire le seguenti operazioni:

  • Ferma i tuoi processi httpd

  • gdb httpd

  • Ferma i tuoi processi httpd

  • > esegui -X -f /percorso/per/httpd.conf

  • Quindi trova l'URL che causa problemi usando il tuo browser

  • > esegui -X -f /percorso/per/httpd.conf

  • Se ottieni un, gdb ora dovrebbe informarti di ciò

  • digita: bt

  • Comunica il bug a http://bugs.php.net/ includendo un backtrace del problema.

Se nei tuoi script usi espressioni regolari (ereg() e simili), dovresti assicurarti di aver compilato PHP e Apache con lo stesso pacchetto di espressioni regolari. Ciò dovrebbe succedere automaticamente con PHP e Apache 1.3.x

3. Unix: ho installato PHP usando dei pacchetti RPM, ma Apache non processa le mie pagine PHP. Che sta succedendo?

Presumendo che tu abbia installato sia Apache che PHP da pacchetti RPM, hai bisogno di decommentare o aggiungere qualcuna o tutte le righe seguenti nel file http.conf:
# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php3_module        modules/libphp3.so     /* per PHP 3 */
LoadModule php4_module        modules/libphp4.so     /* per PHP 4 */
LoadModule perl_module        modules/libperl.so
And add:
AddType application/x-httpd-php3 .php3    /* per PHP 3 */
AddType application/x-httpd-php .php      /* per PHP 4 */
... alle proprietà globali o alle proprietà del VirtualDomain su cui vuoi aggiungere il supporto PHP.

4. Unix: ho installato PHP 3 usando dei pacchetti RPM, ma il supporto per database del quale ho bisogno non viene compilato correttamente. Che sta succedendo?

A causa della struttura stessa di PHP 3, non è facile ottenere dei pacchetti RPM completi e flessibili. Questo problema è stato corretto in PHP 4. Per installare PHP 3, consigliamo di usare la guida presente nel file INSTALL.REDHAT della distribuzione PHP: se proprio non puoi fare a meno di installare PHP 3 tramite pacchetti RPM, leggi prima questo file...

Per semplificare le fasi dell'installazione, i pacchetti RPM sono stati progettati per installare PHP senza il supporto per i database, e inoltre i pacchetti RPM usano la cartella /usr/ invece di /usr/local/ per copiare i file. Devi 'dire' ai pacchetti RPM in un file speciale quale supporto per databse installare e il percorso della cartella di livello superiore del tuo database.

Questo esempio servirà a chiarire come aggiungere il supporto per gli ormai diffusi databse MySQL usando l'installazione mod di Apache.

Ovviamente le righe seguenti possono essere modificate per qualsiasi tipo di database supportato da PHP. Presumendo che tu abbia installato sia Apache che MySQL solo con pacchetti RPM, quanto segue potrebbe esserti di aiuto:

  • Per prima cosa rimuovi mod_php3:
    rpm -e mod_php3

  • Quindi prendi i pacchetti RPM e installali di nuovo, non reinstallarli
    rpm -Uvh mod_php3-3.0.5-2.src.rpm

  • Adesso modifica il file /usr/src/redhat/SPECS/mod_php3.spec

    Nella sezione %build aggiungi il supporto che desideri e il percorso.

    Per MySQL dovresti aggiungere:
    --with-mysql=/usr \
    La sezione %build (installazione) dovrebbe ora essere simile a questa:
    ./configure --prefix=/usr \
    	--with-apxs=/usr/sbin/apxs \
    	--with-config-file-path=/usr/lib \
    	--enable-debug=no \
    	--enable-safe-mode \
    	--with-exec-dir=/usr/bin \
    	--with-mysql=/usr \
    	--with-system-regex

  • Dopo aver fatto queste modifiche assembla i binari RPM come segue:
    rpm -bb /usr/src/redhat/SPECS/mod_php3.spec

  • Quindi installa i pacchetti RPM
    rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm

Assicurati di riavviare Apache, quindi dovresti avere PHP 3 installato tramite pacchetti RPM con pieno supporto MySQL. Nota che probabilmente sarà più facile installare ciò seguendo le istruzioni presenti nel file INSTALL.REDHAT della distribuzione.

5. Unix: ho installato la patch di Apache per avere compatibilità con le estensioni del server di FrontPage, e improvvisamente PHP ha smesso di funzionare: PHP è quindi incompatibile con le estensioni del server di FrontPage per Apache?

No, PHP lavora senza problemi con le estensioni del server di FrontPage. Il problema è che la patch di FrontPage modifica diverse strutture di Apache dalle quali dipende PHP stesso. Per risolvere il problema ricompila PHP (usando 'make clean ; make') dopo aver installato la patch.

6. Unix/Windows: ho installato PHP, ma se provo ad accedere ai miei script via browser, ricevo una pagina vuota.

Controlla il sorgente della pagina che ricevi e probabilmente vedrai il codice sorgente del tuo script PHP. Ciò significa che il webserver non ha inviato lo script all'interprete PHP. C'è qualcosa che non va nella configurazione del webserver: confronta la configurazione del webserver con le istruzioni per installare PHP.

7. Unix/Windows: ho installato PHP, ma se provo ad accedere ai miei script via browser, ricevo un errore 500 dal server.

C'è qualcosa che non va al momento in cui il server prova a richiamare l'interprete PHP. Per ricevere un messaggio sensato di errore, dalla linea di comando, cambia la cartella che contiene l'eseguibile di PHP (php.exe sotto Windows) ed esegui php -i. Se PHP riscontrerà dei problemi durante l'esecuzione, comparirà un opportuno messaggio d'errore contente informazioni su cosa fare successivamente. Se riceverai una schermata di codice HTML (la stessa di phpinfo()) significherà che PHP sta lavorando correttamente, e quindi il problema potrebbe essere legato alla configurazione del server, che andrebbe quindi controllata.

8. Diversi sistemi operativi: ho installato PHP senza ricevere errori, ma se provo a far partire Apache ricevo un errore con strani simboli:
[mybox:user /src/php4] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

Ciò non ha nulla a che vedere con PHP, ma con le librerie lato client di MySQL. Alcune richiedono --with-zlib, altre no. Questo argomento è ripreso meglio nelle FAQ relative a MySQL.

9. Windows: ho installato PHP, ma se provo ad accedere ai miei script via browser, ricevo questo errore:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Questo errore vuol dire che PHP non è riuscito ad ottenere qualcuno di tutti gli output richiesti. Per ricevere un messaggio sensato di errore, dalla linea di comando, cambia la cartella che contiene l'eseguibile di PHP (php.exe sotto Windows) ed esegui php -i. Se PHP riscontrerà dei problemi durante l'esecuzione, comparirà un opportuno messaggio d'errore contente informazioni su cosa fare successivamente. Se riceverai una schermata di codice HTML (la stessa di phpinfo()) significherà che PHP sta lavorando correttamente, e quindi il problema potrebbe essere legato alla configurazione del server, che andrebbe quindi controllata.

Dopo che PHP sta lavorando dalla linea di comando, prova ad accedere di nuovo ai tuoi script via browser. Se ancora ricevi messaggi di errore, il problema potrebbe essere dovuto ad una delle seguenti cose:

  • I permessi dei file php.exe, php4ts.dll, php.ini o di qualche altra estensione PHP che stai cercando di caricare potrebbero essere settati in modo da impedire l'accesso agli utenti anonimi di internet ISUR_<machinename>.

  • Il file dello script non esiste (o forse non è dove pensi in relazione alla tua root directory). Nota che con IIS puoi aggirare quest'ostacolo selezionando la voce relativa a 'check file exists' (controlla se il file esiste) nelle opzioni di Internet Services Manager. Se il file di uno script non esiste il server invierà un errore 404. C'è un ulteriore beneficio: IIS si preoccuperà di effettuare tutte le autenticazioni necessarie al posto tuo, in base ai permessi NTLanMan del tuo file contenente lo script.

10. Windows: ho seguito tutte le istruzioni, ma proprio non riesco a far convivere PHP con IIS!

Assicurati che l'utente con il quale stai cercando di eseguire script PHP abbia i permessi necessari per eseguire php.exe! IIS usa un utente anonimo che viene aggiunto al momento dell'installazione del webserver. Questo utente ha bisogno dei permessi appropriati per eseguire php.exe. Qualunque utente avrà bisogno dei permessi appropriati per eseguire php.exe. Se usi IIS4, hai bisogno di dire al webserver che c'è un parser PHP.


Capitolo 53. Problemi di installazione

Questa sezione raccoglie i più comuni errori che avvengono durante l'installazione.

1. Ho l'ultima versione di PHP e uso l'anonymous CVS, ma non c'è nessuno script per la configurazione!
2. Ho problemi nel configurare PHP per farlo lavorare con Apache. Dice che è impossibile trovare il file httpd.h, ma questo è nel percorso che ho specificato!
3. Durante la configurazione di PHP (./configure), si può incontrare un errore simile al seguente:
4. Quando avvio Apache ottengo il seguente messaggio:
5. Quando eseguo la configurazione, un messaggio di errore mi dice che non è possibile trovare file inclusi o librerie per GD, gdbm o qualche altro pacchetto!
6. Quando cerco di compilare il file language-parser.tab.c, un messaggio di errore mi dice yytname undeclared.
7. Quando eseguo make sembra che vada tutto bene, ma lo script si blocca quando cerca di creare un collegamento all'applicazione finale, un messaggio di errore dice che non è possibile trovare alcuni file.
8. Quando linko PHP, un messaggio di errore mi avvisa di parecchie undefined reference.
9. Non riesco a capire come installare PHP con Apache 1.3.
10. Ho seguito le istruzioni per installare Apache come modulo sotto UNIX, ma il browser mi mostra il codice dei miei script PHP o mi viene chiesto di salvare la pagina PHP sul disco.
11. Un messaggio di errore mi dice di usare: --activate-module=src/modules/php4/libphp4.a, ma questo file non esiste, quindi l'ho cambiato in --activate-module=src/modules/php4/libmodphp4.a ma il tutto non funziona. Che succede?
12. Quando provo ad installare Apache con PHP come modulo statico usando --activate-module=src/modules/php4/libphp4.a un messaggio di errore mi dice che il mio compilatore non è compatibile con ANSI.
13. Quando provo ad installare Apache usando --with-apxs ricevo uno strano messaggio di errore.
14. Quando eseguo make, ricevo errori nei microtime e un sacco di errori RUSAGE_.
15. Quando si compila il PHP con MySQL, la configurazione viene eseguita correttamente, ma durante il make si ottiene un errore simile al seguente: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', che cosa c'è di sbagliato?
16. Voglio aggiornare il mio PHP. Dove posso trovare la linea di ./configure che è stata usata per creare la mia attuale versione di PHP?
17. Quando si compila il PHP con la libreria GD, si ottiene dei strani errori di compila oppure dei segfault durante l'esecuzione.
18. Quando si compila il PHP sembra di avere errori casuali, tipo blocchi. Se interessa sto utilizzando Solaris.

1. Ho l'ultima versione di PHP e uso l'anonymous CVS, ma non c'è nessuno script per la configurazione!

Per generare lo script di configurazione dal file configure.in devi avere il pacchetto autoconf di GNU installato sul tuo PC. Esegui ./buildconf nella cartella di livello più alto dopo aver ottenuto i sorgenti dal server CVS. (A meno che tu non esegua la configurazione con l'opzione --enable-maintainer-mode, lo script di configurazione non ricostruirà automaticamente lo script quando il file configure.in è aggiornato, così dovresti essere sicuro di farlo manualmente quando ti accorgi che il file configure.in è cambiato. Un segno di ciò è trovare cose simili a @VARIABLE@ nel tuo Makefile dopo aver eseguito la configurazione o il config.status.)

2. Ho problemi nel configurare PHP per farlo lavorare con Apache. Dice che è impossibile trovare il file httpd.h, ma questo è nel percorso che ho specificato!

Nello script di configurazione/setup devi specificare il percorso della cartella di livello più alto di Apache, cioè devi scrivere --with-apache=/path/to/apache e non --with-apache=/path/to/apache/src.

3. Durante la configurazione di PHP (./configure), si può incontrare un errore simile al seguente:

checking lex output file root... ./configure: lex: command not found
       configure: error: cannot find output from lex; giving up

Leggere attentamente le istruzioni di installazione e ricordarsi che per compilare il PHP occorre disporre sia di flex sia di bison. In base al proprio sistema si dovrà installare bison e flex dai sorgenti o da pacchetti tipo RPM.

4. Quando avvio Apache ottengo il seguente messaggio:

fatal: relocation error: file /path/to/libphp4.so:
       symbol ap_block_alarms: referenced symbol not found

Questo errore solitamente accade quando si compila il cuore di Apache come libreria DSO per utilizzo condiviso. Provare a riconfigurare Apache, prestando attenzione all'impostazione dei seguenti flag:

--enable-shared=max --enable-rule=SHARED_CORE

Per maggiori dettagli leggere INSTALL nella directory principale di Apache, oppure le pagine del manuale DSO.

5. Quando eseguo la configurazione, un messaggio di errore mi dice che non è possibile trovare file inclusi o librerie per GD, gdbm o qualche altro pacchetto!

Puoi ordinare allo script di configurazione di cercare di gli header e le librerie anche in posizioni non standard specificando flag addizionali da passare al preprocessore C, come:
CPPFLAGS=.I/percorso/da/includere LDFLAGS=-L/percorso/per/la/libreria ./configure
Se usi una variante di csh come shell di login (perché?), il codice diventa:
env CPPFLAGS=-I/percorso/da/includere LDFLAGS=-L/percorso/per/la/libreria ./configure

6. Quando cerco di compilare il file language-parser.tab.c, un messaggio di errore mi dice yytname undeclared.

Devi aggiornare la tua versione di Bison. Puoi trovare l'ultima versione su http://www.gnu.org/software/bison/bison.html.

7. Quando eseguo make sembra che vada tutto bene, ma lo script si blocca quando cerca di creare un collegamento all'applicazione finale, un messaggio di errore dice che non è possibile trovare alcuni file.

Qualche vecchia versione di make non mette le versioni compilate dei file nelle cartelle giuste. Prova ad eseguire cp *.o functions e quindi e rieseguire make e controlla se il messaggio di errore compare ancora. Se dovesse continuare ad apparire avrai bisogno di scaricare una versione più recente di make GNU.

8. Quando linko PHP, un messaggio di errore mi avvisa di parecchie undefined reference.

Controlla la linea relativa al link ed assicurati che tutte le librerie appropriate siano state incluse alla fine dello script. Le librerie più comuni che tu possa aver scordato sono le '-ldl' e quelle relative al supporto di qualche database che hai incluso.

Se stai linkando Apache 1.2.x, ti sei ricordato di aggiungere le informazioni appropriate nella linea EXTRA_LIBS del file di configurazione? Ti sei ricordato di rieseguire lo script di configurazione di Apache? Guarda il file INSTALL presente in questa distribuzione per avere maggiori informazioni.

Qualcuno che aveva problemi a linkare Apache ha risolto aggiungendo '-ldl' subito dopo libphp4.a.

9. Non riesco a capire come installare PHP con Apache 1.3.

Installare PHP insieme con Apache 1.3 è veramente semplice. Segui queste istruzioni:

  • Scarica l'ultima distribuzione di Apache 1.3 da http://www.apache.org/dist/httpd/.

  • Estrai prima l'archivio gzip e poi quello tar dove preferisci, per esempio in /usr/local/src/apache-1.3.

  • Compila PHP per la prima volta eseguendo: ./configure --with-apache=/<percorso>/apache-1.3 Sostituisci <percorso> con il percorso che porta alla cartella di Apache 1.3

  • Scrivi make seguito da make install per installare PHP e copiare i file necessari alla distribuzione di Apache.

  • Cambia il percorso delle cartelle fino al tuo /<percorso>/apache-1.3/src e modifica il file di Configuration. Aggiungi al file la riga seguente: AddModule modules/php4/libphp4.a.

  • Scrivi: ./configure seguito da make.

  • Ora dovresti avere un eseguibile httpd abilitato per PHP!

Nota: puoi anche usare il nuovo script ./configure di Apache. Leggi le istruzioni nel file README.configure presente nella tua distribuzione di Apache. Leggi anche il file INSTALL nella distribuzione di PHP.

10. Ho seguito le istruzioni per installare Apache come modulo sotto UNIX, ma il browser mi mostra il codice dei miei script PHP o mi viene chiesto di salvare la pagina PHP sul disco.

Questo significa che il modulo PHP non viene invocato correttamente per una qualche ragione. Prima di cercare ulteriore aiuto controlla tre cose:

  • Assicurati che l'httpd binario che stai eseguendo sia quello nuovo che hai appena installato. Per fare ciò prova ad eseguire: /percorso/per/il/file/eseguibile/httpd -l

    Se nell'elenco non compare mod_php4.c, significa che non stai eseguendo il binario giusto: trova ed installa il binario corretto.

  • Assicurati di aver aggiunto il corretto Myme Type ad uno dei tuoi file Apache .conf. Dovrebbe essere: AddType application/x-httpd-php3 .php3 (per PHP 3)

    o AddType application/x-httpd-php .php (per PHP 4)

    Assicurati anche che questa linea AddType non sia nascosta all'interno di un <Virtualhost> o di un blocco di <Directory> che possa impedire l'applicazione al percorso dei tuoi script di prova.

  • Infine sappi che il percorso predefinito del file di configurazione di Apache 1.2 è diverso da quello di Apache 1.3. Dovresti controllare che il file della linea AddType sia al momento letto. Puoi inserire un errore di sintassi di proposito nel file httpd.conf o effettuare qualche altro cambiamento che ti farà capire se il file è correntemente letto.

11. Un messaggio di errore mi dice di usare: --activate-module=src/modules/php4/libphp4.a, ma questo file non esiste, quindi l'ho cambiato in --activate-module=src/modules/php4/libmodphp4.a ma il tutto non funziona. Che succede?

Nota che si presume che il file libphp4.a non esista ancora. Sarà un processo di Apache a crearlo!

12. Quando provo ad installare Apache con PHP come modulo statico usando --activate-module=src/modules/php4/libphp4.a un messaggio di errore mi dice che il mio compilatore non è compatibile con ANSI.

Questo è un messaggio d'errore ingannevole di Apache, un bug che è stato corretto nelle versioni più recenti.

13. Quando provo ad installare Apache usando --with-apxs ricevo uno strano messaggio di errore.

Per risolvere questo problema devi controllare tre cose. Per iniziare, per qualche ragione, quando Apache installa gli script Perl apxs, ogni tanto finisce senza il compilatore appropriato e le variabili flag. Trova il tuo script apxs (prova il comando which apxs), ogni tanto lo trova in /usr/local/apache/bin/apxs o in /usr/sbin/apxs. Aprilo e cerca linee simili a queste:
my $CFG_CFLAGS_SHLIB  = '&nbsp;';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = '&nbsp;';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = '&nbsp;';          # substituted via Makefile.tmpl
Se vedi scritto esattamente questo, hai trovato il problema: queste linee potrebbero contenere spazi o altri valori sbagliati, come 'q()'. Cambia le linee precedenti come segue:
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
Il secondo problema possibile potrebbe solo essere una particolare distribuzione di Red Hat 6.1 e 6.2. L'unità degli script apxs in Red Hat non è funzionante. Cerca una linea simile a questa:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
Se trovi una linea identica a quella precedente, cambiala come segue:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Infine, se hai riconfigurato o reinstallato Apache, aggiungi un make clean al processo dopo ./configure e prima di make.

14. Quando eseguo make, ricevo errori nei microtime e un sacco di errori RUSAGE_.

Se durante la parte di installazione che riguarda make hai incontrato problemi simili a questi, significa che il tuo sistema ha qualche problema:
microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

Hai bisogno di fissare alcuni tuoi file in /usr/include installando un pacchetto glibc-devel che corrisponda al tuo glibc. Questo non ha assolutamente niente a che fare con PHP. Per controllare se il tuo problema dipende da questo, prova questo semplice test:
$ cat >test.c <<X
      #include <sys/resource.h>
      X
      $ gcc -E test.c >/dev/null
Se ricevi messaggi d'errore, allora i tuoi file include sono incasinati.

15. Quando si compila il PHP con MySQL, la configurazione viene eseguita correttamente, ma durante il make si ottiene un errore simile al seguente: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', che cosa c'è di sbagliato?

Primo, è importante realizzare che questo è un Warning e non un errore fatale. Poichè spesso questo è l'ultimo messaggio visibile durante il make, sembra indicare un errore fatale, ma non lo è. Certamente, se si imposta il compilatore ad uscire anche sui warning, questo lo farà. Ricordarsi inoltre, che il supporto per MySQL è abilitato per default.

Nota: Dal PHP 4.3.2, sarà visualizzato il seguente testo dopo il completamento della compila (make):

Build complete.
        (It is safe to ignore warnings about tempnam and tmpnam).

16. Voglio aggiornare il mio PHP. Dove posso trovare la linea di ./configure che è stata usata per creare la mia attuale versione di PHP?

Puoi cercare nel file config.nice nel sorgente della tua attuale installazione di PHP o eseguire questo semplice script:
<?php phpinfo(); ?>
Nella prima parte della pagina risultante è mostrata la linea ./configure usata durante la precedente installazione di PHP.

17. Quando si compila il PHP con la libreria GD, si ottiene dei strani errori di compila oppure dei segfault durante l'esecuzione.

Essere certi che la libreria GD e PHP condividano le medesime librerie (ad esempio libpng).

18. Quando si compila il PHP sembra di avere errori casuali, tipo blocchi. Se interessa sto utilizzando Solaris.

L'uso di utility non GNU per la compila del PHP può creare problemi. Occorre essere certi di utilizzare i tool GNU per essere certi della corretta compila del PHP. Ad esempio, con Solaris, l'utilizzo di SunOS BSD-compatibile con la versione di Solaris di sed crea dei problemi, ma utilizzando la versione GNU o Sun POSIX (xpg4) di sed non si avranno problemi. Riferimenti: GNU sed, GNU flex e GNU bison.


Capitolo 54. Using PHP

This section gathers many common errors that you may face while writing PHP scripts.

1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
2. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.
3. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?
4. When I do the following, the output is printed in the wrong order:
<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
what's going on?
5. Hey, what happened to my newlines?
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>
6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
7. I need to access information in the request header directly. How can I do this?
8. When I try to use authentication with IIS I get 'No Input file specified'.
9. Windows: I can't access files shared on another computer using IIS
10. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
11. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
12. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
13. Where can I find a complete list of variables are available to me in PHP?
14. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.
15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?

1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

PHP offers many predefined variables, like the superglobal $_POST. You may loop through $_POST as it's an associate array of all POSTed values. For example, let's simply loop through it with foreach, check for empty() values, and print them out.
<?php
$empty = $post = array();
foreach ($_POST as $varname => $varvalue) {
    if (empty($varvalue)) {
        $empty[$varname] = $varvalue;
    } else {
        $post[$varname] = $varvalue;
    }
}

print "<pre>";
if (empty($empty)) {
    print "None of the POSTed values are empty, posted:\n";
    var_dump($post);
} else {
    print "We have " . count($empty) . " empty values\n";
    print "Posted:\n"; var_dump($post);
    print "Empty:\n";  var_dump($empty);
    exit;
}
?>

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

2. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.

The function addslashes() will do this. See also mysql_escape_string(). You may also strip backslashes with stripslashes().

note per il parametro: magic_quotes_gpc: Il parametro magic_quotes_gpc è impostato per default a on. Essenzialmente esegue addslashes() su tutti i dati provenienti tramite GET, POST, e COOKIE. Si può utilizzare stripslashes() per rimuoverli.

3. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?

The PHP function stripslashes() will strip those backslashes from your string. Most likely the backslashes magically exist because the PHP directive magic_quotes_gpc is on.

note per il parametro: magic_quotes_gpc: Il parametro magic_quotes_gpc è impostato per default a on. Essenzialmente esegue addslashes() su tutti i dati provenienti tramite GET, POST, e COOKIE. Si può utilizzare stripslashes() per rimuoverli.

4. When I do the following, the output is printed in the wrong order:
<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
what's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return() the value, not echo() it.

5. Hey, what happened to my newlines?
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

6. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.

The functions header(), setcookie(), and the session functions need to add headers to the output stream but headers can only be sent before all other content. There can be no output before using these functions, output such as HTML. The function headers_sent() will check if your script has already sent headers and see also the Output Control functions.

7. I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:
<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
    echo "headers[$name] = $content<br />\n";
}
?>

See also apache_lookup_uri(), apache_response_headers(), and fsockopen()

8. When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/kb/q160422/ and the manual section on HTTP Authentication .

9. Windows: I can't access files shared on another computer using IIS

You have to change the Go to Internet Information Services. Locate your PHP file and go to its properties. Go to the File Security tab, Edit -< Anonymous access and authentication control.

You can fix the problem either by unticking Anonymous Access and leaving Integrated Window Authentication ticked, or, by ticking Anonymous Access and editing the user as he may not have the access right.

10. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.

Netscape is more strict regarding HTML tags (such as tables) then IE. Running your HTML output through a HTML validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.

Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.

11. How am I supposed to mix XML and PHP? It complains about my <?xml tags!

In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is on.

12. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?

One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.

13. Where can I find a complete list of variables are available to me in PHP?

Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.

register_globals: nota importante: A partire da PHP 4.2.0, il valore di default per il parametro register_globals è off. La comunità PHP incoraggia tutti a non basarsi su questo parametro, ma, piuttosto, usare altre strutture come superglobals.

14. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.

There are a few alternatives written in PHP such as http://www.ros.co.nz/pdf/, http://www.fpdf.org/, http://www.gnuvox.com/pdf4php/, and http://www.potentialtech.com/ppl.php. There is also the Panda module.

15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?

It's important to realize that the PHP directive register_globals also affects server and environment variables. When register_globals = off (the default is off since PHP 4.2.0), $DOCUMENT_ROOT will not exist. Instead, use $_SERVER['DOCUMENT_ROOT'] . If register_globals = on then the variables $DOCUMENT_ROOT and $GLOBALS['DOCUMENT_ROOT'] will also exist.

If you're sure register_globals = on and wonder why $DOCUMENT_ROOT isn't available inside functions, it's because these are like any other variables and would require global $DOCUMENT_ROOT inside the function. See also the manual page on variable scope. It's preferred to code with register_globals = off.

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

16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?

The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes; available since PHP 5.1.0), these are case insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. You may not use these shorthand notations outside of php.ini, instead use an integer value of bytes. See the ini_get() documentation for an example on how to convert these values.


Capitolo 55. PHP and HTML

PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from outside of PHP. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.

1. What encoding/decoding do I need when I pass a value through a form/URL?
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
3. How do I create arrays in a HTML <form>?
4. How do I get all the results from a select multiple HTML tag?
5. How can I pass a variable from Javascript to PHP?

1. What encoding/decoding do I need when I pass a value through a form/URL?

There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:

  • HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.

  • URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().

Esempio 55-1. A hidden HTML form element

<?php
    echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
?>

Nota: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.

Esempio 55-2. Data to be edited by the user

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Nota: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols.

Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.

Esempio 55-3. In a URL

<?php
    echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . "'>\n";
?>

Nota: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Nota: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencoded() the data.

You'll notice that the & in the URL is replaced by &amp;. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.

2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type="image" src="image.gif" name="foo" />
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from outside of PHP. For example, $_GET['foo_x'].

Nota: Spaces in request variable names are converted to underscores.

3. How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
The AnotherArray array will now contain the keys 0, 1, email and phone.

Nota: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables from outside PHP.

4. How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]'];

5. How can I pass a variable from Javascript to PHP?

Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a "stateless" protocol, the two languages cannot directly share variables.

It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this -- it allows PHP code to capture screen height and width, something that is normally only possible on the client side.

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>


Capitolo 56. PHP e COM

PHP può essere usato per accedere a oggetti COM o DCOM sotto piattaforme Win32.

1. Ho creato una DLL per calcolare qualcosa. Esiste un modo per eseguire questa DLL sotto PHP?
2. Cosa significa: 'Unsupported variant type: xxxx (0xxxxx)'?
3. È possibile manipolare dei visual object con PHP?
4. Posso salvare un oggetto COM in una sessione?
5. Come posso bloccare gli errori COM?
6. Tramite script Perl riesco a creare delle DLL: è possibile farlo anche in PHP?
7. Cosa significa: 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?
8. Come devo fare per eseguire oggetti COM da un server remoto?
9. Ricevo questo messaggio di errore: 'DCOM is disabled in C:\percorso...\nome_script.php on line 6'. Cosa posso fare?
10. È possibile caricare/manipolare un oggetto ActiveX in una pagina PHP?
11. È possibile un'istanza in esecuzione di un componente?
12. Esiste un modo per manipolare un evento inviato da un oggetto COM?
13. Sto riscontrando dei problemi quando provo a invocare un metodo di un oggetto COM che espone più di una interfaccia. Che cosa posso fare?
14. PHP riesce a lavorare con COM, ma come si comporta con COM+?
15. Se PHP può manipolare oggetti COM, immagino di poter usare MTS per amministrare le risorse dei componenti insieme a PHP.

1. Ho creato una DLL per calcolare qualcosa. Esiste un modo per eseguire questa DLL sotto PHP?

Se è una semplice DLL non esiste ancora un modo per poterla eseguire sotto PHP. Se la DLL contiene un server COM potresti essere in grado di eseguirla se è fornita di un'interfaccia IDispatch.

2. Cosa significa: 'Unsupported variant type: xxxx (0xxxxx)'?

Ci sono dozzine di tipi di VARIANT (varianti) e loro possibili combinazioni. La maggior parte di queste sono già supportate, ma una piccola parte deve ancora essere implementata. Gli array non sono ancora completamente supportati. Possono essere passati tra PHP e COm solo array non multidimesionali. Se trovi altri tipi che non sono supportati, segnalalo come un BUG (solo se non è già stato fatto da qualcun altro) e cerca di fornire il maggior numero possibile di informazioni.

3. È possibile manipolare dei visual object con PHP?

Generalmente sì, ma PHP, essendo per lo più usato come un linguaggio di scripting per il web, gira nel contesto di un webserver, quindi i visual object non appariranno mai sui desktope dei server. Per esempio se usi PHP per scrivere applicazioni insieme a PHP-GTK non ci sono limiti di sorta agli accessi o alla manipolazioni di visual object attraverso COM.

4. Posso salvare un oggetto COM in una sessione?

No, non puoi. Le istanze COM sono trattate come risorse e quindi sono disponibili solo nel contesto di un singolo script.

5. Come posso bloccare gli errori COM?

In PHP 5, il modulo COM genera un'eccezione com_exception, che può essere catturata per determinare come comporstarsi.

In PHP 4 non è possibile bloccare gli errori COM nei soliti modi disponibili in PHP (@, track_errors, ...).

6. Tramite script Perl riesco a creare delle DLL: è possibile farlo anche in PHP?

No, sfortunatamente non esiste ancora una funzione simile per PHP.

7. Cosa significa: 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?

Questo errore può essere determinato da diversi fattori:

  • il CLSID è sbagliato

  • manca una DLL richiesta

  • i componenti richiesti non implementano l'interfaccia IDispatch

8. Come devo fare per eseguire oggetti COM da un server remoto?

Nello stesso modo in cui esegui un oggetto COM in locale. Devi solo passare l'IP del server remoto come secondo parametro al costruttore COM.

Assicurati di aver settato com.allow_dcom =TRUE nel tuo php.ini.

9. Ricevo questo messaggio di errore: 'DCOM is disabled in C:\percorso...\nome_script.php on line 6'. Cosa posso fare?

Modifica il tuo php.ini e setta com.allow_dcom =TRUE.

10. È possibile caricare/manipolare un oggetto ActiveX in una pagina PHP?

Ciò non ha nulla a che vedere con PHP. Gli oggetti ActiveX sono caricati dalla macchina del visitatore (client side) se sono richiesti in una pagina HTML. Non esiste alcun nesso con gli script PHP e quindi non ci può essere nessun tipo di interazione sul server.

11. È possibile un'istanza in esecuzione di un componente?

Ciò è possibile con l'aiuto di soprannomi. Se vuoi ricevere referenze multiple di una stessa istanza, puoi creare l'istanza come segue:

<?php
$word = new COM("C:\docs\word.doc");
?>

Questo creerà una nuova istanza se non esistono istanza in esecuzione disponibili, o ritornerà un handle, se disponibile, dell'istanza in esecuzione.

12. Esiste un modo per manipolare un evento inviato da un oggetto COM?

Si possono creare i event sink e collegarli tramite com_event_sink(). Inoltre si può utilizzare com_print_typeinfo() per fare generare al PHP lo scheletro di una classe per gestire un event sink.

13. Sto riscontrando dei problemi quando provo a invocare un metodo di un oggetto COM che espone più di una interfaccia. Che cosa posso fare?

La risposta è semplice. Non so bene il perchè, ma non puoi farci niente. Se qualcuno avesse informazioni specifiche riguardo a ciò, è pregato di farle pervenire a questo indirizzo :)

14. PHP riesce a lavorare con COM, ma come si comporta con COM+?

COM+ estende COM tramite una struttura di amministrazione dei componenti attraverso MTS e MSMQ, ma non c'è niente di particolare che PHP dovrebbe avere in più per supportare anche questi componenti.

15. Se PHP può manipolare oggetti COM, immagino di poter usare MTS per amministrare le risorse dei componenti insieme a PHP.

PHP ancora non è in grado di manipolare di per sè le transazioni. Quindi se avviene un qualunque errore non viene eseguito nessun rollback. Se fai uso di componenti che supportano le transazioni dovrai implementare da te la gestione delle transazioni.


Capitolo 57. PHP e gli altri linguaggi di programmazione

PHP è il miglior linguaggio di programmazione per la programmazione web, ma cosa si può dire sugli altri linguaggi?

1. PHP vs. ASP?
2. Esiste un programma per convertire del codice ASP in codice PHP?
3. PHP o Cold Fusion?
4. PHP o Perl?

1. PHP vs. ASP?

ASP, acronimo di Active Server Pages, non è un vero è proprio linguaggio di programmazione, ma l'attuale linguaggio di programmazione per programmare con ASP è il Visual Basic Script o JScript. Il più grande svantaggio di questo linguaggio è il fatto che l'ASP è un linguaggio nato per essere usato solo con Microsoft Internet Information Server (IIS), cioè può essere usato solo su server Win32. Attualmente ci sono alcuni progetti in fase di sviluppo per consentire ad ASP di girare anche sotto altri sistemi operativi e webserver: InstantASP (maggiori informazioni sul sito commerciale di Halcyon), Chili!Soft ASP (maggiori informazioni sul sito commerciale Chili!Soft) e OpenASP from ActiveScripting.org (libero). Molti sostengono che ASP sia più lento e pesante di PHP, e anche meno stabile, ma un pregio di ASP è il fatto che, usando VBScript, è relativamente semplice avvicinarsi a questo linguaggio se si conosce già il Visual Basic. Il supporto ASP è inizialmente abilitato sui server IIS per consentire una rapida configurazione ed esecuzione del linguaggio stesso. I componenti forniti con ASP sono davvero limitati: se per esempio avessi bisogno di interagire con server FTP, dovresti comprare dei componenti aggiuntivi.

2. Esiste un programma per convertire del codice ASP in codice PHP?

Sì, uno dei più famosi e consigliati è asp2php.

3. PHP o Cold Fusion?

Generalmente PHP è considerato più efficente per script complessi e per sperimentare nuove idee; molti dicono inoltre che PHP sia più stabile e che usi meno risorse di sistema. Cold Fusion ha un miglior sistema per la gestione degli errori e per l'estrazione di dati da database, tuttavia in PHP 4 è stata implementata e velocizzata la consultazione dei database. Un altro punto di forza di Cold Fusion è il potente motore di ricerca di cui dispone, anche se il motore di ricerca non è qualcosa che possa essere incluso in un linguaggio di scripting dedicato al web. PHP gira su ogni tipo di piattaforma, Cold Fusion solo su server Win32, Solaris, Linux e HP/UX. Cold Fusion generalmente è un linguaggio più semplice da imparare, mentre PHP richiede qualche conoscenza iniziale prima di cominciare a programmare. Cold Fusion é progettato non preminentemente per i progrmmatori, mentre PHP è un linguaggio sviluppato proprio per i programmatori.

Un buon riassunto di Micheal J. Sheldon su questi argomenti è stato postato su una mailing list di PHP. Potete trovare una copia qui.

4. PHP o Perl?

Il più grande vantaggio che PHP ha su Perl è il fatto che PHP fu progettato solo per lo scripting web, mentre Perl fu progettato per fare molte alte cose, e quindi risulta molto più complicato. La flessibilità/complessità di Perl rende molto più semplice per un programmatore scrivere del codice che non leggere quello già scritto da un altro. PHP ha un codice più ordinato e preciso, senza però perdere in flessibilità. PHP ha a disposizione tutte le funzionalità di Perl: costrutti, sintassi a così via, senza però avere un codice altrettanto complicato. Perl è un linguaggio di programmazione vero e proprio molto testato, dato che il suo sviluppo iniziò negli anni ottanta, ma PHP sta maturando ed evolvendo molto rapidamente.


Capitolo 58. Migrazione da PHP 2 a PHP 3

PHP ha già una lunga storia dietro di se: Il leggendario PHP 1.0, PHP/FI, PHP 3.0 e PHP 4.0.

1. Migrazione da PHP 2 a PHP 3?

1. Migrazione da PHP 2 a PHP 3?

PHP/FI 2.0 non è più supportato. Per favore fare riferimento alla sezione appropriata del manuale per avere maggiori informazioni su come effettuare la migrazione da PHP/FI 2.0.

Se si sta ancora usando PHP 2, noi raccomandiamo fortemente di aggiornare direttamente a PHP 4.


Capitolo 59. Migrazione da PHP3 a PHP4

PHP ha già una lunga storia dietro di se: Il leggendario PHP 1.0, PHP/FI, PHP 3.0 e PHP 4.0.

1. Migrazione da PHP 3 a PHP 4
2. Esistono le sessioni in PHP 3?
3. Funzioni incompatibili?

1. Migrazione da PHP 3 a PHP 4

PHP 4 è stato sviluppato per essere il più possibile compatibile con le versioni precedenti di PHP e molte poche funzionalità sono state intaccate nel processo. Se si hanno dubbi sulla compatibilità si dovrebbe installare PHP 4 in un ambiente di test e provare a far girare i propri script lì.

Vedere anche l'appendice appropriata di questo manuale.

2. Esistono le sessioni in PHP 3?

Sebbene in PHP 3non esista il supporto nativo alle sessioni, esistono moduli di terze parti che offrono funzionalità di sessione. Il modulo più noto era PHPLIB.

3. Funzioni incompatibili?

Poiché PHP 4 è semplicemente una riscrittura dell'intero engine PHP, solo alcune funzioni sono state alterare e solo alcune molto esotiche.


Capitolo 60. Migrating from PHP 4 to PHP 5

This faq section will help you migrate from PHP 4 to PHP 5.

1. Migrating from PHP 4 to PHP 5
2. Does MySQL work in PHP 5? It seemed to have disappeared.
3. I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?
4. So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?

1. Migrating from PHP 4 to PHP 5

Although PHP 5 offers many new features, it's designed to be as compatible with earlier versions of PHP as possible with little functionality being broken in the process.

Be sure to read the appropriate PHP 5 migration appendix of this manual as it contains even more information on the topic of migrating to PHP 5.

2. Does MySQL work in PHP 5? It seemed to have disappeared.

MySQL is supported with the only change being that MySQL support is no longer enabled by default in PHP 5. This essentially means that PHP doesn't include the --with-mysql option in the configure line so that you must now manually do this when compiling PHP. Windows users will edit php.ini and enable the php_mysql.dll DLL as in PHP 4 no such DLL existed, it was simply built into your Windows PHP binaries.

Also, the MySQL client libraries are no longer bundled with PHP. More details on this topic are covered in the following FAQ and be sure to read the MySQL section for details on installing MySQL. An example configure line would be --with-mysql=/usr while Windows users will need the libmySQL.dll available to the system.

3. I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?

The main change in PHP 5 is to the OOP model as PHP 5 now uses the Zend Engine 2.0. The zend.ze1_compatibility_mode directive enables compatability with the Zend Engine 1.0 (PHP 4).

The new OOP model is documented in the OOP language reference and OOP migration appendix sections.

4. So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?

Few other changes exist, see the migration 5 appendix for details. There won't be a PHP 5 specific version of the manual as the bulk of PHP remains the same.


Capitolo 61. Domande varie

Ci sono diverse domande che ricorrono frequentemente ma che non possono essere inserite in una delle categorie principali: puoi torvare queste domande in questa sezione.

1. Come si fanno a creare le pop-up in un sito web? È possibile avere il codice per crearle?
2. Come posso gestire i file compressi bz2 sotto Windows?

1. Come si fanno a creare le pop-up in un sito web? È possibile avere il codice per crearle?

Le pop-up gialle stile vecchio Windows sono molto carine, ma sono anche molto difficili da mantenere (da quando qualche società sembra divertirsi nel cambiare il modo in cui il proprio browser lavora con le nuove release).

Tutto il codice delle versioni precedenti del sito sono ancora disponibili mediante CVS. In modo particolare, l'ultima versione di shared.inc (che contiene tutto il codice Javascript e DHTML per le pop-up) è disponibile a questo link.

2. Come posso gestire i file compressi bz2 sotto Windows?

Se non hai un software in grado di estrarre gli archivi bz2, scarica questo programma a riga di comando per RedHat (leggi più sotto per maggiori informazioni).

Se non vuoi usare la riga di comando, puoi scaricare uno di questi software grauiti: Stuffit Expander, UltimateZip, 7-Zip o Quick Zip. Se hai già dei software tipo WinRAR o Power Archiver, puoi gestire senza problemi gli archivi bz2. Se usi Windows Commander, sul sito Windows Commander è disponibile un plugin gratuito per gestire i file bz2.

Programma a riga di comando per RedHat:

Gli utenti Sp2 Win2k possono scaricare l'ultima versione, la 1.0.2, tutti gli altri utenti Windows devono scaricare la versione 1.00. Dopo aver scaricato il file, rinominarlo in bzip2.exe. Per comodità copia questo file in una cartella del tuo hard disk principale, per esempio C:\Windows (dove C rappresenta la lettera del tuo hard disk).

Nota: 'lang' indica la tua lingua e x il formato desiderato, per esempio pdf. Per decomprimere il file php_manual.x.bz2 segui queste semplici istruzioni:

  • Apri il prompt dei comandi di WIndows

  • Entra nella cartella che contiene il file php_manual_lang.x.bz2 (cd nome_cartella)

  • digita bzip2 -d php_manual_lang.x.bz2 per estrarre il file nella stessa cartella

Nel caso tu abbia scaricato il manuale php_lang.tar.bz2 nel formato contenente molti file HTML, la procedura sarà la stessa. La sola differenza è che hai scaricato un file *.tar. Il formato *.tar è famoso perchè viene riconosciuto dalla maggior parte dei software di archiviazione per Windows, per esempio WinZip.


Appendice A. History of PHP and related projects

PHP has come a long way in the last few years. Growing to be one of the most prominent languages powering the Web was not an easy task. Those of you interested in briefly seeing how PHP grew out to what it is today, read on. Old PHP releases can be found at the PHP Museum.


History of PHP

PHP/FI

PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code.

PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent.

By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project.

PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.


PHP 3

PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI's existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax.

The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor.

By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet.

PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.


PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet.

PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.


PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. To get more information on this engine, see its webpage.


History of PHP related projects

PEAR

PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute PHP extensions among developers.

PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.

Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.

More information about PEAR can be found in the manual.


PHP Quality Assurance Initiative

The PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.


PHP-GTK

PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:

GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.

Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.

Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.

Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.

Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.


Books about PHP

As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.

To the best of our knowledge, the first book dedicated to PHP was 'PHP - tvorba interaktivních internetových aplikací' - a Czech book published in April 1999, authored by Jirka Kosek. Next month followed a German book authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. Both of these books covered PHP 3.0.

While these books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 40 books in English, 50 books in German, and over 20 books in French! In addition, you can find books about PHP in many other languages, including Spanish, Korean, Japanese and Hebrew.

Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.


Publications about PHP

To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the Czech mutation of Computerworld in the spring of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.

Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!


Appendice B. Migrating from PHP 4 to PHP 5

What has changed in PHP 5

PHP 5 and the integrated Zend Engine 2 have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 4 to 5 should be very easy. Most existing PHP 4 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments.


Backward Incompatible Changes

Although most existing PHP 4 code should work without changes, you should pay attention to the following backward incompatible changes:

  • There are some new reserved keywords.

  • strrpos() and strripos() now use the entire string as a needle.

  • Illegal use of string offsets causes E_ERROR instead of E_WARNING. An example illegal use is: $str = 'abc'; unset($str[0]);.

  • array_merge() was changed to accept only arrays. If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. Be careful because your code may start emitting E_WARNING out of the blue.

  • PATH_TRANSLATED server variable is no longer set implicitly under Apache2 SAPI in contrast to the situation in PHP 4, where it is set to the same value as the SCRIPT_FILENAME server variable when it is not populated by Apache. This change was made to comply with the CGI specification. Please refer to bug #23610 for further information, and see also the $_SERVER['PATH_TRANSLATED'] description in the manual. This issue also affects PHP versions >= 4.3.2.

  • The T_ML_COMMENT constant is no longer defined by the Tokenizer extension. If error_reporting is set to E_ALL, PHP will generate a notice. Although the T_ML_COMMENT was never used at all, it was defined in PHP 4. In both PHP 4 and PHP 5 // and /* */ are resolved as the T_COMMENT constant. However the PHPDoc style comments /** */, which starting PHP 5 are parsed by PHP, are recognized as T_DOC_COMMENT.

  • $_SERVER should be populated with argc and argv if variables_order includes "S". If you have specifically configured your system to not create $_SERVER, then of course it shouldn't be there. The change was to always make argc and argv available in the CLI version regardless of the variables_order setting. As in, the CLI version will now always populate the global $argc and $argv variables.

  • An object with no properties is no longer considered "empty".

  • In some cases classes must be declared before used. It only happens only if some of the new features of PHP 5 are used. Otherwise the behaviour is the old.

  • get_class(), get_parent_class() and get_class_methods() now return the name of the classes/methods as they were declared (case-sensitive) which may lead to problems in older scripts that rely on the previous behaviour (the class/method name was always returned lowercased). A possible solution is to search for those functions in all your scripts and use strtolower().

    This case sensitivity change also applies to the magical predefined constants __CLASS__, __METHOD__, and __FUNCTION__. The values are returned exactly as they're declared (case-sensitive).

  • ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.

  • If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about it. It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.

  • include_once() and require_once() first normalize the path of included file on Windows so that including A.php and a.php include the file just once.

Esempio B-1. strrpos() and strripos() now use the entire string as a needle

<?php
var_dump(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?>

Esempio B-2. An object with no properties is no longer considered "empty"

<?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    // Will be executed
}
?>

Esempio B-3. In some cases classes must be declared before used

<?php

//works with no errors:
$a = new a();
class a {
}


//throws an error:
$a = new b();

interface c{
}
class b implements c {
} 

?>


CLI and CGI

In PHP 5 there were some changes in CLI and CGI filenames. In PHP 5, the CGI version was renamed to php-cgi.exe (previously php.exe) and the CLI version now sits in the main directory (previously cli/php.exe).

In PHP 5 it was also introduced a new mode: php-win.exe. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk.

In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.

See also the commandline reference.


Migrating Configuration Files

Since the ISAPI modules changed their names, from php4xxx to php5xxx, you need to make some changes in the configuration files. There were also changes in the CLI and CGI filenames. Please refer to the corresponding section for more information.

Migrate the Apache configuration is extremely easy. See the example below to check the change you need to do:

Esempio B-4. Migrating Apache configuration files for PHP 5

# change this line:    
LoadModule php4_module /php/sapi/php4apache2.dll

# with this one:
LoadModule php5_module /php/php5apache2.dll

If your webserver is running PHP in CGI mode, you should note that the CGI version has changed its name from php.exe to php-cgi.exe. In Apache, you should do something like this:

Esempio B-5. Migrating Apache configuration files for PHP 5, CGI mode

# change this line:    
Action application/x-httpd-php "/php/php.exe" 

# with this one:
Action application/x-httpd-php "/php/php-cgi.exe"

In other webservers you need to change either the CGI or the ISAPI module filenames.


New Functions

In PHP 5 there are some new functions. Here is the list of them:

Arrays:

  • array_combine() - Creates an array by using one array for keys and another for its values

  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function

  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison

  • array_udiff_assoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function

  • array_udiff_uassoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also

  • array_walk_recursive() - Apply a user function recursively to every member of an array

  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check. The data is compared by using a callback function

  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check. Both the data and the indexes are compared by using a callback functions

  • array_uintersect() - Computes the intersection of arrays. The data is compared by using a callback function

InterBase:

iconv:

Streams:

Date and time related:

Strings:

  • str_split() - Convert a string to an array

  • strpbrk() - Search a string for any of a set of characters

  • substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters

Other:

Nota: The Tidy extension has also changed its API completely.


New Directives

There were some new php.ini directives introduced in PHP 5. Here is a list of them:

  • mail.force_extra_parameters - Force the addition of the specified parameters to be passed as extra parameters to the sendmail binary. These parameters will always replace the value of the 5th parameter to mail(), even in safe mode

  • register_long_arrays - allow/disallow PHP to register the deprecated long $HTTP_*_VARS

  • session.hash_function - select a hash function (MD5 or SHA-1)

  • session.hash_bits_per_character - define how many bits are stored in each character when converting the binary hash data to something readable (from 4 to 6)

  • zend.ze1_compatibility_mode - Enable compatibility mode with Zend Engine 1 (PHP 4)


Databases

There were some changes in PHP 5 regarding databases (MySQL and SQLite).

In PHP 5 the MySQL client libraries are not bundled, because of license problems and some others. For more information, read the FAQ entry.

There is also a new extension, MySQLi (Improved MySQL), which is designed to work with MySQL 4.1 and above.

Since PHP 5, the SQLite extension is built-in PHP. SQLite is an embeddable SQL database engine and is not a client library used to connect to a big database server (like MySQL or PostgreSQL). The SQLite library reads and writes directly to and from the database files on disk.


New Object Model

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. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or pass as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Many PHP programmers aren't even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications.

The new Object Model is documented at the Language Reference.

See also the zend.ze1_compatibility_mode directive for compatability with PHP 4.


Error Reporting

As of PHP 5 new error reporting constant E_STRICT was introduced with value 2048. It enables run-time PHP suggestions on your code interoperability and forward compatibility, that will help you to keep latest and greatest suggested method of coding. E.g. STRICT message will warn you on using deprecated functions.

Nota: E_ALL does not include E_STRICT so it's not enabled by default


Appendice C. Migrating from PHP 3 to PHP 4

What has changed in PHP 4

PHP 4 and the integrated Zend engine have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 3 to 4 should be much easier than migrating from PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments. The following should give you some hints about what to look for.


Running PHP 3 and PHP 4 concurrently

Recent operating systems provide the ability to perform versioning and scoping. This features make it possible to let PHP 3 and PHP 4 run as concurrent modules in one Apache server.

This feature is known to work on the following platforms:

  • Linux with recent binutils (binutils 2.9.1.0.25 tested)

  • Solaris 2.5 or better

  • FreeBSD (3.2, 4.0 tested)

To enable it, configure PHP 3 and PHP 4 to use APXS (--with-apxs) and the necessary link extensions (--enable-versioning). Otherwise, all standard installations instructions apply. For example:

$ ./configure \
  --with-apxs=/apache/bin/apxs \
  --enable-versioning \
  --with-mysql \
  --enable-track-vars


Migrating Configuration Files

The global configuration file, php3.ini, has changed its name to php.ini.

For the Apache configuration file, there are slightly more changes. The MIME types recognized by the PHP module have changed.

application/x-httpd-php3        -->    application/x-httpd-php
application/x-httpd-php3-source -->    application/x-httpd-php-source

You can make your configuration files work with both versions of PHP (depending on which one is currently compiled into the server), using the following syntax:

AddType  application/x-httpd-php3        .php3
AddType  application/x-httpd-php3-source .php3s

AddType  application/x-httpd-php         .php
AddType  application/x-httpd-php-source  .phps

In addition, the PHP directive names for Apache have changed.

Starting with PHP 4.0, there are only four Apache directives that relate to PHP:

php_value [PHP directive name] [value]
php_flag [PHP directive name] [On|Off]
php_admin_value [PHP directive name] [value]
php_admin_flag [PHP directive name] [On|Off]

There are two differences between the Admin values and the non admin values:

  • Admin values (or flags) can only appear in the server-wide Apache configuration files (e.g., httpd.conf).

  • Standard values (or flags) cannot control certain PHP directives, for example: modalità sicura (if you could override safe mode settings in .htaccess files, it would defeat modalità sicura's purpose). In contrast, Admin values can modify the value of any PHP directive.

To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.

To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:

~/php4/scripts/apache:#  ./apconf-conv.sh /usr/local/apache/conf/httpd.conf

Your original configuration file will be saved in httpd.conf.orig.

To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):

~/php4/scripts/apache:#  find / -name .htaccess -exec ./aphtaccess-conv.sh {} \;

Likewise, your old .htaccess files will be saved with an .orig prefix.

The conversion scripts require awk to be installed.


Parser behavior

Parsing and execution are now two completely separated steps, no execution of a files code will happen until the complete file and everything it requires has completely and successfully been parsed.

One of the new requirements introduced with this split is that required and included files now have to be syntactically complete. You can no longer spread the different controlling parts of a control structure across file boundaries. That is you cannot start a for or while loop, an if statement or a switch block in one file and have the end of loop, else, endif, case or break statements in a different file.

It still perfectly legal to include additional code within loops or other control structures, only the controlling keywords and corresponding curly braces {...} have to be within the same compile unit (file or eval()ed string).

This should not harm too much as spreading code like this should be considered as very bad style anyway.

Another thing no longer possible, though rarely seen in PHP 3 code is returning values from a required file. Returning a value from an included file is still possible.


Error reporting

Configuration changes

With PHP 3 the error reporting level was set as a simple numeric value formed by summing up the numbers related to different error levels. Usual values were 15 for reporting all errors and warnings or 7 for reporting everything but simple notice messages reporting bad style and things like that.

PHP 4 has a larger set of error and warning levels and comes with a configuration parser that now allows for symbolic constants to be used for setting the intended behavior.

Error reporting level should now be configured by explicitly taking away the warning levels you do not want to generate error messages by x-oring them from the symbolic constant E_ALL. Sounds complicated? Well, lets say you want the error reporting system to report all but the simple style warnings that are categorized by the symbolic constant E_NOTICE. Then you'll put the following into your php.ini: error_reporting = E_ALL & ~ ( E_NOTICE ). If you want to suppress warnings too you add up the appropriate constant within the braces using the binary or operator '|': error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING ).

Avvertimento

When upgrading code or servers from PHP 3 to PHP 4 you should check these settings and calls to error_reporting() or you might disable reporting the new error types, especially E_COMPILE_ERROR. This may lead to empty documents without any feedback of what happened or where to look for the problem.

Avvertimento

Using the old values 7 and 15 for setting up error reporting is a very bad idea as this suppresses some of the newly added error classes including parse errors. This may lead to very strange behavior as scripts might no longer work without error messages showing up anywhere.

This has lead to a lot of unreproducible bug reports in the past where people reported script engine problems they were not capable to track down while the TRUE case was usually some missing '}' in a required file that the parser was not able to report due to a misconfigured error reporting system.

So checking your error reporting setup should be the first thing to do whenever your scripts silently die. The Zend engine can be considered mature enough nowadays to not cause this kind of strange behavior.


Additional warning messages

A lot of existing PHP 3 code uses language constructs that should be considered as very bad style as this code, while doing the intended thing now, could easily be broken by changes in other places. PHP 4 will output a lot of notice messages in such situations where PHP 3 didn't. The easy fix is to just turn off E_NOTICE messages, but it is usually a good idea to fix the code instead.

The most common case that will now produce notice messages is the use of unquoted string constants as array indices. Both PHP 3 and 4 will fall back to interpret these as strings if no keyword or constant is known by that name, but whenever a constant by that name had been defined anywhere else in the code it might break your script. This can even become a security risk if some intruder manages to redefine string constants in a way that makes your script give him access rights he wasn't intended to have. So PHP 4 will now warn you whenever you use unquoted string constants as for example in $_SERVER[REQUEST_METHOD]. Changing it to $_SERVER['REQUEST_METHOD'] will make the parser happy and greatly improve the style and security of your code.

Another thing PHP 4 will now tell you about is the use of uninitialized variables or array elements.


Initializers

Static variable and class member initializers only accept scalar values while in PHP 3 they accepted any valid expression. This is, once again, due to the split between parsing and execution as no code has yet been executed when the parser sees the initializer.

For classes you should use constructors to initialize member variables instead. For static variables anything but a simple static value rarely makes sense anyway.


empty("0")

The perhaps most controversial change in behavior has happened to the behavior of the empty(). A String containing only the character '0' (zero) is now considered empty while it wasn't in PHP 3.

This new behavior makes sense in web applications, with all input fields returning strings even if numeric input is requested, and with PHP's capabilities of automatic type conversion. But on the other hand it might break your code in a rather subtle way, leading to misbehavior that is hard to track down if you do not know about what to look for.


Missing functions

While PHP 4 comes with a lot of new features, functions and extensions, you may still find some functions from version 3 missing. A small number of core functions has vanished because they do not work with the new scheme of splitting parsing and execution as introduced into 4 with the Zend engine. Other functions and even complete extensions have become obsolete as newer functions and extensions serve the same task better and/or in a more general way. Some functions just simply haven't been ported yet and finally some functions or extensions may be missing due to license conflicts.


Functions missing due to conceptual changes

As PHP 4 now separates parsing from execution it is no longer possible to change the behavior of the parser (now embedded in the Zend engine) at runtime as parsing already happened by then. So the function short_tags() no longer exists. You can still change the parsers behavior by setting appropriate values in the php.ini file.

Another feature of PHP 3 that is not a part of PHP 4 is the bundled debugging interface. There are third-party add-ons for the Zend engine which add similar functionality.


Deprecate functions and extensions

The Adabas and Solid database extensions are no more. Long live the unified ODBC extension instead.


Changed status for unset()

unset(), although still available, is implemented as a language construct rather than a function.

This does not have any consequences on the behavior of unset(), but testing for "unset" using function_exists() will return FALSE as it would with other language constructs that look like functions such as echo().

Another more practical change is that it is no longer possible to call unset() indirectly, that is $func="unset"; $func($somevar) won't work anymore.


PHP 3 extension

Extensions written for PHP 3 will not work with PHP 4, neither as binaries nor at the source level. It is not difficult to port extensions to PHP 4 if you have access to the original source. A detailed description of the actual porting process is not part of this text.


Variable substitution in strings

PHP 4 adds a new mechanism to variable substitution in strings. You can now finally access object member variables and elements from multidimensional arrays within strings.

To do so you have to enclose your variables with curly braces with the dollar sign immediately following the opening brace: {$...}

To embed the value of an object member variable into a string you simply write "text {$obj->member} text" while in PHP 3 you had to use something like "text ".$obj->member." text".

This should lead to more readable code, while it may break existing scripts written for PHP 3. But you can easily check for this kind of problem by checking for the character combination {$ in your code and by replacing it with \{$ with your favorite search-and-replace tool.


Cookies

PHP 3 had the bad habit of setting cookies in the reverse order of the setcookie() calls in your code. PHP 4 breaks with this habit and creates the cookie header lines in exactly the same order as you set the cookies in the code.

This might break some existing code, but the old behaviour was so strange to understand that it deserved a change to prevent further problems in the future.


Handling of global variables

While handling of global variables had the focus on to be easy in PHP 3 and early versions of PHP 4, the focus has changed to be more secure. While in PHP 3 the following example worked fine, in PHP 4 it has to be unset(unset($GLOBALS["id"]));. This is only one issue of global variable handling. You should always have used $GLOBALS, with newer versions of PHP 4 you are forced to do so in most cases. Read more on this subject in the global references section.

Esempio C-1. Migration of global variables

<?php
$id = 1;
function test()
{
    global $id;
    unset($id);
}
test();
echo($id); // This will print out 1 in PHP 4
?>

Appendice D. Migrazione da PHP/FI 2 a PHP 3

Incompatibilià in 3.0

PHP 3.0 è rescritto da terra in su. Ha un proprio parser che è molto più robusto è consistente della 2.0. PHP 3.0 è anche significativamente più veloce ed usa meno memoria. Tuttavia, alcuni di questi miglioramenti non sarebbero resi possibili senza i cambiamenti delle compatibilità, sia in sintassi che nelle funzionalità.

In più, gli sviluppatori di PHP hanno cercato di pulire sia sintassi del PHP che la semantica nella versione 3.0, e questo ha anche causato alcune incompatibilità. A lungo termine, crediamo che questi cambiamenti siano per il migliore.

Questo capitolo proverà a guidarti tra le incompatibilità che potresti trovare passando da PHP/FI 2.0 a PHP 3.0 ed auitarti a resolverli. Almeno dove è necessario, le nuove funzionalità non vi sono accennate.

Un programma di conversione che può convertire automaticamente i vostri vecchi script di PHP/FI 2.0 esiste già. Può essere trovato in convertor sottodirectory della distribuzione di PHP 3.0. Questo programma, comunque, interferisce soltanto sui cambiamenti di sintassi, per ciò bisogna legere questo capitolo lo stesso.


old_function

L'istruzione old_function permette di dichiarare una funzione utilizzando una sintassi simile a PHP/FI2 (tranne che occorre sostituire 'function' con 'old_function').

Questa è un'opzione sconsigliata e dovrebbe essere utilizzata solo dal convertitore PHP/FI2->PHP 3.

Avvertimento

Funzioni dichiarate come old_function non possono essere chiamata dal codice interno al PHP. Tra le altre cose, questo significa che si possono utilizzare queste funzioni in usort(), array_walk(), e register_shutdown_function(). Si può aggirare questa limitazione scrivendo un proprio wrapper (nel normale metodo PHP 3) e da qui chiamare la old_function.


Inizio/fine tags di PHP

La prima cosa che probabilmente noterete è la modificha dei tag del inizio e della fine di PHP. Il vecchio <? > è stato sostituito da tre nuove forme possibili:

Esempio D-1. Migrazione: vecchio inizio/fine tag

<? echo "Questo &egrave; il codice di PHP/FI 2.0\n"; ?>
La versione 2.0, PHP/FI supporta anche questa variazione:

Esempio D-2. Migrazione: primo nuovo inizio/fine tag

<? echo "Questo &egrave; il codice di PHP 3.0\n"; ?>
Nota che il tag della fine ora consiste di un punto interrogativo e di un superiore-che carattere anziché solamente un superiore-che. Comunque, se pensate di usare XML sul vostro server, avrete dei problemi con la prima nuova variazione perché PHP potrebbe provare ad eseguire il XML markup nei documenti XML come un codice PHP. Per questa raggione, la seguente variazione è stata introdotta:

Esempio D-3. Migrazione: secondo nuovo inizio/fine tag

<?php echo "Questo &egrave; il codice di PHP 3.0\n"; ?>
Alcune persone hanno avuto dei problemi con gli editor che non capiscono affatto i tag di istruzione del processo. Microsoft FrontPage è un tale editor. Per evitare un suo comportamento scoretto la seguente variazione è anche stata introdotta:

Esempio D-4. Migrazione: terzo nuovo inizio/fine tag

<script language="php">

  echo "Questo &egrave; il codice di PHP 3.0\n";

</script>


Sintassi di if..endif

Un modo `alternativo' di scrivere le istruzioni if/elseif/else usando if(); elseif(); else; endif; non può essere implementato efficientemente senza aggiungere una gran parte di complessità nel parser 3.0. Per questo, la sintassi è stata cambiata:

Esempio D-5. Migrazione: vecchia sintassi di if..endif

if ($foo);
    echo "Si\n";
elseif ($bar);
    echo "Quasi\n";
else;
    echo "No\n";
endif;

Esempio D-6. Migrazione: nuova sintassi di if..endif

if ($foo):
    echo "Si\n";
elseif ($bar):
    echo "Quasi\n";
else:
    echo "No\n";
endif;
Nota che il punto e virgola e stata sostituita dai due punti in tutte le istruzioni tranne quella che termina l'espressione (endif).


Sintassi di while

Stesso come con if..endif, la sintassi di while..endwhile è anche cambiata:

Esempio D-7. Migrazione: vecchia sintassi di while..endwhile

while ($piu_roba_qui);
    ...
endwhile;

Esempio D-8. Migrazione: nuova sintassi di while..endwhile

while ($piu_roba_qui):
    ...
endwhile;

Avvertimento

Usando la vecchia sintassi di while..endwhile in PHP 3.0, otterreste un ciclo infinito.


Tipi di espressione

PHP/FI 2.0 usava il lato sinistro delle espressioni per determinare che tipo il risultato dovrebbe essere. PHP 3.0 prende entrambi i lati in considerazione quando determina i tipi del risultato, e questo può causare un comportamento inaspettato dei script 2.0 in versione 3.0.

Considera questo exampio:

$a[0]=5;
$a[1]=7;

$key = key($a);
while ("" != $key) {
    echo "$keyn";
    next($a);
}

In PHP/FI 2.0, questo visualizzerebbe entrambi gli indici di $a. In PHP 3.0, invece, non visualizzerebbe nulla. Il motivo è che in PHP 2.0, siccome il tipo del'argomento sinistro è una stringa, è stato fatto una paragono tra le stringhe, ed infatti, "" non è uguale a "0", per ciò il ciclo è continuato. In PHP 3.0, quando una stringa è paragonata ad un intero, viene fatto un paragone fra gli interi (la stringa è convertita in intero). Ciò provoca una confrontazione di atoi("") che è 0, e variablelist che è anche 0, e siccome 0==0, il ciclo non passa neanche una volta.

La soluzione è semplice. Sostituisci l'espressione while con:

while ((string)$key != "") {


I messaggi di errore sono cambiati

I messaggi di errore in PHP 3.0 sono spesso più esatti di quanto erano quelli di 2.0, anche se non è più possibile di visuallizare il codice che causa l'errore. Si visuallizerano comunque il nome del file e la linea sulla quale l'errore è accaduto.


Valutazione cortocircuita booleana

In PHP 3.0 valutazione booleana è cortocircuita. Questo significa che in una espressione come (1 || testami()), la funzione testami() non sarebbe eseguita poiché niente può cambiare il risultato dell'espressione dopo1.

Questa è una questione di compatibilità minore, ma può causare dei effetti laterali inattesi.


TRUE/FALSE valori ritornati dalle funzioni

La maggior parte delle funzioni interne sono state riscritte in modo che ritornino TRUE al successo e FALSE al fallimento, invece di 0 e -1 come nel PHP/FI 2.0. Il nuovo comportamento aggevola un codice più logico, come $fp = fopen("/tuo/file") or fail("fallito!");. Datto che PHP/FI 2.0 non ha avuto una chiara regola su cosa deve ritornare una funzione fallita, la maggior parte dei tali scritti probabilmente dovranno essere verificate manualmente dopo aver usato il convertitore 2.0 - 3.0.

Esempio D-9. Migrazione da 2.0: valori di ritorno, vecchio codice

$fp = fopen($file, "r");
if ($fp == -1);
    echo("Apertura per la lettura del $file fallita<br />\n");
endif;

Esempio D-10. Migrazione da 2.0: valori di ritorno, nuovo codice

$fp = @fopen($file, "r") or print("Apertura per la lettura del $file fallita<br />\n");


Altre incompatibilità

  • Il modulo Apache per PHP 3.0 non supporta più le versioni Apache inferiori a 1.2. Apache 1.2 e superiore è necessario.

  • echo() non supporta più una stringa formattata. Usa per questo la funzione printf().

  • In PHP/FI 2.0, un implementazione collateranea causava $foo[0] di avere lo stesso effetto di $foo. Questo non è più cosi in PHP 3.0.

  • Leggere gli array con $array[] non è piu supportato

    Cioè, non si puo aprire un array con un ciclo che fà $data = $array[]. Usa current() e next() per avere questo effetto.

    Inoltre, $array1[] = $array2 non aggiunge i valori di $array2 a $array1, ma invece aggiunge $array2 come làultima entrata di $array1. Vedi anche il supporto di array multidimensionali.

  • "+" non è più usato come un operatore di concatenazione per le stringhe, invece converte i suoi argumenti in numeri e realizza l'aggiunta numerica. Usa "." al posto suo.

Esempio D-11. Migrazione da 2.0: concatenazione delle stringhe

echo "1" + "1";

In PHP 2.0 avrebbe emettesso 11, in PHP 3.0 invece emetterebbe 2. Perciò si usa:
echo "1"."1";
$a = 1;
$b = 1;
echo $a + $b;

Emette 2 in entrambi PHP 2.0 e 3.0.
$a = 1;
$b = 1;
echo $a.$b;
Questo emettera 11 in PHP 3.0.


Appendice E. Debugging PHP

Il debugger

PHP 3 include supporto per il debugger network-based.

PHP 4 non ha un sistema interno per il debugging. È possibile utilizzare comunque dei debugger esterni. Zend IDE include un debugger; ci sono anche delle estensioni di debugging gratuite come DBG su http://dd.cron.ru/dbg/ oppure Advanced PHP Debugger (APD).


Utilizzare il Debugger

Il debugger interno del PHP 3 è utile per tracciare errori non visibili. Il debugger funziona tramite una connessione ad una porta TCP che viene attivata ogni volta che viene eseguito il PHP 3. Tutti i messaggi di errore generati da quella richiesta, vengono inviati a questa connessione TCP. Questa modalità è pensata per i "server di debugging" che possono essere eseguiti all'interno di un IDE o di un editor programmabile (tipo Emacs).

Come configurare il debugger:

  1. impostare una porta TCP per il debugger nel file di configurazione (debugger.port) e attivarla (debugger.enabled).

  2. Impostare un TCP listener sulla porta scelta (per esempio socket -l -s 1400 su UNIX).

  3. Nel codice, eseguire "debugger_on(host)", dove host è l'indirizzo IP o il nome dell'host su cui è in esecuzione il TCP listener.

Dopo di chè, tutti le avvertenze, notizie ecc. verranno mostrate in questo socket, anche qualora li spegneste con error_reporting().


Debugger Protocol

The PHP 3 debugger protocol is line-based. Each line has a type, and several lines compose a message. Each message starts with a line of the type start and terminates with a line of the type end. PHP 3 may send lines for different messages simultaneously.

A line has this format:


date time
host(pid)
type:
message-data
     

date

Date in ISO 8601 format (yyyy-mm-dd)

time

Time including microseconds: hh:mm:uuuuuu

host

DNS name or IP address of the host where the script error was generated.

pid

PID (process id) on host of the process with the PHP 3 script that generated this error.

type

Type of line. Tells the receiving program about what it should treat the following data as:

Tabella E-1. Debugger Line Types

NameMeaning
start Tells the receiving program that a debugger message starts here. The contents of data will be the type of error message, listed below.
messageThe PHP 3 error message.
location File name and line number where the error occurred. The first location line will always contain the top-level location. data will contain file:line. There will always be a location line after message and after every function.
framesNumber of frames in the following stack dump. If there are four frames, expect information about four levels of called functions. If no "frames" line is given, the depth should be assumed to be 0 (the error occurred at top-level).
function Name of function where the error occurred. Will be repeated once for every level in the function call stack.
end Tells the receiving program that a debugger message ends here.

data

Line data.

Tabella E-2. Debugger Error Types

DebuggerPHP 3 Internal
warningE_WARNING
errorE_ERROR
parseE_PARSE
noticeE_NOTICE
core-errorE_CORE_ERROR
core-warningE_CORE_WARNING
unknown(any other)

Esempio E-1. Example Debugger Message


1998-04-05 23:27:400966 lucifer.guardian.no(20481) start: notice
1998-04-05 23:27:400966 lucifer.guardian.no(20481) message: Uninitialized variable
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: (NULL):7
1998-04-05 23:27:400966 lucifer.guardian.no(20481) frames: 1
1998-04-05 23:27:400966 lucifer.guardian.no(20481) function: display
1998-04-05 23:27:400966 lucifer.guardian.no(20481) location: /home/ssb/public_html/test.php3:10
1998-04-05 23:27:400966 lucifer.guardian.no(20481) end: notice
     


Appendice F. Configure options

List of core configure options

Below is a partial list of configure options used by the PHP configure scripts when compiling in Unix-like environments. Most configure options are listed in their appropriate locations on the extension reference pages and not here. For a complete up-to-date list of configure options, run ./configure --help in your PHP source directory after running autoconf (see also the Installation chapter). You may also be interested in reading the GNU configure documentation for information on additional configure options such as --prefix=PREFIX.

Nota: These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Runtime Configuration.


Configure Options in PHP 4

Nota: These options are only used in PHP 4 as of PHP 4.1.0. Some are available in older versions of PHP 4, some even in PHP 3, some only in PHP 4.1.0. If you want to compile an older version, some options will probably not be available.


Misc options

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

Sets how installed files will be laid out. Type is one of PHP (default) or GNU.

--with-pear=DIR

Install PEAR in DIR (default PREFIX/lib/php).

--without-pear

Do not install PEAR.

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-php-streams

Include experimental PHP streams. Do not use unless you are testing the code!

--with-zlib-dir[=DIR]

Define the location of zlib install directory.

--enable-trans-sid

Enable transparent session id propagation. Only valid for PHP 4.1.2 or less. From PHP 4.2.0, trans-sid feature is always compiled.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

Assume the C compiler uses GNU ld [default=no].

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

Try to use only PIC/non-PIC objects [default=use both].

--enable-memory-limit

Compile with memory limit support.

--disable-url-fopen-wrapper

Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP.

--enable-versioning

Export only required symbols. See INSTALL for more information.

--with-imsp[=DIR]

Include IMSp support (DIR is IMSP's include dir and libimsp.a dir). PHP 3 only!

--with-mck[=DIR]

Include Cybercash MCK support. DIR is the cybercash mck build directory, defaults to /usr/src/mck-3.2.0.3-linux for help look in extra/cyberlib. PHP 3 only!

--with-mod-dav=DIR

Include DAV support through Apache's mod_dav, DIR is mod_dav's installation directory (Apache module version only!) PHP 3 only!

--enable-debugger

Compile with remote debugging functions. PHP 3 only!

--enable-versioning

Take advantage of versioning and scoping provided by Solaris 2.x and Linux. PHP 3 only!


PHP options

--enable-maintainer-mode

Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.

--with-config-file-path=PATH

Sets the path in which to look for php.ini, defaults to PREFIX/lib.

--enable-safe-mode

Enable safe mode by default.

--with-exec-dir[=DIR]

Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.

--enable-magic-quotes

Enable magic quotes by default.

--disable-short-tags

Disable the short-form <? start tag by default.


SAPI options

The following list contains the available SAPI&s (Server Application Programming Interface) for PHP.

--with-aolserver=DIR

Specify path to the installed AOLserver.

--with-apxs[=FILE]

Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.

--with-apache[=DIR]

Build a static Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.

--with-mod_charset

Enable transfer tables for mod_charset (Russian Apache).

--with-apxs2[=FILE]

Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.

--with-caudium=DIR

Build PHP as a Pike module for use with Caudium. DIR is the Caudium server dir, with the default value /usr/local/caudium/server.

--disable-cli

Available with PHP 4.3.0. Disable building the CLI version of PHP (this forces --without-pear). More information is available in the section about Using PHP from the command line.

--enable-embed[=TYPE]

Enable building of the embedded SAPI library. TYPE is either shared or static, which defaults to shared. Available with PHP 4.3.0.

--with-fhttpd[=DIR]

Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd. No longer available as of PHP 4.3.0.

--with-isapi=DIR

Build PHP as an ISAPI module for use with Zeus.

--with-nsapi=DIR

Specify path to the installed Netscape/iPlanet/SunONE Webserver.

--with-phttpd=DIR

No information yet.

--with-pi3web=DIR

Build PHP as a module for use with Pi3Web.

--with-roxen=DIR

Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.

--enable-roxen-zts

Build the Roxen module using Zend Thread Safety.

--with-servlet[=DIR]

Include servlet support. DIR is the base install directory for the JSDK. This SAPI requires the java extension must be built as a shared dl.

--with-thttpd=SRCDIR

Build PHP as thttpd module.

--with-tux=MODULEDIR

Build PHP as a TUX module (Linux only).

--with-webjames=SRCDIR

Build PHP as a WebJames module (RISC OS only)

--disable-cgi

Disable building CGI version of PHP. Available with PHP 4.3.0.

--enable-force-cgi-redirect

Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.

--enable-discard-path

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

--with-fastcgi

Build PHP as FastCGI application. No longer available as of PHP 4.3.0, instead you should use --enable-fastcgi.

--enable-fastcgi

If this is enabled, the CGI module will be built with support for FastCGI also. Available since PHP 4.3.0

--disable-path-info-check

If this is disabled, paths such as /info.php/test?a=b will fail to work. Available since PHP 4.3.0. For more information see the Apache Manual.


Appendice G. Impostazioni del php.ini

Elenco delle impostazioni del of php.ini

Questo elenco include tutte le impostazioni del php.ini che possono essere impostate in fase di setup del PHP.

Tabella G-1. Opzioni di configurazione

NomeDefaultModificabileModifiche
allow_call_time_pass_reference"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.0.0.
allow_url_fopen"1"PHP_INI_SYSTEMPHP_INI_ALL in PHP <= 4.3.4. Disponibile da PHP 4.0.4.
always_populate_raw_post_data"0"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.1.0.
apc.cache_by_default"1"PHP_INI_SYSTEM 
apc.enabled"1"PHP_INI_SYSTEM 
apc.filters""PHP_INI_SYSTEM 
apc.gc_ttl"3600"PHP_INI_SYSTEM 
apc.mmap_file_maskNULLPHP_INI_SYSTEM 
apc.num_files_hint"1000"PHP_INI_SYSTEM 
apc.optimization"0"PHP_INI_SYSTEM 
apc.shm_segments"1"PHP_INI_SYSTEM 
apc.shm_size"30"PHP_INI_SYSTEM 
apc.slam_defense"0"PHP_INI_SYSTEM 
apc.ttl"0"PHP_INI_SYSTEM 
apc.user_entries_hint"100"PHP_INI_SYSTEM 
apc.user_ttl"0"PHP_INI_SYSTEM 
apd.dumpdirNULLPHP_INI_ALL 
apd.statement_tracing"0"PHP_INI_ALL 
arg_separator.input"&"PHP_INI_PERDIRDisponibile da PHP 4.0.5.
arg_separator.output"&"PHP_INI_ALLDisponibile da PHP 4.0.5.
asp_tags"0"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.0.0.
assert.active"1"PHP_INI_ALL 
assert.bail"0"PHP_INI_ALL 
assert.callbackNULLPHP_INI_ALL 
assert.quiet_eval"0"PHP_INI_ALL 
assert.warning"1"PHP_INI_ALL 
auto_append_fileNULLPHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
auto_detect_line_endings"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
auto_globals_jit"1"PHP_INI_PERDIRDisponibile da PHP 5.0.0.
auto_prepend_fileNULLPHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
bcmath.scale"0"PHP_INI_ALLDisponibile da PHP 5.0.0.
blenc.key_file"/usr/local/etc/blenckeys"PHP_INI_ALL 
browscapNULLPHP_INI_SYSTEM 
child_terminate"0"PHP_INI_ALLDisponibile da PHP 4.0.5.
com.allow_dcom"0"PHP_INI_SYSTEMDisponibile da PHP 4.0.5.
com.autoregister_casesensitive"1"PHP_INI_ALLPHP_INI_SYSTEM in PHP 4. Disponibile da PHP 4.1.0.
com.autoregister_typelib"0"PHP_INI_ALLPHP_INI_SYSTEM in PHP 4. Disponibile da PHP 4.1.0.
com.autoregister_verbose"0"PHP_INI_ALLPHP_INI_SYSTEM in PHP 4. Disponibile da PHP 4.1.0.
com.code_page""PHP_INI_ALLDisponibile da PHP 5.0.0.
com.typelib_file""PHP_INI_SYSTEMDisponibile da PHP 4.0.5.
crack.default_dictionaryNULLPHP_INI_SYSTEMDisponibile da PHP 4.0.5.
daffodildb.default_host"localhost"PHP_INI_ALL 
daffodildb.default_password"daffodil"PHP_INI_ALL 
daffodildb.default_socketNULLPHP_INI_ALL 
daffodildb.default_user"DAFFODIL"PHP_INI_ALL 
daffodildb.port"3456"PHP_INI_ALL 
date.default_latitude"31.7667"PHP_INI_ALLDisponibile da PHP 5.0.0.
date.default_longitude"35.2333"PHP_INI_ALLDisponibile da PHP 5.0.0.
date.sunrise_zenith"90.83"PHP_INI_ALLDisponibile da PHP 5.0.0.
date.sunset_zenith"90.83"PHP_INI_ALLDisponibile da PHP 5.0.0.
dba.default_handler""PHP_INI_ALLDisponibile da PHP 4.3.3.
dbx.colnames_case"unchanged"PHP_INI_SYSTEMDisponibile da PHP 4.3.0.
default_charset""PHP_INI_ALL 
default_mimetype"text/html"PHP_INI_ALL 
default_socket_timeout"60"PHP_INI_ALLDisponibile da PHP 4.3.0.
define_syslog_variables"0"PHP_INI_ALL 
disable_classes""php.ini onlyDisponibile da PHP 4.3.2.
disable_functions""php.ini onlyDisponibile da PHP 4.0.1.
display_errors"1"PHP_INI_ALL 
display_startup_errors"0"PHP_INI_ALLDisponibile da PHP 4.0.3.
docref_ext""PHP_INI_ALLDisponibile da PHP 4.3.2.
docref_root""PHP_INI_ALLDisponibile da PHP 4.3.0.
doc_rootNULLPHP_INI_SYSTEM 
enable_dl"1"PHP_INI_SYSTEM 
engine"1"PHP_INI_ALLDisponibile da PHP 4.0.5.
error_append_stringNULLPHP_INI_ALL 
error_logNULLPHP_INI_ALL 
error_prepend_stringNULLPHP_INI_ALL 
error_reportingNULLPHP_INI_ALL 
exif.decode_jis_intel"JIS"PHP_INI_ALLDisponibile da PHP 4.3.0.
exif.decode_jis_motorola"JIS"PHP_INI_ALLDisponibile da PHP 4.3.0.
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALLDisponibile da PHP 4.3.0.
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALLDisponibile da PHP 4.3.0.
exif.encode_jis""PHP_INI_ALLDisponibile da PHP 4.3.0.
exif.encode_unicode"ISO-8859-15"PHP_INI_ALLDisponibile da PHP 4.3.0.
expose_php"1"php.ini only 
extension_dir"/path/to/php"PHP_INI_SYSTEM 
fbsql.allow_persistent"1"PHP_INI_SYSTEMDisponibile da PHP 4.2.0.
fbsql.autocommit"1"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.batchsize"1000"PHP_INI_ALLDisponibile da PHP 5-cvs.
fbsql.default_database""PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.default_database_password""PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.default_hostNULLPHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.default_password""PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.default_user"_SYSTEM"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.generate_warnings"0"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.max_connections"128"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.max_links"128"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.max_persistent"-1"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
fbsql.max_results"128"PHP_INI_SYSTEMDisponibile da PHP 4.0.6.
file_uploads"1"PHP_INI_SYSTEMPHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.0.3.
filter.default"notags"PHP_INI_ALL 
highlight.bg"#FFFFFF"PHP_INI_ALL 
highlight.comment"#FF8000"PHP_INI_ALL 
highlight.default"#0000BB"PHP_INI_ALL 
highlight.html"#000000"PHP_INI_ALL 
highlight.keyword"#007700"PHP_INI_ALL 
highlight.string"#DD0000"PHP_INI_ALL 
html_errors"1"PHP_INI_ALLPHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.0.2.
http.allowed_methods"GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, CONNECT, "PHP_INI_ALL 
hyperwave.allow_persistent"0"PHP_INI_SYSTEMDisponibile da PHP 4.3.2.
hyperwave.default_port"418"PHP_INI_ALL 
ibase.allow_persistent"1"PHP_INI_SYSTEM 
ibase.dateformat"%Y-%m-%d"PHP_INI_ALL 
ibase.default_charsetNULLPHP_INI_ALLDisponibile da PHP 5.0.0.
ibase.default_dbNULLPHP_INI_SYSTEMDisponibile da PHP 5.0.0.
ibase.default_passwordNULLPHP_INI_ALL 
ibase.default_userNULLPHP_INI_ALL 
ibase.max_links"-1"PHP_INI_SYSTEM 
ibase.max_persistent"-1"PHP_INI_SYSTEM 
ibase.timeformat"%H:%M:%S"PHP_INI_ALL 
ibase.timestampformat"%Y-%m-%d %H:%M:%S"PHP_INI_ALL 
ibm_db2.binmode"0"PHP_INI_ALL 
iconv.input_encoding"ISO-8859-1"PHP_INI_ALLDisponibile da PHP 4.0.5.
iconv.internal_encoding"ISO-8859-1"PHP_INI_ALLDisponibile da PHP 4.0.5.
iconv.output_encoding"ISO-8859-1"PHP_INI_ALLDisponibile da PHP 4.0.5.
ifx.allow_persistent"1"PHP_INI_SYSTEM 
ifx.blobinfile"1"PHP_INI_ALL 
ifx.byteasvarchar"0"PHP_INI_ALL 
ifx.charasvarchar"0"PHP_INI_ALL 
ifx.default_hostNULLPHP_INI_SYSTEM 
ifx.default_passwordNULLPHP_INI_SYSTEM 
ifx.default_userNULLPHP_INI_SYSTEM 
ifx.max_links"-1"PHP_INI_SYSTEM 
ifx.max_persistent"-1"PHP_INI_SYSTEM 
ifx.nullformat"0"PHP_INI_ALL 
ifx.textasvarchar"0"PHP_INI_ALL 
ignore_repeated_errors"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
ignore_repeated_source"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
ignore_user_abort"0"PHP_INI_ALL 
implicit_flush"0"PHP_INI_ALLPHP_INI_PERDIR in PHP <= 4.2.3.
include_path".;/path/to/php/pear"PHP_INI_ALL 
ingres.allow_persistent"1"PHP_INI_SYSTEMDisponibile da PHP 4.0.2.
ingres.default_databaseNULLPHP_INI_ALLDisponibile da PHP 4.0.2.
ingres.default_passwordNULLPHP_INI_ALLDisponibile da PHP 4.0.2.
ingres.default_userNULLPHP_INI_ALLDisponibile da PHP 4.0.2.
ingres.max_links"-1"PHP_INI_SYSTEMDisponibile da PHP 4.0.2.
ingres.max_persistent"-1"PHP_INI_SYSTEMDisponibile da PHP 4.0.2.
ircg.control_user"nobody"PHP_INI_ALLDisponibile da PHP 5.0.0.
ircg.keep_alive_interval"60"PHP_INI_ALLDisponibile da PHP 5.0.0.
ircg.max_format_message_sets"12"PHP_INI_ALLDisponibile da PHP 5.0.0.
ircg.shared_mem_size"6000000"PHP_INI_ALLDisponibile da PHP 5.0.0.
ircg.work_dir"/tmp/ircg"PHP_INI_ALLDisponibile da PHP 5.0.0.
last_modified"0"PHP_INI_ALLDisponibile da PHP 4.0.5.
ldap.max_links"-1"PHP_INI_SYSTEM 
log_errors"0"PHP_INI_ALL 
log_errors_max_len"1024"PHP_INI_ALLDisponibile da PHP 4.3.0.
magic_quotes_gpc"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
magic_quotes_runtime"0"PHP_INI_ALL 
magic_quotes_sybase"0"PHP_INI_ALL 
mail.force_extra_parametersNULLPHP_INI_PERDIRDisponibile da PHP 5.0.0.
mailparse.def_charset"us-ascii"PHP_INI_ALLDisponibile da PHP 4.1.0.
maxdb.default_dbNULLPHP_INI_ALL 
maxdb.default_hostNULLPHP_INI_ALL 
maxdb.default_pwNULLPHP_INI_ALL 
maxdb.default_userNULLPHP_INI_ALL 
maxdb.long_readlen"200"PHP_INI_ALL 
max_execution_time"30"PHP_INI_ALL 
max_input_time"-1"PHP_INI_PERDIRDisponibile da PHP 4.3.0.
mbstring.detect_orderNULLPHP_INI_ALLDisponibile da PHP 4.0.6.
mbstring.encoding_translation"0"PHP_INI_PERDIRDisponibile da PHP 4.3.0.
mbstring.func_overload"0"PHP_INI_PERDIRPHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.2.0.
mbstring.http_input"pass"PHP_INI_ALLDisponibile da PHP 4.0.6.
mbstring.http_output"pass"PHP_INI_ALLDisponibile da PHP 4.0.6.
mbstring.internal_encodingNULLPHP_INI_ALLDisponibile da PHP 4.0.6.
mbstring.language"neutral"PHP_INI_PERDIRDisponibile da PHP 4.3.0.
mbstring.script_encodingNULLPHP_INI_ALLDisponibile da PHP 4.3.0.
mbstring.substitute_characterNULLPHP_INI_ALLDisponibile da PHP 4.0.6.
mcrypt.algorithms_dirNULLPHP_INI_ALLDisponibile da PHP 4.0.2.
mcrypt.modes_dirNULLPHP_INI_ALLDisponibile da PHP 4.0.2.
memory_limit"8M"PHP_INI_ALL 
mime_magic.debug"0"PHP_INI_SYSTEMDisponibile da PHP 5.0.0.
mime_magic.magicfile"/path/to/php/magic.mime"PHP_INI_SYSTEMDisponibile da PHP 4.3.0.
mssql.allow_persistent"1"PHP_INI_SYSTEM 
mssql.batchsize"0"PHP_INI_ALLDisponibile da PHP 4.0.4.
mssql.compatability_mode"0"PHP_INI_ALL 
mssql.connect_timeout"5"PHP_INI_ALL 
mssql.datetimeconvert"1"PHP_INI_ALLDisponibile da PHP 4.2.0.
mssql.max_links"-1"PHP_INI_SYSTEM 
mssql.max_persistent"-1"PHP_INI_SYSTEM 
mssql.max_procs"25"PHP_INI_ALLDisponibile da PHP 4.3.0.
mssql.min_error_severity"10"PHP_INI_ALL 
mssql.min_message_severity"10"PHP_INI_ALL 
mssql.secure_connection"0"PHP_INI_SYSTEMDisponibile da PHP 4.3.0.
mssql.textlimit"-1"PHP_INI_ALL 
mssql.textsize"-1"PHP_INI_ALL 
mssql.timeout"60"PHP_INI_ALLDisponibile da PHP 4.1.0.
mysql.allow_persistent"1"PHP_INI_SYSTEM 
mysql.connect_timeout"60"PHP_INI_ALLPHP_INI_SYSTEM in PHP <= 4.3.2. Disponibile da PHP 4.3.0.
mysql.default_hostNULLPHP_INI_ALL 
mysql.default_passwordNULLPHP_INI_ALL 
mysql.default_portNULLPHP_INI_ALL 
mysql.default_socketNULLPHP_INI_ALLDisponibile da PHP 4.0.1.
mysql.default_userNULLPHP_INI_ALL 
mysql.max_links"-1"PHP_INI_SYSTEM 
mysql.max_persistent"-1"PHP_INI_SYSTEM 
mysql.trace_mode"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
mysqli.default_hostNULLPHP_INI_ALLDisponibile da PHP 5.0.0.
mysqli.default_port"3306"PHP_INI_ALLDisponibile da PHP 5.0.0.
mysqli.default_pwNULLPHP_INI_ALLDisponibile da PHP 5.0.0.
mysqli.default_socketNULLPHP_INI_ALLDisponibile da PHP 5.0.0.
mysqli.default_userNULLPHP_INI_ALLDisponibile da PHP 5.0.0.
mysqli.max_links"-1"PHP_INI_SYSTEMDisponibile da PHP 5.0.0.
mysqli.reconnect"0"PHP_INI_SYSTEMDisponibile da PHP 5.0.0.
namazu.debugmode"0"PHP_INI_ALL 
namazu.langNULLPHP_INI_ALL 
namazu.loggingmode"0"PHP_INI_ALL 
namazu.sortmethodNULLPHP_INI_ALL 
namazu.sortorderNULLPHP_INI_ALL 
nsapi.read_timeout"60"PHP_INI_ALLDisponibile da PHP 4.3.3.
odbc.allow_persistent"1"PHP_INI_SYSTEM 
odbc.check_persistent"1"PHP_INI_SYSTEM 
odbc.defaultbinmode"1"PHP_INI_ALL 
odbc.defaultlrl"4096"PHP_INI_ALL 
odbc.default_dbNULLPHP_INI_ALL 
odbc.default_pwNULLPHP_INI_ALL 
odbc.default_userNULLPHP_INI_ALL 
odbc.max_links"-1"PHP_INI_SYSTEM 
odbc.max_persistent"-1"PHP_INI_SYSTEM 
opendirectory.max_refs"-1"PHP_INI_ALL 
opendirectory.separator"/"PHP_INI_ALL 
open_basedirNULLPHP_INI_SYSTEM 
output_buffering"0"PHP_INI_PERDIR 
output_handlerNULLPHP_INI_PERDIRDisponibile da PHP 4.0.4.
pfpro.defaulthost"test-payflow.verisign.com"PHP_INI_ALLDisponibile da PHP 4.0.2.
pfpro.defaultport"443"PHP_INI_ALLDisponibile da PHP 4.0.2.
pfpro.defaulttimeout"30"PHP_INI_ALLDisponibile da PHP 4.0.2.
pfpro.proxyaddress""PHP_INI_ALLDisponibile da PHP 4.0.2.
pfpro.proxylogon""PHP_INI_ALLDisponibile da PHP 4.0.2.
pfpro.proxypassword""PHP_INI_ALLDisponibile da PHP 4.0.2.
pfpro.proxyport""PHP_INI_ALLDisponibile da PHP 4.0.2.
pgsql.allow_persistent"1"PHP_INI_SYSTEM 
pgsql.auto_reset_persistent"0"PHP_INI_SYSTEMDisponibile da PHP 4.2.0.
pgsql.ignore_notice"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
pgsql.log_notice"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
pgsql.max_links"-1"PHP_INI_SYSTEM 
pgsql.max_persistent"-1"PHP_INI_SYSTEM 
post_max_size"8M"PHP_INI_PERDIRPHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.0.3.
precision"14"PHP_INI_ALL 
printer.default_printer""PHP_INI_ALL 
realpath_cache_size"16K"PHP_INI_SYSTEMDisponibile da PHP 5-cvs.
realpath_cache_ttl"120"PHP_INI_SYSTEMDisponibile da PHP 5-cvs.
register_argc_argv"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
register_globals"0"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
register_long_arrays"1"PHP_INI_PERDIRDisponibile da PHP 5.0.0.
report_memleaks"1"PHP_INI_ALLDisponibile da PHP 4.3.0.
report_zend_debug"1"PHP_INI_ALLDisponibile da PHP 5.0.0.
safe_mode"0"PHP_INI_SYSTEM 
safe_mode_allowed_env_vars"PHP_"PHP_INI_SYSTEM 
safe_mode_exec_dir""PHP_INI_SYSTEM 
safe_mode_gid"0"PHP_INI_SYSTEMDisponibile da PHP 4.1.0.
safe_mode_include_dirNULLPHP_INI_SYSTEMDisponibile da PHP 4.1.0.
safe_mode_protected_env_vars"LD_LIBRARY_PATH"PHP_INI_SYSTEM 
sendmail_fromNULLPHP_INI_ALL 
sendmail_pathNULLPHP_INI_SYSTEM 
serialize_precision"100"PHP_INI_ALLDisponibile da PHP 4.3.2.
session.auto_start"0"PHP_INI_ALL 
session.bug_compat_42"1"PHP_INI_ALLDisponibile da PHP 4.3.0.
session.bug_compat_warn"1"PHP_INI_ALLDisponibile da PHP 4.3.0.
session.cache_expire"180"PHP_INI_ALL 
session.cache_limiter"nocache"PHP_INI_ALL 
session.cookie_domain""PHP_INI_ALL 
session.cookie_lifetime"0"PHP_INI_ALL 
session.cookie_path"/"PHP_INI_ALL 
session.cookie_secure""PHP_INI_ALLDisponibile da PHP 4.0.4.
session.entropy_file""PHP_INI_ALL 
session.entropy_length"0"PHP_INI_ALL 
session.gc_divisor"100"PHP_INI_ALLDisponibile da PHP 4.3.2.
session.gc_maxlifetime"1440"PHP_INI_ALL 
session.gc_probability"1"PHP_INI_ALL 
session.hash_bits_per_character"4"PHP_INI_ALLDisponibile da PHP 5.0.0.
session.hash_function"0"PHP_INI_ALLDisponibile da PHP 5.0.0.
session.name"PHPSESSID"PHP_INI_ALL 
session.referer_check""PHP_INI_ALL 
session.save_handler"files"PHP_INI_ALL 
session.save_path""PHP_INI_ALL 
session.serialize_handler"php"PHP_INI_ALL 
session.use_cookies"1"PHP_INI_ALL 
session.use_only_cookies"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
session.use_trans_sid"0"PHP_INI_ALLPHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Disponibile da PHP 4.0.3.
session_pgsql.create_table"1"PHP_INI_SYSTEM 
session_pgsql.db"host=localhost dbname=php_session user=nobody"PHP_INI_SYSTEM 
session_pgsql.disable"0"PHP_INI_SYSTEM 
session_pgsql.failover_mode"0"PHP_INI_SYSTEM 
session_pgsql.gc_interval"3600"PHP_INI_SYSTEM 
session_pgsql.keep_expired"0"PHP_INI_SYSTEM 
session_pgsql.sem_file_name"/tmp/php_session_pgsql"PHP_INI_SYSTEM 
session_pgsql.serializable"0"PHP_INI_SYSTEM 
session_pgsql.short_circuit"0"PHP_INI_SYSTEM 
session_pgsql.use_app_vars"0"PHP_INI_SYSTEM 
session_pgsql.vacuum_interval"21600"PHP_INI_SYSTEM 
short_open_tag"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.0.0.
simple_cvs.authMethod"0"PHP_INI_ALL 
simple_cvs.compressionLevel"0"PHP_INI_ALL 
simple_cvs.cvsRoot"0"PHP_INI_ALL 
simple_cvs.host"0"PHP_INI_ALL 
simple_cvs.moduleName"0"PHP_INI_ALL 
simple_cvs.userName"0"PHP_INI_ALL 
simple_cvs.workingDir"0"PHP_INI_ALL 
SMTP"localhost"PHP_INI_ALL 
smtp_port"25"PHP_INI_ALLDisponibile da PHP 4.3.0.
soap.wsdl_cache_dir"/tmp"PHP_INI_ALLDisponibile da PHP 5.0.0.
soap.wsdl_cache_enabled"1"PHP_INI_ALLDisponibile da PHP 5.0.0.
soap.wsdl_cache_ttl"86400"PHP_INI_ALLDisponibile da PHP 5.0.0.
sql.safe_mode"0"PHP_INI_SYSTEM 
sqlite.assoc_case"0"PHP_INI_ALLDisponibile da PHP 5.0.0.
sybct.allow_persistent"1"PHP_INI_SYSTEMDisponibile da PHP 4.0.4.
sybct.deadlock_retry_count"0"PHP_INI_ALLDisponibile da PHP 4.3.0.
sybct.hostnameNULLPHP_INI_ALLDisponibile da PHP 4.0.4.
sybct.login_timeout"-1"PHP_INI_ALLDisponibile da PHP 4.3.5.
sybct.max_links"-1"PHP_INI_SYSTEMDisponibile da PHP 4.0.4.
sybct.max_persistent"-1"PHP_INI_SYSTEMDisponibile da PHP 4.0.4.
sybct.min_client_severity"10"PHP_INI_ALLDisponibile da PHP 4.0.4.
sybct.min_server_severity"10"PHP_INI_ALLDisponibile da PHP 4.0.4.
tidy.clean_output"0"PHP_INI_PERDIRDisponibile da PHP 5.0.0.
tidy.default_config""PHP_INI_SYSTEMDisponibile da PHP 5.0.0.
track_errors"0"PHP_INI_ALL 
unserialize_callback_funcNULLPHP_INI_ALLDisponibile da PHP 4.2.0.
upload_max_filesize"2M"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
upload_tmp_dirNULLPHP_INI_SYSTEM 
url_rewriter.tags"a=href,area=href,frame=src,form=,fieldset="PHP_INI_ALLDisponibile da PHP 4.0.4.
user_agentNULLPHP_INI_ALLDisponibile da PHP 4.3.0.
user_dirNULLPHP_INI_SYSTEM 
valkyrie.auto_validate"0"PHP_INI_ALL 
valkyrie.config_pathNULLPHP_INI_ALL 
variables_order"EGPCS"PHP_INI_ALL 
xbithack"0"PHP_INI_ALLDisponibile da PHP 4.0.5.
xmlrpc_errors"0"PHP_INI_SYSTEMDisponibile da PHP 4.1.0.
xmlrpc_error_number"0"PHP_INI_ALLDisponibile da PHP 4.1.0.
xmms.path"/usr/bin/xmms"PHP_INI_ALL 
xmms.session"0"PHP_INI_ALL 
y2k_compliance"1"PHP_INI_ALL 
yaz.keepalive"120"PHP_INI_ALL 
yaz.log_fileNULLPHP_INI_ALLDisponibile da PHP 4.3.0.
yaz.log_maskNULLPHP_INI_ALL 
yaz.max_links"100"PHP_INI_ALLDisponibile da PHP 4.3.0.
zend.ze1_compatibility_mode"0"PHP_INI_ALLDisponibile da PHP 5.0.0.
zlib.output_compression"0"PHP_INI_ALLDisponibile da PHP 4.0.5.
zlib.output_compression_level"-1"PHP_INI_ALLDisponibile da PHP 4.3.0.
zlib.output_handler""PHP_INI_ALLDisponibile da PHP 4.3.0.

Tabella G-2. Definizione delle costanti PHP_INI_*

CostanteValoreSignificato
PHP_INI_USER1Parametro che può essere impostato nello script utente o nelregistry di Winwos
PHP_INI_PERDIR2Parametro che può essere impostato in php.ini, .htaccess oppure in httpd.conf
PHP_INI_SYSTEM4Parametro che può essere impostato in php.ini o httpd.conf
PHP_INI_ALL7Parametro che può essere impostato ovunque


Descrizione dei parametri core di php.ini

Questo elenco contiene i parametri 'core' del php.ini che sono utilizzati per configurare il PHP. Le impostazioni gestite dai vari moduli sono elencate e dettagliate nelle pagine di documentazione dei rispettivi moduli; informazioni sui parametri per le sessioni, ad esempio, possono essere troavte nelle pagine delle sessioni.


Httpd Options

Tabella G-3. Httpd Options

NomeDefaultModificabileVariazioni
async_send"0"PHP_INI_ALL 


Parametri del linguaggio

Tabella G-4. Parametri del linguaggio e configurazioni varie

NomeDefaultModificabileVariazioni
short_open_tag"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.0.0.
asp_tags"0"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.0.0.
precision"14"PHP_INI_ALL 
y2k_compliance"1"PHP_INI_ALL 
allow_call_time_pass_reference"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.0.0.
expose_php"1"php.ini only 
zend.ze1_compatibility_mode"0"PHP_INI_ALLDisponibile da PHP 5.0.0.

Breve descrizione dei parametri di configurazione.

short_open_tag boolean

Indica se abilitare o meno la forma abbreviata dei tag di apertura del PHP <? ?>). Se si desidera utilizzare il PHP in combinazione con l'XML, occorre disabilitare questa opzione per potere abilitare la riga <?xml ?>. In alternativa occorre stampare il testo con il PHP, ad esempio: <?php echo '<?xml version="1.0"'; ?>. Inoltre, se disabilitato, occorre utilizzare la versione lunga dei tag di apertura del PHP (<?php ?>).

Nota: Questo parametro influisce anche su <?=, la quale è identica a <? echo. L'uso di questa abbreviazione richiede l'abilitazione di short_open_tag.

asp_tags boolean

Abilita l'uso dei tags tipo ASP <% %> in aggiunta agli usuali <?php ?>. Questi includono la scorciatoia per scrivere il valore delle variabili <%= $value %>. Per maggiori informazioni vedere Escaping from HTML.

Nota: Il supporto per i tag stile ASP è sttao aggiunto nella versione 3.0.4.

precision integer

Il numero di cifre significative usato nella visualizzazione dei numeri in virgola mobile.

y2k_compliance boolean

Forza la compatibilità con l'anno 2000 (ciò causa problemi con browser non compatibili)

allow_call_time_pass_reference boolean

Abilita o meno la possibilità di forzare gli argomenti delle funzioni ad essere passati per riferimento. Questo parametro è deprecato e potrebbe non essere più supportato nelle versioni future di PHP/Zend. Si incoraggia il metodo di specificare quale parametro debba essere passato per riferimento al momento della dichiarazione della funzione. Si suggerisce di impostare l'opzione a off per essere certi che lo script funzioni correttamente con questa impostazione, in modo da predisporsi ad eventuali modifiche future del linguaggio (si riceverà un warning ogni volta che si utilizza questa opzione e i valori saranno passati per valore anzichè per riferimento).

Passare i valori per riferimento al momento della chiamata della funzione viene sconsigliato per motivi di chiarezza del codice. La funzione può modificare il parametro in modo non previsto se non indica questo come passato per riferimento. Per evitare effetti secondari inattesi, è meglio indicare soltanto al momento della dichiarazione della funzione quali parametri saranno passati per riferimento.

Vedere anche Spiegazioni sui riferimenti.

expose_php boolean

Indica se il PHP deve indicare il fatto che è installato su un server (ad esempi9o aggiungendo una propria sigla all'intestazione del server web). Non vi sono insiti problemi di sicurezza, ma ciò indica che si sta utilizzando il PHP su quel server.

zend.ze1_compatibility_mode boolean

Abilita la compatibilità con lo Zend Engine 1 (PHP 4). Ciò influisce sulle funzioni di clonazione, di cast e di confronto degli oggetti.

Vedere anche la sezione intitolata Migrazione da PHP 4 a PHP 5.


Limiti per le risorse

Tabella G-5. Limiti per le risorse

NomeDefaultModificabileVariazioni
memory_limit"8M"PHP_INI_ALL 

Breve descrizione dei parametri di configurazione.

memory_limit integer

Questo parametro imposta la dimensione massima in byte di memoria occupabile dallo script. Questo aiuta a impedire che script scritti male utilizzino tutta la memoria del server. Per potere utilizzare questo parametro occorre abilitarlo al momento della compila. Pertanto occorrerà includere nella configurazione la linea: --enable-memory-limit. Si noti che occorre impostare il parametro a -1 se non si desidera impostare limiti di memoria.

Dal PHP 4.3.2, e quando è abilitato il parametro memory_limit, il PHP rende disponibile la funzione memory_get_usage().

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

See also: max_execution_time.


Gestione dei dati

Tabella G-6. Parametri di configurazione per la gestione dei dati

NomeDefaultModificabileVariazioni
track_vars"On"PHP_INI_?? 
arg_separator.output"&"PHP_INI_ALLDisponibile da PHP 4.0.5.
arg_separator.input"&"PHP_INI_PERDIRDisponibile da PHP 4.0.5.
variables_order"EGPCS"PHP_INI_ALL 
auto_globals_jit"1"PHP_INI_PERDIRDisponibile da PHP 5.0.0.
register_globals"0"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
register_argc_argv"1"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
register_long_arrays"1"PHP_INI_PERDIRDisponibile da PHP 5.0.0.
post_max_size"8M"PHP_INI_PERDIRPHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.0.3.
gpc_order"GPC"PHP_INI_ALL 
auto_prepend_fileNULLPHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
auto_append_fileNULLPHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.
default_mimetype"text/html"PHP_INI_ALL 
default_charset""PHP_INI_ALL 
always_populate_raw_post_data"0"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.1.0.
allow_webdav_methods"0"PHP_INI_PERDIR 

Breve descrizione dei parametri di configurazione.

track_vars boolean

Se abilitato, le variabili Environment, GET, POST, Cookie, e Server sono recuperabili nelle rispettive matrici $_ENV, $_GET, $_POST, $_COOKIE e $_SERVER.

Nota: dal PHP 4.0.3, track_vars è sempre impostato a on.

arg_separator.output string

Il separatore degli argomenti utilizzato nelle URL genarate dal PHP.

arg_separator.input string

Lista dei separatori utilizzati dal PHP per la siddivisione dell'URL di input nelle veriabili.

Nota: Qualsiasi carattere inserito in questo parametro sarà considerato un separatore!

variables_order string

Imposta l'ordine di parsing delle variabili EGPCS (Enviroment, GET, POST, Cookie e Server). Per default l'impostazione di questo parametro è "EGPCS". Impostare questo a "GP", ad esempio, per ignorare completamente le variabili di ambiente, i cookie e le variabili del server, e per sovrascrivere qualsiasi variabile GET con una eventuale variabile POST con lo stesso nome.

Vedere anche register_globals.

auto_globals_jit boolean

Quando abilitato, le varaibili SERVER ed ENV sono create al momento del primo utilizzo (Just In Time) invece che all'avvio dello script. Se queste variabili non sono utilizzate dallo script, impostanto questo parametro ad on si ha un beneficio in termini di performance.

I parametri di PHP register_globals, register_long_arrays e register_argc_argv devono essere disabilitati affinché questa impostazione abbia effetto.

register_globals boolean

Indica se registrare o meno le variabili EGPCS (Environment, GET, POST, Cookie, Server) come variabili globali.

Dal PHP 4.2.0, questo parametro è impostato per default a off.

Guardare il capitolo della sicurezza riguardante l'uso di register_globals per maggiori informazioni.

Si ricorda che register_globals non può essere impostato a runtime da (ini_set()). In alternativa, se permesso dal proprio host, si può utilizzare .htaccess. Un esempio di riga .htaccess: php_flag register_globals off.

Nota: Il parametro register_globals è influenzato da variables_order directive.

register_argc_argv boolean

Indica al PHP se dichiarare le variabili argv & argc (che contengono le informazioni GET).

Vedere anche command line. Infine, questo parametro è stato introdotto in PHP 4.0.0 ed era sempre impostato a"on" nelle versioni precedenti.

register_long_arrays boolean

Indica al PHP se registrare o meno le deprecate variabili lunghe $HTTP_*_VARS, vedere variabili predefinite. Quando viene impostato ad On (default), vengono definite le variabili lunghe, tipo $HTTP_GET_VARS, del PHP. Se non si utilizzano, si consiglia di impostare il parametro ad off per motivi di performance. Al posto di queste, utilizzare le matrici $_GET.

Questa impostazione è disponibile dal PHP 5.0.0.

post_max_size integer

Imposta la dimensione massima dei dati post. Questa impostazione influenza anche gli upload dei file. Per permettere upload di file di grandi dimensioni, il valore impostato deve essere maggiore di upload_max_filesize.

Anche il limite di memoria, memory_limit, se abilitato, può limitare gli upload di file. In termini generali memory_limit dovrebbe essere maggiore di post_max_size.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

Se la dimensione dei dati post è maggiore di post_max_size, le variabili superglobale $_POST e $_FILES sono vuote. Questo può essere rilevato in diversi modi, ad esempio passando una variabile $_GET allo script che processa i dati, tipo <form action="edit.php?processed=1">, e verificare se $_GET['processed'] è impostata.

gpc_order string

Imposta l'ordine di parsing delle variabili GET/POST/COOKIE. l'impostazione di default per questo parametro è "GPC". Impostare questo a "GP", ad esempio, farà ignorare i cookie al PHP e farà sovrascrivere qualsiasi variabile GET dalla eventuale omonima variabile POST.

Nota: Questo parametro non è disponibil in PHP 4. Al suo posto utilizzare variables_order.

auto_prepend_file string

Indica il nome del file che deve essere parsato prima del file principale. Quetso file viene incluso come se fosse chiamato dalla funzione include(), pertanto si utilizza il parametro include_path.

Il valore speciale none disabilita la funzione.

auto_append_file string

Specifica il file che deve essere parsato in automatico dopo il file principale. Il file è incluso come se fosse chiamato dalla funzione include() pertanto si utilizza il parametro include_path.

The special value none disables auto-appending.

Nota: Se lo script termina con exit(), l'auto-accodamento non viene eseguito.

default_mimetype string

default_charset string

Dalla versione 4.0b4, il PHP invia, per default, la codifica del carattere nell'intestazione Content-type:. Per disabilitare questo invio, lasciare vuoto il parametro.

always_populate_raw_post_data boolean

Valorizza sempre la variabile $HTTP_RAW_POST_DATA.

allow_webdav_methods boolean

Permette la gestione delle richieste http di WebDAV all'interno di script PHP (ad esempio. PROPFIND, PROPPATCH, MOVE, COPY, etc.). Questo parametro non esisteva prima di PHP 4.3.2. Se si vuole ricevere i dati post di queste richieste, occorre impostare anche always_populate_raw_post_data.

Vedere anche: magic_quotes_gpc, magic_quotes_runtime e magic_quotes_sybase.


Percorsi e Directory

Tabella G-7. Parametri di configurazione per percorsi e directory

NomeDefaultModificabileLog delle variazioni
include_path".;/path/to/php/pear"PHP_INI_ALL 
doc_rootNULLPHP_INI_SYSTEM 
user_dirNULLPHP_INI_SYSTEM 
extension_dir"/path/to/php"PHP_INI_SYSTEM 
cgi.fix_pathinfo"0"PHP_INI_SYSTEM 
cgi.force_redirect"1"PHP_INI_SYSTEM 
cgi.redirect_status_env""PHP_INI_SYSTEM 
fastcgi.impersonate"0"PHP_INI_SYSTEM 
cgi.rfc2616_headers"0"PHP_INI_SYSTEM 

Breve descrizione dei parametri di configurazione.

include_path string

Elenco di directory in cui le funzioni require(), include() e fopen_with_path() cercheranno i files. Il formato è tipo la variabile d'ambiente PATH: una lista di directory separate da due punti in Unix, punto e virgola in Widnows.

Esempio G-1. Unix include_path

include_path=".:/php/includes"

Esempio G-2. Windows include_path

include_path=".;c:\php\includes"

L'uso di . nel percorso di include indica, negli include relativi, la directory corrente.

doc_root string

La directory radice (root directory) del PHP sul server. Utilizzata solo se compilata. Se il PHP è configurato con il modalità sicura, ignorerà tutti i file al di fuori di questa directory. Se il PHP non è compilato con il parametro FORCE_REDIRECT, si dovrebbe impostare doc_root se si utilizza il PHP come CGI in qualsiasi web server (oltre che IIS). In alternativa utilizzare il seguente parametro cgi.force_redirect.

user_dir string

Il nome di base della directory utilizzata come home directory degli utenti per i file PHP, ad esempio public_html .

extension_dir string

Directory in cui il PHP cerca i moduli caricabili dinamicamente. Vedere anche: enable_dl, e dl().

extension string

Quale modulo dinamico caricare quando il PHP parte.

cgi.fix_pathinfo boolean

Fornisce il reale PATH_INFO/PATH_TRANSLATED per il CGI. Il precedente comportamento del PHP era di impostare PATH_TRANSLATED a SCRIPT_FILENAME, non curarsi di quale sia PATH_INFO. Per maggiori dettagli su PATH_INFO, vedere le specifiche cgi. Impostare il parametro a 1, si forza il PHP CGI a correggere il percorso in modo conforme alle specifiche. Impostare il parametro a 0 si forza il PHP a comportarsi come solito. Il valore di default è zero. Si dovrebbe correggere gli script affinchè utilizzino SCRIPT_FILENAME piuttosto che PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect è necessario per garantire maggiore sicurezza al PHP quando gira come CGI in diversi web server. Non impostando il parametro, il PHP lo imposta a on per default. Può essere impostato ad off a proprio rischio.

Nota: Nota per gli utenti di Windows: si può tranquillamente impostare questo parametro a off con IIS, infatti è obbligatorio. Anche con OmniHTTPD o Xitami occorre impostare il parametro a off.

cgi.redirect_status_env string

Se cgi.force_redirect è impostato ad on, e non si utilizza i web server Apache o Netscape (iPlanet), può essere necessario impostare il nome di una variabile di ambiente the il PHP verificherà per sapere se può continuare l'esecuzione.

Nota: L'impostazione di questa variabile può portare a problemi di sicurezza, fare attenzione a quello che si fa.

fastcgi.impersonate string

FastCGI con IIS (su OS basati su WINNT) offre la possibilità di attivare il contesto di sicurezza del client chiamante. Questo permette a IIS di definire un contesto di sicurezza in cui fare girare la richiesta. Attualmente mod_fastcgi di Apache non supporta questa caratteristica (17/03/2002). Impostare a 1 se si utilizza IIS. Il default è zero.

cgi.rfc2616_headers int

Indica al PHP quale tipo di intesazione utilizzare quando si invia risposte HTTP. Se impostato a 0, il PHP invia una intestazione Status:, che è supportata da Apache ed altri server web. Quando il parametro è impostato a 1, il PHP invia una intestazione conforme alle specifiche indicate in RFC 2616. Lasciare il parametro a 0 a meno che non si sappia cosa si sta facendo.


File Uploads

Tabella G-8. File Uploads Configuration Options

NomeDefaultModificabileVariazioni
file_uploads"1"PHP_INI_SYSTEMPHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.0.3.
upload_tmp_dirNULLPHP_INI_SYSTEM 
upload_max_filesize"2M"PHP_INI_PERDIRPHP_INI_ALL in PHP <= 4.2.3.

Breve descrizione dei parametri di configurazione.

file_uploads boolean

Indica se abilitare o meno gli upload di file. Vedere anche i parametri upload_max_filesize, upload_tmp_dir e post_max_size.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.

upload_tmp_dir string

Directory temporanea utilizzata per il transito dei file durante l'upload. Deve avere i permessi di scrittura per gli utenti utilizzati dal PHP per girare. Se non indicata il PHP utilizzerà il default di sistema.

upload_max_filesize integer

La dimensione massima di un file inviato.

When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.


General SQL

Tabella G-9. Parametri di configurazione generali per SQL

NomeDefaultModificabileVariazioni
sql.safe_mode"0"PHP_INI_SYSTEM 

Breve descrizione dei parametri di configurazione.

sql.safe_mode boolean


Debugger Configuration Directives

Attenzione

Soltanto il PHP 3 possiede un debugger di default, per maggiori dettagli vedere Appendice E.

debugger.host string

Nome DNS oppure indirizzo IP utilizzato dal debugger.

debugger.port string

Numero di porta utilizzato dal debugger.

debugger.enabled boolean

Indica se abilitare o meno il debugger.


Appendice H. List of Supported Timezones


List of timezones in the group Africa

Tabella H-1. Africa

Africa/AbidjanAfrica/AccraAfrica/Addis_AbabaAfrica/AlgiersAfrica/Asmera
Africa/BamakoAfrica/BanguiAfrica/BanjulAfrica/BissauAfrica/Blantyre
Africa/BrazzavilleAfrica/BujumburaAfrica/CairoAfrica/CasablancaAfrica/Ceuta
Africa/ConakryAfrica/DakarAfrica/Dar_es_SalaamAfrica/DjiboutiAfrica/Douala
Africa/El_AaiunAfrica/FreetownAfrica/GaboroneAfrica/HarareAfrica/Johannesburg
Africa/KampalaAfrica/KhartoumAfrica/KigaliAfrica/KinshasaAfrica/Lagos
Africa/LibrevilleAfrica/LomeAfrica/LuandaAfrica/LubumbashiAfrica/Lusaka
Africa/MalaboAfrica/MaputoAfrica/MaseruAfrica/MbabaneAfrica/Mogadishu
Africa/MonroviaAfrica/NairobiAfrica/NdjamenaAfrica/NiameyAfrica/Nouakchott
Africa/OuagadougouAfrica/Porto-NovoAfrica/Sao_TomeAfrica/TimbuktuAfrica/Tripoli
Africa/TunisAfrica/Windhoek   

List of timezones in the group America

Tabella H-2. America

America/AdakAmerica/AnchorageAmerica/AnguillaAmerica/AntiguaAmerica/Araguaina
America/Argentina/Buenos_AiresAmerica/Argentina/CatamarcaAmerica/Argentina/ComodRivadaviaAmerica/Argentina/CordobaAmerica/Argentina/Jujuy
America/Argentina/La_RiojaAmerica/Argentina/MendozaAmerica/Argentina/Rio_GallegosAmerica/Argentina/San_JuanAmerica/Argentina/Tucuman
America/Argentina/UshuaiaAmerica/ArubaAmerica/AsuncionAmerica/AtkaAmerica/Bahia
America/BarbadosAmerica/BelemAmerica/BelizeAmerica/Boa_VistaAmerica/Bogota
America/BoiseAmerica/Buenos_AiresAmerica/Cambridge_BayAmerica/Campo_GrandeAmerica/Cancun
America/CaracasAmerica/CatamarcaAmerica/CayenneAmerica/CaymanAmerica/Chicago
America/ChihuahuaAmerica/Coral_HarbourAmerica/CordobaAmerica/Costa_RicaAmerica/Cuiaba
America/CuracaoAmerica/DanmarkshavnAmerica/DawsonAmerica/Dawson_CreekAmerica/Denver
America/DetroitAmerica/DominicaAmerica/EdmontonAmerica/EirunepeAmerica/El_Salvador
America/EnsenadaAmerica/Fort_WayneAmerica/FortalezaAmerica/Glace_BayAmerica/Godthab
America/Goose_BayAmerica/Grand_TurkAmerica/GrenadaAmerica/GuadeloupeAmerica/Guatemala
America/GuayaquilAmerica/GuyanaAmerica/HalifaxAmerica/HavanaAmerica/Hermosillo
America/Indiana/IndianapolisAmerica/Indiana/KnoxAmerica/Indiana/MarengoAmerica/Indiana/VevayAmerica/Indianapolis
America/InuvikAmerica/IqaluitAmerica/JamaicaAmerica/JujuyAmerica/Juneau
America/Kentucky/LouisvilleAmerica/Kentucky/MonticelloAmerica/Knox_INAmerica/La_PazAmerica/Lima
America/Los_AngelesAmerica/LouisvilleAmerica/MaceioAmerica/ManaguaAmerica/Manaus
America/MartiniqueAmerica/MazatlanAmerica/MendozaAmerica/MenomineeAmerica/Merida
America/Mexico_CityAmerica/MiquelonAmerica/MonterreyAmerica/MontevideoAmerica/Montreal
America/MontserratAmerica/NassauAmerica/New_YorkAmerica/NipigonAmerica/Nome
America/NoronhaAmerica/North_Dakota/CenterAmerica/PanamaAmerica/PangnirtungAmerica/Paramaribo
America/PhoenixAmerica/Port-au-PrinceAmerica/Port_of_SpainAmerica/Porto_AcreAmerica/Porto_Velho
America/Puerto_RicoAmerica/Rainy_RiverAmerica/Rankin_InletAmerica/RecifeAmerica/Regina
America/Rio_BrancoAmerica/RosarioAmerica/SantiagoAmerica/Santo_DomingoAmerica/Sao_Paulo
America/ScoresbysundAmerica/ShiprockAmerica/St_JohnsAmerica/St_KittsAmerica/St_Lucia
America/St_ThomasAmerica/St_VincentAmerica/Swift_CurrentAmerica/TegucigalpaAmerica/Thule
America/Thunder_BayAmerica/TijuanaAmerica/TorontoAmerica/TortolaAmerica/Vancouver
America/VirginAmerica/WhitehorseAmerica/WinnipegAmerica/YakutatAmerica/Yellowknife
Brazil/AcreBrazil/DeNoronhaBrazil/EastBrazil/WestCanada/Atlantic
Canada/CentralCanada/East-SaskatchewanCanada/EasternCanada/MountainCanada/Newfoundland
Canada/PacificCanada/SaskatchewanCanada/YukonChile/ContinentalChile/EasterIsland
Mexico/BajaNorteMexico/BajaSurMexico/GeneralUS/AlaskaUS/Aleutian
US/ArizonaUS/CentralUS/East-IndianaUS/EasternUS/Hawaii
US/Indiana-StarkeUS/MichiganUS/MountainUS/PacificUS/Pacific-New
US/Samoa    

List of timezones in the group Antarctica

Tabella H-3. Antarctica

Antarctica/CaseyAntarctica/DavisAntarctica/DumontDUrvilleAntarctica/MawsonAntarctica/McMurdo
Antarctica/PalmerAntarctica/RotheraAntarctica/South_PoleAntarctica/SyowaAntarctica/Vostok

List of timezones in the group Arctic

Tabella H-4. Arctic

Arctic/Longyearbyen    

List of timezones in the group Asia

Tabella H-5. Asia

Asia/AdenAsia/AlmatyAsia/AmmanAsia/AnadyrAsia/Aqtau
Asia/AqtobeAsia/AshgabatAsia/AshkhabadAsia/BaghdadAsia/Bahrain
Asia/BakuAsia/BangkokAsia/BeirutAsia/BishkekAsia/Brunei
Asia/CalcuttaAsia/ChoibalsanAsia/ChongqingAsia/ChungkingAsia/Colombo
Asia/DaccaAsia/DamascusAsia/DhakaAsia/DiliAsia/Dubai
Asia/DushanbeAsia/GazaAsia/HarbinAsia/Hong_KongAsia/Hovd
Asia/IrkutskAsia/IstanbulAsia/JakartaAsia/JayapuraAsia/Jerusalem
Asia/KabulAsia/KamchatkaAsia/KarachiAsia/KashgarAsia/Katmandu
Asia/KrasnoyarskAsia/Kuala_LumpurAsia/KuchingAsia/KuwaitAsia/Macao
Asia/MacauAsia/MagadanAsia/MakassarAsia/ManilaAsia/Muscat
Asia/NicosiaAsia/NovosibirskAsia/OmskAsia/OralAsia/Phnom_Penh
Asia/PontianakAsia/PyongyangAsia/QatarAsia/QyzylordaAsia/Rangoon
Asia/RiyadhAsia/SaigonAsia/SakhalinAsia/SamarkandAsia/Seoul
Asia/ShanghaiAsia/SingaporeAsia/TaipeiAsia/TashkentAsia/Tbilisi
Asia/TehranAsia/Tel_AvivAsia/ThimbuAsia/ThimphuAsia/Tokyo
Asia/Ujung_PandangAsia/UlaanbaatarAsia/Ulan_BatorAsia/UrumqiAsia/Vientiane
Asia/VladivostokAsia/YakutskAsia/YekaterinburgAsia/YerevanIndian/Antananarivo
Indian/ChagosIndian/ChristmasIndian/CocosIndian/ComoroIndian/Kerguelen
Indian/MaheIndian/MaldivesIndian/MauritiusIndian/MayotteIndian/Reunion

List of timezones in the group Atlantic

Tabella H-6. Atlantic

Atlantic/AzoresAtlantic/BermudaAtlantic/CanaryAtlantic/Cape_VerdeAtlantic/Faeroe
Atlantic/Jan_MayenAtlantic/MadeiraAtlantic/ReykjavikAtlantic/South_GeorgiaAtlantic/St_Helena
Atlantic/Stanley    

List of timezones in the group Australia

Tabella H-7. Australia

Australia/ACTAustralia/AdelaideAustralia/BrisbaneAustralia/Broken_HillAustralia/Canberra
Australia/CurrieAustralia/DarwinAustralia/HobartAustralia/LHIAustralia/Lindeman
Australia/Lord_HoweAustralia/MelbourneAustralia/NorthAustralia/NSWAustralia/Perth
Australia/QueenslandAustralia/SouthAustralia/SydneyAustralia/TasmaniaAustralia/Victoria
Australia/WestAustralia/Yancowinna   

List of timezones in the group Europe

Tabella H-8. Europe

Europe/AmsterdamEurope/AndorraEurope/AthensEurope/BelfastEurope/Belgrade
Europe/BerlinEurope/BratislavaEurope/BrusselsEurope/BucharestEurope/Budapest
Europe/ChisinauEurope/CopenhagenEurope/DublinEurope/GibraltarEurope/Helsinki
Europe/IstanbulEurope/KaliningradEurope/KievEurope/LisbonEurope/Ljubljana
Europe/LondonEurope/LuxembourgEurope/MadridEurope/MaltaEurope/Mariehamn
Europe/MinskEurope/MonacoEurope/MoscowEurope/NicosiaEurope/Oslo
Europe/ParisEurope/PragueEurope/RigaEurope/RomeEurope/Samara
Europe/San_MarinoEurope/SarajevoEurope/SimferopolEurope/SkopjeEurope/Sofia
Europe/StockholmEurope/TallinnEurope/TiraneEurope/TiraspolEurope/Uzhgorod
Europe/VaduzEurope/VaticanEurope/ViennaEurope/VilniusEurope/Warsaw
Europe/ZagrebEurope/ZaporozhyeEurope/Zurich  

List of timezones in the group Pacific

Tabella H-9. Pacific

Pacific/ApiaPacific/AucklandPacific/ChathamPacific/EasterPacific/Efate
Pacific/EnderburyPacific/FakaofoPacific/FijiPacific/FunafutiPacific/Galapagos
Pacific/GambierPacific/GuadalcanalPacific/GuamPacific/HonoluluPacific/Johnston
Pacific/KiritimatiPacific/KosraePacific/KwajaleinPacific/MajuroPacific/Marquesas
Pacific/MidwayPacific/NauruPacific/NiuePacific/NorfolkPacific/Noumea
Pacific/Pago_PagoPacific/PalauPacific/PitcairnPacific/PonapePacific/Port_Moresby
Pacific/RarotongaPacific/SaipanPacific/SamoaPacific/TahitiPacific/Tarawa
Pacific/TongatapuPacific/TrukPacific/WakePacific/WallisPacific/Yap

List of timezones in the group Others

Tabella H-10. Others

CETCST6CDTCubaEETEgypt
EireESTEST5EDTEtc/GMTEtc/GMT+0
Etc/GMT+1Etc/GMT+10Etc/GMT+11Etc/GMT+12Etc/GMT+2
Etc/GMT+3Etc/GMT+4Etc/GMT+5Etc/GMT+6Etc/GMT+7
Etc/GMT+8Etc/GMT+9Etc/GMT-0Etc/GMT-1Etc/GMT-10
Etc/GMT-11Etc/GMT-12Etc/GMT-13Etc/GMT-14Etc/GMT-2
Etc/GMT-3Etc/GMT-4Etc/GMT-5Etc/GMT-6Etc/GMT-7
Etc/GMT-8Etc/GMT-9Etc/GMT0Etc/GreenwichEtc/UCT
Etc/UniversalEtc/UTCEtc/ZuluFactoryGB
GB-EireGMTGMT+0GMT-0GMT0
GreenwichHongkongHSTIcelandIran
IsraelJamaicaJapanKwajaleinLibya
METMSTMST7MDTNavajoNZ
NZ-CHATPolandPortugalPRCPST8PDT
ROCROKSingaporeTurkeyUCT
UniversalUTCW-SUWETZulu

Appendice I. Extension Categorization

This appendix categorizes more than 150 extensions documented in the PHP Manual by several criteria.


Purpose


Membership


Bundled Extensions

These extensions are bundled with PHP.


External Extensions

In order to compile these extensions, external libraries will be needed.


PECL Extensions

These extensions are available from PECL. More PECL extensions exist but they are not documented in the PHP manual yet.


Appendice J. Lista dei sinonimi delle funzioni PHP

Esistono diverse funzioni in PHP che si possono richiamare con diversi nomi. In alcuni casi non esistono nomi preferenziali, ad esempio is_int() e is_integer() sono entrambi validi. Tuttavia esistono funzioni che hanno cambiato nomi per via di una pulizia delle API o per qualche altro motivo e si è mantenuto il vecchio nome solo compatibilità con il passato. É solitamente una cattiva idea utilizzare questo tipo di sinonimi, in quanto possono esser soggetti a ridenominazione ed invecchiamento, e quindi il loro uso può indurre alla scrittura di script non portabili. Quest'elenco è fornito per aiutare coloro che vogliono trasformare i vecchi script nella nuova sintassi.

Quest'elenco è consistente con la versione 4.0.6 del PHP. Per avere la lista completa aggiornata quotidianamente, guardare http://zend.com/phpfunc/all_aliases.php.

Tabella J-1. Sinonimi

Sinonimi (alias)Funzione MasterEstensione utilizzata
_gettext()Gettext
addswfmovie_add()Ming (flash)
addswfsprite_add()Ming (flash)
add_rootdomxml_add_root()DOM XML
addactionswfbutton_addAction()Ming (flash)
addcolorswfdisplayitem_addColor()Ming (flash)
addentryswfgradient_addEntry()Ming (flash)
addfillswfshape_addfill()Ming (flash)
addshapeswfbutton_addShape()Ming (flash)
addstringswftext_addString()Ming (flash)
addstringswftextfield_addString()Ming (flash)
alignswftextfield_align()Ming (flash)
attributesdomxml_attributes()DOM XML
childrendomxml_children()DOM XML
choprtrim()Base syntax
closeclosedir()Base syntax
com_getcom_propget()COM
com_propsetcom_propput()COM
com_setcom_propput()COM
cv_addccvs_add()CCVS
cv_authccvs_auth()CCVS
cv_commandccvs_command()CCVS
cv_countccvs_count()CCVS
cv_deleteccvs_delete()CCVS
cv_doneccvs_done()CCVS
cv_initccvs_init()CCVS
cv_lookupccvs_lookup()CCVS
cv_newccvs_new()CCVS
cv_reportccvs_report()CCVS
cv_returnccvs_return()CCVS
cv_reverseccvs_reverse()CCVS
cv_saleccvs_sale()CCVS
cv_statusccvs_status()CCVS
cv_textvalueccvs_textvalue()CCVS
cv_voidccvs_void()CCVS
dieexit()Miscellaneous functions
dirgetdir()Base syntax
diskfreespacedisk_free_space()Filesystem
domxml_getattrdomxml_get_attribute()DOM XML
domxml_setattrdomxml_set_attribute()DOM XML
doublevalfloatval()Base syntax
drawarcswfshape_drawarc()Ming (flash)
drawcircleswfshape_drawcircle()Ming (flash)
drawcubicswfshape_drawcubic()Ming (flash)
drawcubictoswfshape_drawcubicto()Ming (flash)
drawcurveswfshape_drawcurve()Ming (flash)
drawcurvetoswfshape_drawcurveto()Ming (flash)
drawglyphswfshape_drawglyph()Ming (flash)
drawlineswfshape_drawline()Ming (flash)
drawlinetoswfshape_drawlineto()Ming (flash)
dtddomxml_intdtd()DOM XML
dumpmemdomxml_dumpmem()DOM XML
fbsqlfbsql_db_query()FrontBase
fputsfwrite()Base syntax
get_attributedomxml_get_attribute()DOM XML
getascentswffont_getAscent()Ming (flash)
getascentswftext_getAscent()Ming (flash)
getattrdomxml_get_attribute()DOM XML
getdescentswffont_getDescent()Ming (flash)
getdescentswftext_getDescent()Ming (flash)
getheightswfbitmap_getHeight()Ming (flash)
getleadingswffont_getLeading()Ming (flash)
getleadingswftext_getLeading()Ming (flash)
getshape1swfmorph_getShape1()Ming (flash)
getshape2swfmorph_getShape2()Ming (flash)
getwidthswfbitmap_getWidth()Ming (flash)
getwidthswffont_getWidth()Ming (flash)
getwidthswftext_getWidth()Ming (flash)
gzputsgzwrite()Zlib
i18n_convertmb_convert_encoding()Multi-bytes Strings
i18n_discover_encodingmb_detect_encoding()Multi-bytes Strings
i18n_http_inputmb_http_input()Multi-bytes Strings
i18n_http_outputmb_http_output()Multi-bytes Strings
i18n_internal_encodingmb_internal_encoding()Multi-bytes Strings
i18n_ja_jp_hantozenmb_convert_kana()Multi-bytes Strings
i18n_mime_header_decodemb_decode_mimeheader()Multi-bytes Strings
i18n_mime_header_encodemb_encode_mimeheader()Multi-bytes Strings
imap_createimap_createmailbox()IMAP
imap_fetchtextimap_body()IMAP
imap_getmailboxesimap_list_full()IMAP
imap_getsubscribedimap_lsub_full()IMAP
imap_headerimap_headerinfo()IMAP
imap_listmailboximap_list()IMAP
imap_listsubscribedimap_lsub()IMAP
imap_renameimap_renamemailbox()IMAP
imap_scanimap_listscan()IMAP
imap_scanmailboximap_listscan()IMAP
ini_alterini_set()Base syntax
is_doubleis_float()Base syntax
is_integeris_int()Base syntax
is_longis_int()Base syntax
is_realis_float()Base syntax
is_writeableis_writable()Base syntax
joinimplode()Base syntax
labelframeswfmovie_labelFrame()Ming (flash)
labelframeswfsprite_labelFrame()Ming (flash)
last_childdomxml_last_child()DOM XML
lastchilddomxml_last_child()DOM XML
ldap_closeldap_unbind()LDAP
magic_quotes_runtimeset_magic_quotes_runtime()Base syntax
mbstrcutmb_strcut()Multi-bytes Strings
mbstrlenmb_strlen()Multi-bytes Strings
mbstrposmb_strpos()Multi-bytes Strings
mbstrrposmb_strrpos()Multi-bytes Strings
mbsubstrmb_substr()Multi-bytes Strings
ming_setcubicthresholdming_setCubicThreshold()Ming (flash)
ming_setscaleming_setScale()Ming (flash)
moveswfdisplayitem_move()Ming (flash)
movepenswfshape_movepen()Ming (flash)
movepentoswfshape_movepento()Ming (flash)
movetoswfdisplayitem_moveTo()Ming (flash)
movetoswffill_moveTo()Ming (flash)
movetoswftext_moveTo()Ming (flash)
msqlmsql_db_query()mSQL
msql_createdbmsql_create_db()mSQL
msql_dbnamemsql_result()mSQL
msql_dropdbmsql_drop_db()mSQL
msql_fieldflagsmsql_field_flags()mSQL
msql_fieldlenmsql_field_len()mSQL
msql_fieldnamemsql_field_name()mSQL
msql_fieldtablemsql_field_table()mSQL
msql_fieldtypemsql_field_type()mSQL
msql_freeresultmsql_free_result()mSQL
msql_listdbsmsql_list_dbs()mSQL
msql_listfieldsmsql_list_fields()mSQL
msql_listtablesmsql_list_tables()mSQL
msql_numfieldsmsql_num_fields()mSQL
msql_numrowsmsql_num_rows()mSQL
msql_regcasesql_regcase()mSQL
msql_selectdbmsql_select_db()mSQL
msql_tablenamemsql_result()mSQL
mssql_affected_rowssybase_affected_rows()Sybase
mssql_affected_rowssybase_affected_rows()Sybase
mssql_closesybase_close()Sybase
mssql_closesybase_close()Sybase
mssql_connectsybase_connect()Sybase
mssql_connectsybase_connect()Sybase
mssql_data_seeksybase_data_seek()Sybase
mssql_data_seeksybase_data_seek()Sybase
mssql_fetch_arraysybase_fetch_array()Sybase
mssql_fetch_arraysybase_fetch_array()Sybase
mssql_fetch_fieldsybase_fetch_field()Sybase
mssql_fetch_fieldsybase_fetch_field()Sybase
mssql_fetch_objectsybase_fetch_object()Sybase
mssql_fetch_objectsybase_fetch_object()Sybase
mssql_fetch_rowsybase_fetch_row()Sybase
mssql_fetch_rowsybase_fetch_row()Sybase
mssql_field_seeksybase_field_seek()Sybase
mssql_field_seeksybase_field_seek()Sybase
mssql_free_resultsybase_free_result()Sybase
mssql_free_resultsybase_free_result()Sybase
mssql_get_last_messagesybase_get_last_message()Sybase
mssql_get_last_messagesybase_get_last_message()Sybase
mssql_min_client_severitysybase_min_client_severity()Sybase
mssql_min_error_severitysybase_min_error_severity()Sybase
mssql_min_message_severitysybase_min_message_severity()Sybase
mssql_min_server_severitysybase_min_server_severity()Sybase
mssql_num_fieldssybase_num_fields()Sybase
mssql_num_fieldssybase_num_fields()Sybase
mssql_num_rowssybase_num_rows()Sybase
mssql_num_rowssybase_num_rows()Sybase
mssql_pconnectsybase_pconnect()Sybase
mssql_pconnectsybase_pconnect()Sybase
mssql_querysybase_query()Sybase
mssql_querysybase_query()Sybase
mssql_resultsybase_result()Sybase
mssql_resultsybase_result()Sybase
mssql_select_dbsybase_select_db()Sybase
mssql_select_dbsybase_select_db()Sybase
multcolorswfdisplayitem_multColor()Ming (flash)
mysqlmysql_db_query()MySQL
mysql_createdbmysql_create_db()MySQL
mysql_db_namemysql_result()MySQL
mysql_dbnamemysql_result()MySQL
mysql_dropdbmysql_drop_db()MySQL
mysql_fieldflagsmysql_field_flags()MySQL
mysql_fieldlenmysql_field_len()MySQL
mysql_fieldnamemysql_field_name()MySQL
mysql_fieldtablemysql_field_table()MySQL
mysql_fieldtypemysql_field_type()MySQL
mysql_freeresultmysql_free_result()MySQL
mysql_listdbsmysql_list_dbs()MySQL
mysql_listfieldsmysql_list_fields()MySQL
mysql_listtablesmysql_list_tables()MySQL
mysql_numfieldsmysql_num_fields()MySQL
mysql_numrowsmysql_num_rows()MySQL
mysql_selectdbmysql_select_db()MySQL
mysql_tablenamemysql_result()MySQL
namedomxml_attrname()DOM XML
new_childdomxml_new_child()DOM XML
new_xmldocdomxml_new_xmldoc()DOM XML
nextframeswfmovie_nextFrame()Ming (flash)
nextframeswfsprite_nextFrame()Ming (flash)
nodedomxml_node()DOM XML
oci8appendocicollappend()OCI8
oci8assignocicollassign()OCI8
oci8assignelemocicollassignelem()OCI8
oci8closeocicloselob()OCI8
oci8freeocifreecoll()OCI8
oci8freeocifreedesc()OCI8
oci8getelemocicollgetelem()OCI8
oci8loadociloadlob()OCI8
oci8maxocicollmax()OCI8
oci8ocifreecursorocifreestatement()OCI8
oci8saveocisavelob()OCI8
oci8savefileocisavelobfile()OCI8
oci8sizeocicollsize()OCI8
oci8trimocicolltrim()OCI8
oci8writetemporaryociwritetemporarylob()OCI8
oci8writetofileociwritelobtofile()OCI8
odbc_doodbc_exec()OCI8
odbc_field_precisionodbc_field_len()OCI8
outputswfmovie_output()Ming (flash)
parentdomxml_parent()DOM XML
pdf_add_outlinepdf_add_bookmark()PDF
pg_clientencodingpg_client_encoding()PostgreSQL
pg_setclientencodingpg_set_client_encoding()PostgreSQL
poscurrent()Base syntax
recoderecode_string()Recode
removeswfmovie_remove()Ming (flash)
removeswfsprite_remove()Ming (flash)
rewindrewinddir()Base syntax
rootdomxml_root()DOM XML
rotateswfdisplayitem_rotate()Ming (flash)
rotatetoswfdisplayitem_rotateTo()Ming (flash)
rotatetoswffill_rotateTo()Ming (flash)
saveswfmovie_save()Ming (flash)
savetofileswfmovie_saveToFile()Ming (flash)
scaleswfdisplayitem_scale()Ming (flash)
scaletoswfdisplayitem_scaleTo()Ming (flash)
scaletoswffill_scaleTo()Ming (flash)
set_attributedomxml_set_attribute()DOM XML
set_contentdomxml_set_content()DOM XML
setactionswfbutton_setAction()Ming (flash)
setattrdomxml_set_attribute()DOM XML
setbackgroundswfmovie_setBackground()Ming (flash)
setboundsswftextfield_setBounds()Ming (flash)
setcolorswftext_setColor()Ming (flash)
setcolorswftextfield_setColor()Ming (flash)
setdepthswfdisplayitem_setDepth()Ming (flash)
setdimensionswfmovie_setDimension()Ming (flash)
setdownswfbutton_setDown()Ming (flash)
setfontswftext_setFont()Ming (flash)
setfontswftextfield_setFont()Ming (flash)
setframesswfmovie_setFrames()Ming (flash)
setframesswfsprite_setFrames()Ming (flash)
setheightswftext_setHeight()Ming (flash)
setheightswftextfield_setHeight()Ming (flash)
sethitswfbutton_setHit()Ming (flash)
setindentationswftextfield_setIndentation()Ming (flash)
setleftfillswfshape_setleftfill()Ming (flash)
setleftmarginswftextfield_setLeftMargin()Ming (flash)
setlineswfshape_setline()Ming (flash)
setlinespacingswftextfield_setLineSpacing()Ming (flash)
setmarginsswftextfield_setMargins()Ming (flash)
setmatrixswfdisplayitem_setMatrix()Ming (flash)
setnameswfdisplayitem_setName()Ming (flash)
setnameswftextfield_setName()Ming (flash)
setoverswfbutton_setOver()Ming (flash)
setrateswfmovie_setRate()Ming (flash)
setratioswfdisplayitem_setRatio()Ming (flash)
setrightfillswfshape_setrightfill()Ming (flash)
setrightmarginswftextfield_setRightMargin()Ming (flash)
setspacingswftext_setSpacing()Ming (flash)
setupswfbutton_setUp()Ming (flash)
show_sourcehighlight_file()Base syntax
sizeofcount()Base syntax
skewxswfdisplayitem_skewX()Ming (flash)
skewxtoswfdisplayitem_skewXTo()Ming (flash)
skewxtoswffill_skewXTo()Ming (flash)
skewyswfdisplayitem_skewY()Ming (flash)
skewytoswfdisplayitem_skewYTo()Ming (flash)
skewytoswffill_skewYTo()Ming (flash)
snmpwalkoidsnmprealwalk()SNMP
strchrstrstr()Base syntax
streammp3swfmovie_streamMp3()Ming (flash)
swfactionswfaction_init()Ming (flash)
swfbitmapswfbitmap_init()Ming (flash)
swfbuttonswfbutton_init()Ming (flash)
swffillswffill_init()Ming (flash)
swffontswffont_init()Ming (flash)
swfgradientswfgradient_init()Ming (flash)
swfmorphswfmorph_init()Ming (flash)
swfmovieswfmovie_init()Ming (flash)
swfshapeswfshape_init()Ming (flash)
swfspriteswfsprite_init()Ming (flash)
swftextswftext_init()Ming (flash)
swftextfieldswftextfield_init()Ming (flash)
unlinkdomxml_unlink_node()DOM XML
xptr_new_contextxpath_new_context()DOM XML


Appendice K. Parole riservate nel PHP

Questa è la lista delle parole riservate nel PHP. Nessuno di questi identificatori deve essere utilizzato negli script. Questa lista include parole chiave e variabili predefinite, costanti e nomi di classi. Questa lista non è né esaustiva né completa.


Lista delle parole chiave

Queste parole hanno significato speciale per il PHP. Alcune di esse rappresentano cose che assomigliano a funzioni, altri a costanti, e così via. Ma non lo sono, in verità: sono costrutti del linguaggi. non si deve utilizzare nessuna di queste parole come costante, nome di classe, funzione o nome di metodo. L'utilizzo come nomi di variabili normalmente funziona, ma questo può generare confusione.


Variabili predefinite

A partire dal PHP 4.1.0, il metodo raccomandato per ottenere le variabili esterne è quello di usare i superglobals, come spiegato più sotto. In precedenza, gli sviluppatori si appoggiavano ai register_globals o agli array predefiniti ($HTTP_*_VARS). As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.


Variabili di server: $_SERVER

Nota: Introdotta dal PHP 4.1.0. Nelle versioni precedenti, utilizzare $HTTP_SERVER_VARS.

$_SERVER è un array che contiene informazioni quali header, percorsi e posizioni degli script. Le voci in questo array sono create dal server web. non c'è garanzia che ogni server web fornisca queste informazioni; i server possono ometterne alcune, oppure fornirne altre non contemplate qui. Detto questo, gran parte di queste variabili sono contemplate nelle specifiche CGI 1.1, quindi è molto probabile ritrovarle in questo array.

Questo array è una variabile 'superglobal', o globale automatica. Ciò siginifica che è disponibile in tutti gli scope all'interno di uno script. Non è necessario scrivere global $_SERVER; per accedervi in una funzione o metodo, come invece occorreva fare con $HTTP_SERVER_VARS.

$HTTP_SERVER_VARS contiene le stesse informazioni, ma non è autoglobal. (si noti che $HTTP_SERVER_VARS e $_SERVER sono variabili distinte e che PHP le tratta di conseguenza)

Se la direttiva register_globals è impostata, queste informazioni saranno rese disponibili anche nello scope globale dello script; quindi in variabili diverse da $_SERVER e $HTTP_SERVER_VARS arrays. Per la documentazione correlata, vedere il capitolo sulla sicurezza intitolato Utilizzo dei Register Globals. Queste variabili globali individuali non sono autoglobal.

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'PHP_SELF'

The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.

'argv'

Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.

'argc'

Contains the number of command line parameters passed to the script (if run on the command line).

'GATEWAY_INTERFACE'

What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.

'SERVER_NAME'

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

'SERVER_SOFTWARE'

Server identification string, given in the headers when responding to requests.

'SERVER_PROTOCOL'

Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';

'REQUEST_METHOD'

Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

'REQUEST_TIME'

The timestamp of the start of the request. Available since PHP 5.1.0.

'QUERY_STRING'

The query string, if any, via which the page was accessed.

'DOCUMENT_ROOT'

The document root directory under which the current script is executing, as defined in the server's configuration file.

'HTTP_ACCEPT'

Contents of the Accept: header from the current request, if there is one.

'HTTP_ACCEPT_CHARSET'

Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.

'HTTP_ACCEPT_ENCODING'

Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.

'HTTP_ACCEPT_LANGUAGE'

Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.

'HTTP_CONNECTION'

Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.

'HTTP_HOST'

Contents of the Host: header from the current request, if there is one.

'HTTP_REFERER'

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

'HTTP_USER_AGENT'

Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.

'REMOTE_ADDR'

The IP address from which the user is viewing the current page.

'REMOTE_HOST'

The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Nota: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'

The port being used on the user's machine to communicate with the web server.

'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Nota: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'

The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.

'SERVER_PORT'

The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

'SERVER_SIGNATURE'

String containing the server version and virtual host name which are added to server-generated pages, if enabled.

'PATH_TRANSLATED'

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Nota: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined.

Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'

Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

'PHP_AUTH_USER'

When running under Apache as module doing HTTP authentication this variable is set to the username provided by the user.

'PHP_AUTH_PW'

When running under Apache as module doing HTTP authentication this variable is set to the password provided by the user.

'AUTH_TYPE'

When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.


Environment variables: $_ENV

Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_ENV_VARS.

These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.

Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_ENV; to access it within functions or methods, as you do with $HTTP_ENV_VARS.

$HTTP_ENV_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_ENV and $HTTP_ENV_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP Cookies: $_COOKIE

Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_COOKIE_VARS.

An associative array of variables passed to the current script via HTTP cookies. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_COOKIE; to access it within functions or methods, as you do with $HTTP_COOKIE_VARS.

$HTTP_COOKIE_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_COOKIE and $HTTP_COOKIE_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP GET variables: $_GET

Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_GET_VARS.

An associative array of variables passed to the current script via the HTTP GET method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_GET; to access it within functions or methods, as you do with $HTTP_GET_VARS.

$HTTP_GET_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_GET and $HTTP_GET_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP POST variables: $_POST

Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_VARS.

An associative array of variables passed to the current script via the HTTP POST method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_POST; to access it within functions or methods, as you do with $HTTP_POST_VARS.

$HTTP_POST_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_POST and $HTTP_POST_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


HTTP File upload variables: $_FILES

Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_FILES.

An associative array of items uploaded to the current script via the HTTP POST method. Automatically global in any scope.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_FILES; to access it within functions or methods, as you do with $HTTP_POST_FILES.

$HTTP_POST_FILES contains the same information, but is not an autoglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_FILES and $HTTP_POST_FILES arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


Request variables: $_REQUEST

Nota: Introduced in 4.1.0. There is no equivalent array in earlier versions.

Nota: Prior to PHP 4.3.0, $_FILES information was also included in $_REQUEST.

An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_REQUEST; to access it within functions or methods.

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_REQUEST array. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


Session variables: $_SESSION

Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_SESSION_VARS.

An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SESSION; to access it within functions or methods, as you do with $HTTP_SESSION_VARS.

$HTTP_SESSION_VARS contains the same information, but is not an autoglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SESSION and $HTTP_SESSION_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.


Global variables: $GLOBALS

Nota: $GLOBALS has been available since PHP 3.0.0.

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $GLOBALS; to access it within functions or methods.


The previous error message: $php_errormsg

$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).


Predefined Classes

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory

The class from which dir is instantiated.

stdClass

__PHP_Incomplete_Class


Predefined classes as of PHP 5

These additional predefined classes were introduced in PHP 5.0.0

exception

php_user_filter


Ming Defined Classes

These classes are defined in the Ming extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite


Oracle 8 Defined Classes

These classes are defined in the Oracle 8 extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

OCI-Lob

OCI-Collection


qtdom Defined Classes

These classes are defined in the qtdom extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

QDomDocument

QDomNode


Costanti Predefinite


Core Predefined Constants

These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.

PHP_VERSION (string)

PHP_OS (string)

PHP_EOL (string)

Available since PHP 4.3.10 and PHP 5.0.2

PHP_INT_MAX (integer)

Available since PHP 4.4.0 and PHP 5.0.5

PHP_INT_SIZE (integer)

Available since PHP 4.4.0 and PHP 5.0.5

DEFAULT_INCLUDE_PATH (string)

PEAR_INSTALL_DIR (string)

PEAR_EXTENSION_DIR (string)

PHP_EXTENSION_DIR (string)

PHP_BINDIR (string)

PHP_LIBDIR (string)

PHP_DATADIR (string)

PHP_SYSCONFDIR (string)

PHP_LOCALSTATEDIR (string)

PHP_CONFIG_FILE_PATH (string)

PHP_OUTPUT_HANDLER_START (integer)

PHP_OUTPUT_HANDLER_CONT (integer)

PHP_OUTPUT_HANDLER_END (integer)

E_ERROR (integer)

E_WARNING (integer)

E_PARSE (integer)

E_NOTICE (integer)

E_CORE_ERROR (integer)

E_CORE_WARNING (integer)

E_COMPILE_ERROR (integer)

E_COMPILE_WARNING (integer)

E_USER_ERROR (integer)

E_USER_WARNING (integer)

E_USER_NOTICE (integer)

E_ALL (integer)

E_STRICT (integer)

Available since PHP 5.0.0

__COMPILER_HALT_OFFSET__ (integer)

Available since PHP 5.1.0

See also: Magic constants.


Standard Predefined Constants

These constants are defined in PHP by default.

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

SORT_ASC (integer)

SORT_DESC (integer)

SORT_REGULAR (integer)

SORT_NUMERIC (integer)

SORT_STRING (integer)

CASE_LOWER (integer)

CASE_UPPER (integer)

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

CONNECTION_ABORTED (integer)

CONNECTION_NORMAL (integer)

CONNECTION_TIMEOUT (integer)

INI_USER (integer)

INI_PERDIR (integer)

INI_SYSTEM (integer)

INI_ALL (integer)

M_E (float)

M_LOG2E (float)

M_LOG10E (float)

M_LN2 (float)

M_LN10 (float)

M_PI (float)

M_PI_2 (float)

M_PI_4 (float)

M_1_PI (float)

M_2_PI (float)

M_2_SQRTPI (float)

M_SQRT2 (float)

M_SQRT1_2 (float)

CRYPT_SALT_LENGTH (integer)

CRYPT_STD_DES (integer)

CRYPT_EXT_DES (integer)

CRYPT_MD5 (integer)

CRYPT_BLOWFISH (integer)

DIRECTORY_SEPARATOR (string)

SEEK_SET (integer)

SEEK_CUR (integer)

SEEK_END (integer)

LOCK_SH (integer)

LOCK_EX (integer)

LOCK_UN (integer)

LOCK_NB (integer)

HTML_SPECIALCHARS (integer)

HTML_ENTITIES (integer)

ENT_COMPAT (integer)

ENT_QUOTES (integer)

ENT_NOQUOTES (integer)

INFO_GENERAL (integer)

INFO_CREDITS (integer)

INFO_CONFIGURATION (integer)

INFO_MODULES (integer)

INFO_ENVIRONMENT (integer)

INFO_VARIABLES (integer)

INFO_LICENSE (integer)

INFO_ALL (integer)

CREDITS_GROUP (integer)

CREDITS_GENERAL (integer)

CREDITS_SAPI (integer)

CREDITS_MODULES (integer)

CREDITS_DOCS (integer)

CREDITS_FULLPAGE (integer)

CREDITS_QA (integer)

CREDITS_ALL (integer)

STR_PAD_LEFT (integer)

STR_PAD_RIGHT (integer)

STR_PAD_BOTH (integer)

PATHINFO_DIRNAME (integer)

PATHINFO_BASENAME (integer)

PATHINFO_EXTENSION (integer)

PATH_SEPARATOR (string)

CHAR_MAX (integer)

LC_CTYPE (integer)

LC_NUMERIC (integer)

LC_TIME (integer)

LC_COLLATE (integer)

LC_MONETARY (integer)

LC_ALL (integer)

LC_MESSAGES (integer)

ABDAY_1 (integer)

ABDAY_2 (integer)

ABDAY_3 (integer)

ABDAY_4 (integer)

ABDAY_5 (integer)

ABDAY_6 (integer)

ABDAY_7 (integer)

DAY_1 (integer)

DAY_2 (integer)

DAY_3 (integer)

DAY_4 (integer)

DAY_5 (integer)

DAY_6 (integer)

DAY_7 (integer)

ABMON_1 (integer)

ABMON_2 (integer)

ABMON_3 (integer)

ABMON_4 (integer)

ABMON_5 (integer)

ABMON_6 (integer)

ABMON_7 (integer)

ABMON_8 (integer)

ABMON_9 (integer)

ABMON_10 (integer)

ABMON_11 (integer)

ABMON_12 (integer)

MON_1 (integer)

MON_2 (integer)

MON_3 (integer)

MON_4 (integer)

MON_5 (integer)

MON_6 (integer)

MON_7 (integer)

MON_8 (integer)

MON_9 (integer)

MON_10 (integer)

MON_11 (integer)

MON_12 (integer)

AM_STR (integer)

PM_STR (integer)

D_T_FMT (integer)

D_FMT (integer)

T_FMT (integer)

T_FMT_AMPM (integer)

ERA (integer)

ERA_YEAR (integer)

ERA_D_T_FMT (integer)

ERA_D_FMT (integer)

ERA_T_FMT (integer)

ALT_DIGITS (integer)

INT_CURR_SYMBOL (integer)

CURRENCY_SYMBOL (integer)

CRNCYSTR (integer)

MON_DECIMAL_POINT (integer)

MON_THOUSANDS_SEP (integer)

MON_GROUPING (integer)

POSITIVE_SIGN (integer)

NEGATIVE_SIGN (integer)

INT_FRAC_DIGITS (integer)

FRAC_DIGITS (integer)

P_CS_PRECEDES (integer)

P_SEP_BY_SPACE (integer)

N_CS_PRECEDES (integer)

N_SEP_BY_SPACE (integer)

P_SIGN_POSN (integer)

N_SIGN_POSN (integer)

DECIMAL_POINT (integer)

RADIXCHAR (integer)

THOUSANDS_SEP (integer)

THOUSEP (integer)

GROUPING (integer)

YESEXPR (integer)

NOEXPR (integer)

YESSTR (integer)

NOSTR (integer)

CODESET (integer)

LOG_EMERG (integer)

LOG_ALERT (integer)

LOG_CRIT (integer)

LOG_ERR (integer)

LOG_WARNING (integer)

LOG_NOTICE (integer)

LOG_INFO (integer)

LOG_DEBUG (integer)

LOG_KERN (integer)

LOG_USER (integer)

LOG_MAIL (integer)

LOG_DAEMON (integer)

LOG_AUTH (integer)

LOG_SYSLOG (integer)

LOG_LPR (integer)

LOG_NEWS (integer)

LOG_UUCP (integer)

LOG_CRON (integer)

LOG_AUTHPRIV (integer)

LOG_LOCAL0 (integer)

LOG_LOCAL1 (integer)

LOG_LOCAL2 (integer)

LOG_LOCAL3 (integer)

LOG_LOCAL4 (integer)

LOG_LOCAL5 (integer)

LOG_LOCAL6 (integer)

LOG_LOCAL7 (integer)

LOG_PID (integer)

LOG_CONS (integer)

LOG_ODELAY (integer)

LOG_NDELAY (integer)

LOG_NOWAIT (integer)

LOG_PERROR (integer)


Appendice L. List of Resource Types

The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.

Tabella L-1. Resource Types

Resource Type NameCreated ByUsed ByDestroyed ByDefinition
aspell aspell_new() aspell_check(), aspell_check_raw(), aspell_suggest() None Aspell dictionary
bzip2 bzopen() bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() bzclose() Bzip2 file
COM com_load() com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() None COM object reference
VARIANT    
cpdf cpdf_open() cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() cpdf_close() PDF document with CPDF lib
cpdf outline    
curl curl_copy_handle(), curl_init() curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() curl_close() Curl session
dbm dbmopen() dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() dbmclose() Link to DBM database
dba dba_open() dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() dba_close() Link to DBA database
dba persistent dba_popen() dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() None Persistent link to DBA database
dbase dbase_open() dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() dbase_close() Link to Dbase database
dbx_link_object dbx_connect() dbx_query() dbx_close() dbx connection
dbx_result_object dbx_query()   None dbx result
domxml attribute    
domxml document    
domxml node    
xpath context    
xpath object    
fbsql link fbsql_change_user(), fbsql_connect() fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() fbsql_close() Link to fbsql database
fbsql plink fbsql_change_user(), fbsql_pconnect() fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() None Persistent link to fbsql database
fbsql result fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() fbsql_free_result() fbsql result
fdf fdf_open() fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() fdf_close() FDF File
ftp ftp_connect(), ftp_ssl_connect() ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() ftp_close() FTP stream
gd imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() imagedestroy() GD Image
gd font imageloadfont() imagechar(), imagecharup(), imagefontheight() None Font for GD
gd PS encoding    
gd PS font imagepsloadfont() imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() imagepsfreefont() PS font for GD
GMP integer gmp_init() gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() None GMP Number
hyperwave document hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() hw_deleteobject() Hyperwave object
hyperwave link hw_connect() hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() hw_close(), hw_free_document() Link to Hyperwave server
hyperwave link persistent hw_pconnect() hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() None Persistent link to Hyperwave server
icap icap_open() icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() icap_close() Link to icap server
imap imap_open() imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() imap_close() Link to IMAP, POP3 server
imap chain persistent    
imap persistent    
ingres ingres_connect() ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() ingres_close() Link to ingresII base
ingres persistent ingres_pconnect() ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() None Persistent link to ingresII base
interbase blob    
interbase link ibase_connect() ibase_query(), ibase_prepare(), ibase_trans() ibase_close() Link to Interbase database
interbase link persistent ibase_pconnect() ibase_query(), ibase_prepare(), ibase_trans() None Persistent link to Interbase database
interbase query ibase_prepare() ibase_execute() ibase_free_query() Interbase query
interbase result ibase_query() ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() ibase_free_result() Interbase Result
interbase transaction ibase_trans() ibase_commit() ibase_rollback() Interbase transaction
java    
ldap link ldap_connect(), ldap_search() ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() ldap_close() ldap connection
ldap result ldap_read() ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() ldap_free_result() ldap search result
ldap result entry    
mcal mcal_open(), mcal_popen() mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() mcal_close() Link to calendar server
SWFAction    
SWFBitmap    
SWFButton    
SWFDisplayItem    
SWFFill    
SWFFont    
SWFGradient    
SWFMorph    
SWFMovie    
SWFShape    
SWFSprite    
SWFText    
SWFTextField    
mnogosearch agent    
mnogosearch result    
msql link msql_connect() msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() msql_close() Link to mSQL database
msql link persistent msql_pconnect() msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() None Persistent link to mSQL
msql query msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() msql_free_result(), msql_free_result() mSQL result
mssql link mssql_connect() mssql_query(), mssql_select_db() mssql_close() Link to Microsoft SQL Server database
mssql link persistent mssql_pconnect() mssql_query(), mssql_select_db() None Persistent link to Microsoft SQL Server
mssql result mssql_query() mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() mssql_free_result() Microsoft SQL Server result
mysql link mysql_connect() mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() mysql_close() Link to MySQL database
mysql link persistent mysql_pconnect() mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() None Persistent link to MySQL database
mysql result mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() mysql_free_result() MySQL result
oci8 collection    
oci8 connection ocilogon(), ociplogon(), ocinlogon() ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() ocilogoff() Link to Oracle database
oci8 descriptor    
oci8 server    
oci8 session    
oci8 statement ocinewdescriptor() ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() ocifreestatement() Oracle Cursor
odbc link odbc_connect() odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() odbc_close() Link to ODBC database
odbc link persistent odbc_pconnect() odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() None Persistent link to ODBC database
odbc result odbc_prepare() odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() odbc_free_result() ODBC result
birdstep link    
birdstep result    
OpenSSL key openssl_get_privatekey(), openssl_get_publickey() openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() openssl_free_key() OpenSSL key
OpenSSL X.509 openssl_x509_read() openssl_x509_parse(), openssl_x509_checkpurpose() openssl_x509_free() Public Key
oracle Cursor ora_open() ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() ora_close() Oracle cursor
oracle link ora_logon() ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() ora_logoff() Link to oracle database
oracle link persistent ora_plogon() ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() None Persistent link to oracle database
pdf document pdf_new() pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() pdf_close(), pdf_delete() PDF document
pdf image pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() pdf_close_image() Image in PDF file
pdf object    
pdf outline    
pgsql large object pg_lo_open() pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() pg_lo_close() PostgreSQL Large Object
pgsql link pg_connect() pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() pg_close() Link to PostgreSQL database
pgsql link persistent pg_pconnect() pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() None Persistent link to PostgreSQL database
pgsql result pg_execute(), pg_query(), pg_query_params(), pg_get_result() pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() pg_free_result() PostgreSQL result
pgsql string    
printer    
printer brush    
printer font    
printer pen    
pspell pspell_new(), pspell_new_config(), pspell_new_personal() pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() None pspell dictionary
pspell config pspell_config_create() pspell_new_config() None pspell configuration
Sablotron XSLT xslt_create() xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() xslt_free() XSLT parser
shmop shmop_open() shmop_read(), shmop_write(), shmop_size(), shmop_delete() shmop_close()  
sockets file descriptor set socket() accept_connect(), bind(), connect(), listen(), read(), write() close() Socket
sockets i/o vector    
dir opendir() readdir(), rewinddir() closedir() Dir handle
stream fopen(), tmpfile() feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() fclose() File handle
pipe popen() feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() pclose() Process handle
socket fsockopen(), pfsockopen() fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() fclose() Socket handle
sybase-db link sybase_connect() sybase_query(), sybase_select_db() sybase_close() Link to Sybase database using DB library
sybase-db link persistent sybase_pconnect() sybase_query(), sybase_select_db() None Persistent link to Sybase database using DB library
sybase-db result sybase_query(), sybase_unbuffered_query() sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() sybase_free_result() Sybase result using DB library
sybase-ct link sybase_connect() sybase_affected_rows(), sybase_query(), sybase_select_db() sybase_close() Link to Sybase database using CT library
sybase-ct link persistent sybase_pconnect() sybase_affected_rows(), sybase_query(), sybase_select_db() None Persistent link to Sybase database using CT library
sybase-ct result sybase_query() sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() sybase_free_result() Sybase result using CT library
sysvsem sem_get() sem_acquire() sem_release() System V Semaphore
sysvshm shm_attach() shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() shm_detach() System V Shared Memory
wddx wddx_packet_start() wddx_add_vars() wddx_packet_end() WDDX packet
xml xml_parser_create(), xml_parser_create_ns() xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() xml_parser_free() XML parser
zlib gzopen() gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() gzclose() gz-compressed file


Appendice M. List of Supported Protocols/Wrappers

The following is a list of the various URL style protocols that PHP has built-in for use with the filesystem functions such as fopen() and copy(). In addition to these wrappers, as of PHP 4.3.0, you can write your own wrappers using PHP script and stream_wrapper_register().


Filesystem

All versions of PHP. Explicitly using file:// since PHP 4.3.0

  • /path/to/file.ext

  • relative/path/to/file.ext

  • fileInCwd.ext

  • C:/path/to/winfile.ext

  • C:\path\to\winfile.ext

  • \\smbserver\share\path\to\winfile.ext

  • file:///path/to/file.ext

file:// is the default wrapper used with PHP and represents the local filesystem. When a relative path is specified (a path which does not begin with /, \, \\, or a windows drive letter) the path provided will be applied against the current working directory. In many cases this is the directory in which the script resides unless it has been changed. Using the CLI sapi, this defaults to the directory from which the script was called.

With some functions, such as fopen() and file_get_contents(), include_path may be optionally searched for relative paths as well.

Tabella M-1. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.No
Allows ReadingYes
Allows WritingYes
Allows AppendingYes
Allows Simultaneous Reading and WritingYes
Supports stat()Yes
Supports unlink()Yes
Supports rename()Yes
Supports mkdir()Yes
Supports rmdir()Yes


Socket

This section contains the context options supported by the wrappers that work over sockets, like tcp, http or ftp.

As of PHP 5.1.0 only one option is supported, bindto, which can be used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port (you can set the IP or the port number to 0 if you want to let the system choose them for you).

Nota: As FTP creates two socket connections during normal operation, you cannot specify the port number in the bindto option. So, the only supported syntax is ip:0 for the FTP wrapper.

Esempio M-1. Some examples of how to use the bindto option

<?php
// connect to the internet using the '192.168.0.100' IP
$opts = array('socket' =>
            array('bindto' => '192.168.0.100:0'));


// connect to the internet using the '192.168.0.100' IP and port '7000'
$opts = array('socket' =>
            array('bindto' => '192.168.0.100:7000'));


// connect to the internet using port '7000'
$opts = array('socket' =>
            array('bindto' => '0:7000'));


// create the context...
$context = stream_context_create($opts);

// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);

?>

HTTP and HTTPS

PHP 3, PHP 4, PHP 5. https:// since PHP 4.3.0

  • http://example.com

  • http://example.com/file.php?var1=val1&var2=val2

  • http://user:password@example.com

  • https://example.com

  • https://example.com/file.php?var1=val1&var2=val2

  • https://user:password@example.com

Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your ini file or the stream context, it will also be included in the request.

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.

Redirects have been supported since PHP 4.0.5; if you are using an earlier version you will need to include trailing slashes in your URLs. If it's important to know the URL of the resource where your document came from (after all redirects have been processed), you'll need to process the series of response headers returned by the stream.

<?php
$url = 'http://www.example.com/redirecting_page.php';

$fp = fopen($url, 'r');

/* Prior to PHP 4.3.0 use $http_response_header 
   instead of stream_get_meta_data() */
$meta_data = stream_get_meta_data($fp);
foreach($meta_data['wrapper_data'] as $response) {

  /* Were we redirected? */
  if (substr(strtolower($response), 0, 18) == 'content-location: ') {
    /* update $url with where we were redirected to */
    $url = substr($response, 18);
  }

}

?>

The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data().

HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.

Nota: HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.

Tabella M-2. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.Yes
Allows ReadingYes
Allows WritingNo
Allows AppendingNo
Allows Simultaneous Reading and WritingN/A
Supports stat()No
Supports unlink()No
Supports rename()No
Supports mkdir()No
Supports rmdir()No

Tabella M-3. Context options

NameUsageDefault
method GET, POST, or any other HTTP method supported by the remote server. GET
headerAdditional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).  
user_agentValue to send with User-Agent: header. This value will only be used if user-agent is not specified in the header context option above. php.ini setting: user_agent
content Additional data to be sent after the headers. Typically used with POST or PUT requests.  
proxy URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100). HTTPS proxying (through HTTP proxies) only works in PHP 5.1.0 or greater.  
request_fulluri When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it. FALSE
max_redirects The max number of redirects to follow. Added in PHP 5.1.0. 20

Underlying socket stream context options: Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.


FTP and FTPS

PHP 3, PHP 4, PHP 5. ftps:// since PHP 4.3.0

  • ftp://example.com/pub/file.txt

  • ftp://user:password@example.com/pub/file.txt

  • ftps://example.com/pub/file.txt

  • ftps://user:password@example.com/pub/file.txt

Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.

You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.

Appending: As of PHP 5.0.0 files may be appended via the ftp:// URL wrapper. In prior versions, attempting to append to a file via ftp:// will result in failure.

ftps:// was introduced in PHP 4.3.0. It is the same as ftp://, but attempts to negotiate a secure connection with the ftp server. If the server does not support SSL, then the connection falls back to regular unencrypted ftp.

Nota: FTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.

Tabella M-4. Wrapper Summary

AttributePHP 4PHP 5
Restricted by allow_url_fopen.YesYes
Allows ReadingYesYes
Allows WritingYes (new files only)Yes (new files/existing files with overwrite)
Allows AppendingNoYes
Allows Simultaneous Reading and WritingNoNo
Supports stat()No As of PHP 5.0.0: filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only. As of PHP 5.1.0: filemtime().
Supports unlink()NoYes
Supports rename()NoYes
Supports mkdir()NoYes
Supports rmdir()NoYes

Tabella M-5. Context options (as of PHP 5.0.0)

NameUsageDefault
overwrite Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only. FALSE (Disabled)
resume_pos File offset at which to begin transfer. Applies to read mode (downloading) only. 0 (Beginning of File)
proxy (PHP 5.1.0 or greater) Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000  

Underlying socket stream context options: Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.


PHP input/output streams

PHP 3.0.13 and up, php://output and php://input since PHP 4.3.0, php://filter since PHP 5.0.0.

  • php://stdin

  • php://stdout

  • php://stderr

  • php://output

  • php://input

  • php://filter

php://stdin, php://stdout and php://stderr allow access to the corresponding input or output stream of the PHP process.

php://output allows you to write to the output buffer mechanism in the same way as print() and echo().

php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype="multipart/form-data".

php://stdin and php://input are read-only, whereas php://stdout, php://stderr and php://output are write-only.

php://filter is a kind of meta-wrapper designed to permit the application of filters to a stream at the time of opening. This is useful with all-in-one file functions such as readfile(), file(), and file_get_contents() where there is otherwise no opportunity to apply a filter to the stream prior the contents being read.

The php://filter target takes the following 'parameters' as parts of its 'path'.

  • /resource=<stream to be filtered> (required) This parameter must be located at the end of your php://filter specification and should point to the stream which you want filtered.

    <?php
    /* This is equivalent to simply:
       readfile("http://www.example.com");
       since no filters are actually specified */
    
    readfile("php://filter/resource=http://www.example.com");
    ?>

  • /read=<filter list to apply to read chain> (optional) This parameter takes one or more filternames separated by the pipe character |.

    <?php
    /* This will output the contents of 
       www.example.com entirely in uppercase */
    readfile("php://filter/read=string.toupper/resource=http://www.example.com");
    
    /* This will do the same as above
       but will also ROT13 encode it */
    readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.example.com");
    ?>

  • /write=<filter list to apply to write chain> (optional) This parameter takes one or more filternames separated by the pipe character |.

    <?php
    /* This will filter the string "Hello World"
       through the rot13 filter, then write to
       example.txt in the current directory */
    file_put_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
    ?>

  • /<filter list to apply to both chains> (optional) Any filter lists which are not prefixed specifically by read= or write= will be applied to both the read and write chains (as appropriate).

Tabella M-6. Wrapper Summary (For php://filter, refer to summary of wrapper being filtered.)

AttributeSupported
Restricted by allow_url_fopen.No
Allows Reading php://stdin and php://input only.
Allows Writing php://stdout, php://stderr, and php://output only.
Allows Appending php://stdout, php://stderr, and php://output only. (Equivalent to writing)
Allows Simultaneous Reading and WritingNo. These wrappers are unidirectional.
Supports stat()No
Supports unlink()No
Supports rename()No
Supports mkdir()No
Supports rmdir()No


Compression Streams

zlib: PHP 4.0.4 - PHP 4.2.3 (systems with fopencookie only)

compress.zlib:// and compress.bzip2:// PHP 4.3.0 and up

  • zlib:

  • compress.zlib://

  • compress.bzip2://

zlib: works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated as of PHP 4.3.0 due to ambiguities with filenames containing ':' characters; use compress.zlib:// instead.

compress.zlib:// and compress.bzip2:// are equivalent to gzopen() and bzopen() respectively, and operate even on systems that do not support fopencookie.

Tabella M-7. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.No
Allows ReadingYes
Allows WritingYes
Allows AppendingYes
Allows Simultaneous Reading and WritingNo
Supports stat() No, use the normal file:// wrapper to stat compressed files.
Supports unlink() No, use the normal file:// wrapper to unlink compressed files.
Supports rename()No
Supports mkdir()No
Supports rmdir()No


Secure Shell 2

ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP 4.3.0 and up (PECL)

  • ssh2.shell://user:pass@example.com:22/xterm

  • ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd

  • ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14

  • ssh2.sftp://user:pass@example.com:22/path/to/filename

This wrapper is not enabled by default: In order to use the ssh2.*:// wrappers you must install the SSH2 extension available from PECL.

In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.

Esempio M-2. Opening a stream from an active connection

<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
                                            '/home/username/.ssh/id_rsa', 'secret');
$stream = fopen("ssh2.tunnel://$session/remote.example.com:1234", 'r');
?>

Tabella M-8. Wrapper Summary

Attributessh2.shellssh2.execssh2.tunnelssh2.sftpssh2.scp
Restricted by allow_url_fopen.YesYesYesYesYes
Allows ReadingYesYesYesYesYes
Allows WritingYesYesYesYesNo
Allows AppendingNoNoNoYes (When supported by server)No
Allows Simultaneous Reading and WritingYesYesYesYesNo
Supports stat()NoNoNoYesNo
Supports unlink()NoNoNoYesNo
Supports rename()NoNoNoYesNo
Supports mkdir()NoNoNoYesNo
Supports rmdir()NoNoNoYesNo

Tabella M-9. Context options

NameUsageDefault
sessionPreconnected ssh2 resource to be reused 
sftpPreallocated sftp resource to be reused 
methodsKey exchange, hostkey, cipher, compression, and MAC methods to use 
callbacks  
usernameUsername to connect as 
passwordPassword to use with password authentication 
pubkey_fileName of public key file to use for authentication 
privkey_fileName of private key file to use for authentication 
envAssociate array of environment variables to set 
termTerminal emulation type to request when allocating a pty 
term_widthWidth of terminal requested when allocating a pty 
term_heightHeight of terminal requested when allocating a pty 
term_unitsUnits to use with term_width and term_heightSSH2_TERM_UNIT_CHARS


Audio Streams

ogg:// PHP 4.3.0 and up (PECL)

  • ogg://soundfile.ogg

  • ogg:///path/to/soundfile.ogg

  • ogg://http://www.example.com/path/to/soundstream.ogg

This wrapper is not enabled by default: In order to use the ogg:// wrapper you must install the OGG/Vorbis extension available from PECL.

Files opened for reading via the ogg:// wrapper are treated as compressed audio encoded using the OGG/Vorbis codec. Similarly, files opened for writing or appending via the ogg:// wrapper are writen as compressed audio data. stream_get_meta_data(), when used on an OGG/Vorbis file opened for reading will return various details about the stream including the vendor tag, any included comments, the number of channels, the sampling rate, and the encoding rate range described by: bitrate_lower, bitrate_upper, bitrate_nominal, and bitrate_window.

Tabella M-10. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.No
Allows ReadingYes
Allows WritingYes
Allows AppendingYes
Allows Simultaneous Reading and WritingNo
Supports stat()No
Supports unlink()No
Supports rename()No
Supports mkdir()No
Supports rmdir()No

Tabella M-11. Context options

NameUsageDefaultMode
pcm_mode PCM encoding to apply while reading, one of: OGGVORBIS_PCM_U8, OGGVORBIS_PCM_S8, OGGVORBIS_PCM_U16_BE, OGGVORBIS_PCM_S16_BE, OGGVORBIS_PCM_U16_LE, and OGGVORBIS_PCM_S16_LE. (8 vs 16 bit, signed or unsigned, big or little endian) OGGVORBIS_PCM_S16_LERead
rate Sampling rate of input data, expressed in Hz 44100Write/Append
bitrate When given as an integer, the fixed bitrate at which to encode. (16000 to 131072) When given as a float, the variable bitrate quality to use. (-1.0 to 1.0) 128000Write/Append
channels The number of audio channels to encode, typically 1 (Mono), or 2 (Stero). May range as high as 16. 2Write/Append
comments An array of string values to encode into the track header.  Write/Append


Process Interaction Streams

expect:// PHP 4.3.0 and up (PECL)

  • expect://command

This wrapper is not enabled by default: In order to use the expect:// wrapper you must install the Expect extension available from PECL.

Streams opened via the expect:// wrapper provide access to process'es stdio, stdout and stderr via PTY.

Tabella M-12. Wrapper Summary

AttributeSupported
Restricted by allow_url_fopen.No
Allows ReadingYes
Allows WritingYes
Allows AppendingYes
Allows Simultaneous Reading and WritingNo
Supports stat()No
Supports unlink()No
Supports rename()No
Supports mkdir()No
Supports rmdir()No


Appendice N. List of Available Filters

The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.

It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.

For a list of filters installed in your version of PHP use stream_get_filters().


String Filters

Each of these filters does precisely what their name implies and correspond to the behavior of a built-in php string handling function. For more information on a given filter, refer to the manual page for the corresponding function.

string.rot13 (since PHP 4.3.0) Use of this filter is equivalent to processing all stream data through the str_rot13() function.

Esempio N-1. string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs:  Guvf vf n grfg.   */
?>

string.toupper (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtoupper() function.

Esempio N-2. string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs:  THIS IS A TEST.   */
?>

string.tolower (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtolower() function.

Esempio N-3. string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs:  this is a test.   */
?>

string.strip_tags (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strip_tags() function. It accepts parameters in one of two forms: Either as a string containing a list of tags similar to the second parameter of the strip_tags() function, or as an array of tag names.

Esempio N-4. string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */
?>

Conversion Filters

Like the string.* filters, the convert.* filters perform actions similar to their names. The convert filters were added with PHP 5.0.0. For more information on a given filter, refer to the manual page for the corresponding function.

convert.base64-encode and convert.base64-decode Use of these filters are equivalent to processing all stream data through the base64_encode() and base64_decode() functions respectively. convert.base64-encode supports parameters given as an associative array. If line-length is given, the base64 output will be split into chunks of line-length characters each. If line-break-chars is given, each chunk will be delimited by the characters given. These parameters give the same effect as using base64_encode() with chunk_split().

Esempio N-5. convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs:  This is a test.  */
?>

convert.quoted-printable-encode and convert.quoted-printable-decode Use of the decode version of this filter is equivalent to processing all stream data through the quoted_printable_decode() functions. There is no function equivalent to convert.quoted-printable-encode. convert.quoted-printable-encode supports parameters given as an associative array. In addition to the parameters supported by convert.base64-encode, convert.quoted-printable-encode also supports boolean arguments binary and force-encode-first. convert.base64-decode only supports the line-break-chars parameter as a type-hint for striping from the encoded payload.

Esempio N-6. convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Outputs:  =This is a test.=0A  */
?>

Compression Filters

While the Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.

Nota: Compression filters do not generate headers and trailers used by commandline utilites such as gzip. They only compress and decompress the payload portions of compressed data streams.

zlib.deflate (compression) and zlib.inflate (decompression) are implementations of the compression methods described in RFC 1951. The deflate filter takes up to three parameters passed as an associative array. level describes the compression strength to use (1-9). Higher numbers will generally yield smaller payloads at the cost of additional processing time. Two special compression levels also exist: 0 (for no compression at all), and -1 (zlib internal default -- currently 6). window is the base-2 log of the compression loopback window size. Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory, while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint. Default window size is currently 15. memory is a scale indicating how much work memory should be allocated. Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation affects speed only and does not impact the size of the generated payload.

Nota: Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).

zlib.* compression filters are available with PHP as of version 5.1.0 if zlib support is enabled. They are also available as a backport in version 5.0.x by installing the zlib_filter package from PECL. These filters are not available for PHP 4.

Esempio N-7. zlib.deflate and zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.

 */
?>

Esempio N-8. zlib.deflate simple

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.

 */
?>

bzip2.compress and bzip2.decompress work in the same manner as the zlib filters described above. The bzip2.compress filter accepts up to two parameters given as elements of an associative array: blocks is an integer value from 1 to 9 specifying the number of 100kbyte blocks of memory to allocate for workspace. work is also an integer value ranging from 0 to 250 indicating how much effort to expend using the normal compression method before falling back on a slower, but more reliable method. Tuning this parameter effects only compression speed. Neither size of compressed output nor memory usage are changed by this setting. A work factor of 0 instructs the bzip library to use an internal default. The bzip2.decompress filter only accepts one parameter, which can be passed as either an ordinary boolean value, or as the small element of an associative array. small, when set to a TRUE value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.

bzip2.* compression filters are available with PHP as of version 5.1.0 if bz2 support is enabled. They are also available as a backport in version 5.0.x by installing the bz2_filter package from PECL. These filters are not available for PHP 4.

Esempio N-9. bzip2.compress and bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "The original file is " . filesize('LICENSE') . " bytes long.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";

/* Generates output:

The original text is 3288 characters long.
The compressed file is 1488 bytes long.

 */
?>

Encryption Filters

mcrypt.* and mdecrypt.* provide symmetric encryption and decryption using libmcrypt. Both sets of filters support the same algorithms available to mcrypt extension in the form of mcrypt.ciphername where ciphername is the name of the cipher as it would be passed to mcrypt_module_open(). The following five filter parameters are also available:

Tabella N-1. mcrypt filter parameters

ParameterRequired?DefaultSample Values
modeOptionalcbccbc, cfb, ecb, nofb, ofb, stream
algorithms_dirOptionalini_get('mcrypt.algorithms_dir')Location of algorithms modules
modes_dirOptionalini_get('mcrypt.modes_dir')Location of modes modules
ivRequiredN/ATypically 8, 16, or 32 bytes of binary data. Depends on cipher
keyRequiredN/ATypically 8, 16, or 32 bytes of binary data. Depends on cipher

Esempio N-10. Encrypting file output using 3DES

<?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) . 
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secert-file.enc', 'wb');
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'Secret secret secret data');
fclose($fp);
?>

Esempio N-11. Reading an encrypted file

<?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) . 
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secert-file.enc', 'rb');
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_WRITE, $opts);
$data = rtrim(stream_get_contents($fp));
fclose($fp);

echo $data;
?>

Appendice O. List of Supported Socket Transports

The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Sockets Extension.

For a list of transports installed in your version of PHP use stream_get_transports().


Internet Domain: TCP, UDP, SSL, and TLS

PHP 3, PHP 4, PHP 5. ssl:// & tls:// since PHP 4.3.0 sslv2:// & sslv3:// since PHP 5.0.2

Nota: If no transport is specified, tcp:// will be assumed.

  • 127.0.0.1

  • fe80::1

  • www.example.com

  • tcp://127.0.0.1

  • tcp://fe80::1

  • tcp://www.example.com

  • udp://www.example.com

  • ssl://www.example.com

  • sslv2://www.example.com

  • sslv3://www.example.com

  • tls://www.example.com

Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.

  • tcp://127.0.0.1:80

  • tcp://[fe80::1]:80

  • tcp://www.example.com:80

IPv6 numeric addresses with port numbers: In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.

The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which include SSL encryption. Since PHP 4.3.0 OpenSSL support must be statically compiled into PHP, since PHP 5.0.0 it may be compiled as a module or statically.

ssl:// will attempt to negotiate an SSL V2, or SSL V3 connection depending on the capabilities and preferences of the remote host. sslv2:// and sslv3:// will select the SSL V2 or SSL V3 protocol explicitly.

Tabella O-1. Context options for ssl:// and tls:// transports (since PHP 4.3.2)

NameUsageDefault
verify_peer TRUE or FALSE. Require verification of SSL certificate used. FALSE
allow_self_signed TRUE or FALSE. Allow self-signed certificates. FALSE
cafile Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option to authenticate the identity of the remote peer.  
capath If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a suitable certificate. capath must be a correctly hashed certificate directory.  
local_cert Path to local certificate file on filesystem. It must be a PEM encoded file which contains your certificate and private key. It can optionally contain the certificate chain of issuers.  
passphrase Passphrase with which your local_cert file was encoded.  
CN_match Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail.  

Nota: Because ssl:// is the underlying transport for the https:// and ftps:// wrappers, any context options which apply to ssl:// also apply to https:// and ftps://.


Unix Domain: Unix and UDG

unix:// since PHP 3, udg:// since PHP 5

  • unix:///tmp/mysock

  • udg:///tmp/mysock

unix:// provides access to a socket stream connection in the Unix domain. udg:// provides an alternate transport to a Unix domain socket using the user datagram protocol.

Unix domain sockets, unlike Internet domain sockets, do not expect a port number. In the case of fsockopen() the portno parameter should be set to 0.


Appendice P. PHP type comparison tables

The following tables demonstrate behaviors of PHP types and comparison operators, for both loose and strict comparisons. This supplemental is also related to the manual section on type juggling. Inspiration was provided by various user comments and by the work over at BlueShoes.

Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an integer. FALSE is a boolean while "false" is a string.

Nota: HTML Forms do not pass integers, floats, or booleans; they pass strings. To find out if a string is numeric, you may use is_numeric().

Nota: Simply doing if ($x) while $x is undefined will generate an error of level E_NOTICE. Instead, consider using empty() or isset() and/or initialize your variables.

Tabella P-1. Comparisons of $x with PHP functions

Expressiongettype()empty()is_null()isset()boolean : if($x)
$x = "";stringTRUEFALSETRUEFALSE
$x = NULLNULLTRUETRUEFALSEFALSE
var $x;NULLTRUETRUEFALSEFALSE
$x is undefinedNULLTRUETRUEFALSEFALSE
$x = array();arrayTRUEFALSETRUEFALSE
$x = false;booleanTRUEFALSETRUEFALSE
$x = true;booleanFALSEFALSETRUETRUE
$x = 1;integerFALSEFALSETRUETRUE
$x = 42;integerFALSEFALSETRUETRUE
$x = 0;integerTRUEFALSETRUEFALSE
$x = -1;integerFALSEFALSETRUETRUE
$x = "1";stringFALSEFALSETRUETRUE
$x = "0";stringTRUEFALSETRUEFALSE
$x = "-1";stringFALSEFALSETRUETRUE
$x = "php";stringFALSEFALSETRUETRUE
$x = "true";stringFALSEFALSETRUETRUE
$x = "false";stringFALSEFALSETRUETRUE

Tabella P-2. Loose comparisons with ==

 TRUEFALSE10-1"1""0""-1"NULLarray()"php"
TRUETRUEFALSETRUEFALSETRUETRUEFALSETRUEFALSEFALSETRUE
FALSEFALSETRUEFALSETRUEFALSEFALSETRUEFALSETRUETRUEFALSE
1TRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
0FALSETRUEFALSETRUEFALSEFALSETRUEFALSETRUEFALSETRUE
-1TRUEFALSEFALSEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSE
"1"TRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
"0"FALSETRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSE
"-1"TRUEFALSEFALSEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSE
NULLFALSETRUEFALSETRUEFALSEFALSEFALSEFALSETRUETRUEFALSE
array()FALSETRUEFALSEFALSEFALSEFALSEFALSEFALSETRUETRUEFALSE
"php"TRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSETRUE

Tabella P-3. Strict comparisons with ===

 TRUEFALSE10-1"1""0""-1"NULLarray()"php"
TRUETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
FALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
1FALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
0FALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
-1FALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSE
"1"FALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
"0"FALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSE
"-1"FALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSE
NULLFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSE
array()FALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSE
"php"FALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUE

PHP 3.0 note: The string value "0" was considered non-empty in PHP 3, this behavior changed in PHP 4 where it's now seen as empty.


Appendice Q. List of Parser Tokens

Various parts of the PHP language are represented internally by types like T_SR. PHP outputs identifiers like this one in parse errors, like "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

You're supposed to know what T_SR means. For everybody who doesn't know that, here is a table with those identifiers, PHP-syntax and references to the appropriate places in the manual.

Tabella Q-1. Tokens

TokenSyntaxReference
T_AND_EQUAL&=assignment operators
T_ARRAYarray()array(), array syntax
T_ARRAY_CAST(array)type-casting
T_ASasforeach
T_BAD_CHARACTER anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d)
T_BOOLEAN_AND&&logical operators
T_BOOLEAN_OR||logical operators
T_BOOL_CAST(bool) or (boolean)type-casting
T_BREAKbreakbreak
T_CASEcaseswitch
T_CHARACTER  
T_CLASSclassclasses and objects
T_CLONEcloneclasses and objects. PHP 5 only.
T_CLOSE_TAG?> or %> 
T_COMMENT// or #, and /* */ on PHP 5comments
T_CONCAT_EQUAL.=assignment operators
T_CONSTconst 
T_CONSTANT_ENCAPSED_STRING"foo" or 'bar'string syntax
T_CONTINUEcontinue 
T_CURLY_OPEN  
T_DEC--incrementing/decrementing operators
T_DECLAREdeclaredeclare
T_DEFAULTdefaultswitch
T_DIV_EQUAL/=assignment operators
T_DNUMBER0.12, etcfloating point numbers
T_DOC_COMMENT/** */PHPDoc style comments (PHP 5 only)
T_DOdodo..while
T_DOLLAR_OPEN_CURLY_BRACES${complex variable parsed syntax
T_DOUBLE_ARROW=>array syntax
T_DOUBLE_CAST(real), (double) or (float)type-casting
T_ECHOechoecho()
T_ELSEelseelse
T_ELSEIFelseifelseif
T_EMPTYemptyempty()
T_ENCAPSED_AND_WHITESPACE  
T_ENDDECLAREenddeclaredeclare, alternative syntax
T_ENDFORendforfor, alternative syntax
T_ENDFOREACHendforeachforeach, alternative syntax
T_ENDIFendifif, alternative syntax
T_ENDSWITCHendswitchswitch, alternative syntax
T_ENDWHILEendwhilewhile, alternative syntax
T_END_HEREDOC heredoc syntax
T_EVALeval()eval()
T_EXITexit or dieexit(), die()
T_EXTENDSextendsextends, classes and objects
T_FILE__FILE__constants
T_FORforfor
T_FOREACHforeachforeach
T_FUNCTIONfunction or cfunctionfunctions
T_GLOBALglobalvariable scope
T_IFifif
T_INC++incrementing/decrementing operators
T_INCLUDEinclude()include()
T_INCLUDE_ONCEinclude_once()include_once()
T_INLINE_HTML  
T_INSTANCEOFinstanceoftype operators (PHP5 only)
T_INT_CAST(int) or (integer)type-casting
T_ISSETisset()isset()
T_IS_EQUAL==comparison operators
T_IS_GREATER_OR_EQUAL>=comparison operators
T_IS_IDENTICAL===comparison operators
T_IS_NOT_EQUAL!= or <>comparison operators
T_IS_NOT_IDENTICAL!==comparison operators
T_IS_SMALLER_OR_EQUAL<=comparison operators
T_LINE__LINE__constants
T_LISTlist()list()
T_LNUMBER123, 012, 0x1ac, etcintegers
T_LOGICAL_ANDandlogical operators
T_LOGICAL_ORorlogical operators
T_LOGICAL_XORxorlogical operators
T_MINUS_EQUAL-=assignment operators
T_ML_COMMENT/* and */comments (PHP 4 only)
T_MOD_EQUAL%=assignment operators
T_MUL_EQUAL*=assignment operators
T_NEWnewclasses and objects
T_NUM_STRING  
T_OBJECT_CAST(object)type-casting
T_OBJECT_OPERATOR->classes and objects
T_OLD_FUNCTIONold_functionold_function
T_OPEN_TAG<?php, <? or <%escaping from HTML
T_OPEN_TAG_WITH_ECHO<?= or <%=escaping from HTML
T_OR_EQUAL|=assignment operators
T_PAAMAYIM_NEKUDOTAYIM::::. Also defined as T_DOUBLE_COLON.
T_PLUS_EQUAL+=assignment operators
T_PRINTprint()print()
T_PRIVATEprivateclasses and objects. PHP 5 only.
T_PUBLICpublicclasses and objects. PHP 5 only.
T_PROTECTEDprotectedclasses and objects. PHP 5 only.
T_REQUIRErequire()require()
T_REQUIRE_ONCErequire_once()require_once()
T_RETURNreturnreturning values
T_SL<<bitwise operators
T_SL_EQUAL<<=assignment operators
T_SR>>bitwise operators
T_SR_EQUAL>>=assignment operators
T_START_HEREDOC<<<heredoc syntax
T_STATICstaticvariable scope
T_STRING  
T_STRING_CAST(string)type-casting
T_STRING_VARNAME  
T_SWITCHswitchswitch
T_UNSETunset()unset()
T_UNSET_CAST(unset)(not documented; casts to NULL)
T_USEuse(not implemented)
T_VARvarclasses and objects
T_VARIABLE$foovariables
T_WHILEwhilewhile, do..while
T_WHITESPACE  
T_XOR_EQUAL^=assignment operators
T_FUNC_C__FUNCTION__constants, since PHP 4.3.0
T_CLASS_C__CLASS__constants, since PHP 4.3.0

See also token_name().


Appendice R. Informazioni sul manuale

Formati

Il manuale di PHP è distribuito in diversi formati. Questi formati possono essere divisi in due gruppi: formati leggibili online e pacchetti scaricabili.

Nota: Alcuni editori hanno reso disponibile una versione di questo manuale adatta alla stampa. Noi sconsigliamo questo tipo di manuali, in quanto tendono a diventare obsoleti molto rapidamente.

Puoi leggere il manuale online sul sito PHP.net e sui numerosi siti mirror. Per ottenere risultati migliori, dovresti scegliere il mirror a te più vicino. Puoi leggere il manuale sia in un formato HTML adatto alla stampa, sia in un formato HTML che integri le potenzialità "look and feel" del PHP.

Due vantaggio del manuale online sulla maggior parte dei formati offline sono l'integrazione dei contributi degli utenti e le scorciatoie URL che permettono di ottenere rapidamente la pagina del manuale desiderata. Ovviamente, per poter visualizzare il manuale online, dovrai essere collegato ad internet.

Ci sono diversi tipi di manuale scaricabili, e il formato più appropriato alle tue esigenze dipende dal tipo di sistema operativo che usi e dal tuo personale modo di leggere. Per informazioni su come il manuale viene generato in così tanti formati, leggi la sezione 'Come generiamo i formati' di questa appendice.

Il formato più adatto a diversi tipi di sistemi operativi è l'HTML. Il formato HTML è disponibile sia come unica pagina HTML, sia come pacchetto di file univoci per ogni sezione (cioè qualche migliaio di file). Queste versioni sono fornite compresse, pertanto occorre disporre di utility di decompressione per ottenere i file contenuti negli archivi.

Un altro formato adatto a diversi tipi di sistemi operativi e alla stampa è il formato PDF, conosciuto anche come Adobe Acrobat. Ma prima di scaricare questo tipo di formato e iniziare a stampare il manuale, sappi che è contiene oltre 2000 pagine e che viene aggiornato e corretto frequentemente

Nota: Se ancora non hai un programma in grado di leggere il formato PDF, hai bisogno di scaricare Adobe Acrobat Reader.

Per le piattaforme Windows, la versione HTML Help per Windows del manuale fornisce contenuti utilizzabili con le applicazioni HTML Help per Windows. Questo tipo di versione è fornita con un motore di ricerca per tutto il contenuto, con un indice completo e con la possibilità di salvare le ricerche. Molte versioni di manuale PHP per Windows integrano anche questa versione della documentazione, per garantire un accesso più semplice. Sono disponibili diversi visualizzatori CHM per Linux. Alcuni esempi: xCHM oppure GnoCHM.

Inoltre esiste una versione CHM estesa, che viene aggiornata con frequenza minore, ma fornisce maggiori caratteristiche. E' disponibile soltanto su Microsoft Windows a causa della tecnologia utilizzata per realizzare queste pagine.


Contributi degli utenti

I contributi degli utenti giocano un ruolo importante nello sviluppo di questo manuale. Possiamo includere questi feedback nel testo principale del manuale permettendo agli utenti di contribuire con esempi, avvertimenti e chiarimenti riguardo a diversi tipi di browser. I contributi inviati dagli utenti sono visibili, così come sono stati inviati, nel formato online del manuale ed in alcuni dei formati scaricabili.

Nota: I contributi degli utenti NON sono controllati prima di essere messi online, quindi la chiarezza del contenuto, gli esempi di codice o l'esattezza stessa dei contributi non puù essere garantita. (E non c'è alcuna garanzia sulla qualità o sull'esattezza del testo dello stesso manuale.)

Nota: Dal punto di vista della licenza i contributi degli utenti sono considerati parte del manuale PHP, e quindi coperti dalla stessa licenza che si applica a questa cocumentazione (Open Publication License al momento). Per maggiori dettagli vedere la pagina Manual's Copyright.


Come leggere la definizione di una funzione (prototipo)

Nel manuale ciascuna funzione è documentata per un rapido riferimento. Conoscendo come leggere e capendo il testo si è in grado di apprendere il PHP molto più facilmente. Piuttosto che appoggiarsi sugli esempi o sul copia e incolla, preferirai sicuramente sapere come leggere la definizione di una funzione. Cominciamo:

Pre-requisito: comprensione di base dei tipi di variabili: Sebbene il PHP sia un linguaggio poco tipizzato (loosely typed), è importante avere una conoscenza di base delle tipologie di variabili per il loro importante significato.

La definizione della funzione ci dice quale tipo di valore viene restituito. Utilizziamo la definizione di strlen() come nostro primo esempio:

strlen
 
(PHP 3, PHP 4, PHP 5)
strlen -- Restituisce la lunghezza di una stringa
 
Description
int strlen ( string str )
 
Restituisce la lunghezza di una stringa.

Tabella R-1. Spiegazione della definizione di una funzione

ParteDescrizione
strlen Nome della funzione.
(PHP 3, PHP 4, PHP 5) strlen() è disponibile in tutte le versioni di PHP 3, PHP 4 e PHP 5
int Tipo di valore restituito dalla funzione, il quale è un intero (la lunghezza di una stringa si misura in numei).
( string str ) Il primo (ed in questo caso unico) parametro/argomento per questa funzione si chiama str, ed è una stringa.

Si potrebbe riscrivere la funzione precedente in modo generico:

returned type    function name    ( parameter type   parameter name )

Diverse funzioni hanno diversi parametri, tipo in_array(). Il loro prototipo è:

bool in_array ( mixed needle, array haystack [, bool strict])

Cosa significa? in_array() restituisce un valore boolean value, TRUE se riesce (se il parametro needle viene trovato in haystack) oppure FALSE se fallisce (se il parametro needle non viene trovato in haystack). Il primo parametro si chiama needle e può essere di diversi tipi, pertanto lo chiameremo "mixed". Questo parametro needle di tipo mixed (che indica che il valore che stiamo cercando) può essere sia un valore scalare (stringa, intero, oppure float), sia una matrice. haystack (che indica la variabile in cui cercare) è il secondo parametro. Il terzo parametro opzionale è chiamato strict. Tutti i parametri opzionali sono racchiusi tra parentesi [ quadre ]. Il manuale indica che il valore di defualt per strict è il boolean FALSE. Vedere le pagine del manuale di ciascuna funzione per i dettagli di come funziona.

Esistono anche funzioni con complesse informazioni sulla versione PHP. Ad esempio la funzione html_entity_decode():

(PHP 4 >= 4.3.0, PHP 5)

Questo significa che questa funzione non era disponibile con il PHP 3, ed è soltanto disponibile a partire dalla release PHP 4.3.0.


Le versioni di PHP documentate in questo manuale

Questa documentazione contiene informazioni sulle versioni di PHP 4 e 5, con note sulla migrazione e sulla compatibilità con PHP 3. Il comportamento, i parametri, i valori restituiti ed altre modifiche tra le differenti versioni di PHP sono documentate nelle note e nel testo del manuale.

Si può anche trovare la documentazione sulla versione CVS del PHP, che indica l'ultima verisone in fase di sviluppo, disponibile tramite il sistema di gestione delle versioni CVS. Se non si è sviluppatori del PHP, e non si è ansiosi di utilizzare l'ultimissima versione di PHP, le caratteristiche codificate come "available in CVS" non sono accessibili. Queste caratteristiche, riteniamo, saranno disponibili nella successiva versione stabile del PHP. Se si desidera scaricare la versione CVS vedere la pagina accesso anonimo al CVS.

Si può anche incontrare documentazione di versioni di PHP non ancora rilasciate (tipo PHP 5.0.0 mentre l'ultima versione stabile rilasciata è la 4.3.x). Il più delle volte non si tratta di un errore nella documentazione. Spesso si aggiungono informazioni per caratteristiche non disponibili nella versione corrente di PHP, ma che lo saranno in una versione futura gà nota. In genere il PHP aggiunge nuove caratteristiche nelle release principali, negli altri casi si tratta di correzione di problemi. Nella codifica della versione A.B.C, le release principali aggiornano il numero A o B, mentre le correzioni aggiornano il numero C. Così, ad esempio, è possibile che sia documentata una caratteristica disponibile in PHP x.1.x quando l'ultima versione rilasciata sia PHP x.0.x. Inoltre il manuale è scritto con i verbi al tempo presente, e non futuro

In diverse occasioni il manuale del PHP presenta dei "valori di default" per le configurazioni di PHP. Questi valori sono basati sul php.ini-dist e non sul php.ini-recommended. Inoltre essi si riferiscono all'ultima versione di PHP. Vedere la pagina di appendice parametri di configurazione del PHP per dettagli e modifiche su questi valori.


Come trovare più informazioni sul PHP

Lo scopo di questo manuale non è quello di fornire istruzioni sulla pratica in generale della programmazione. Se questa è la tua prima visita, o se sei un programmatore alle prime armi, potresti trovare difficile imparare a programmare usando solo questo manuale. Forse stai cercando un testo più adatto ai principianti: puoi trovare una lista di libri sul PHP su http://www.php.net/books.php.

Ci sono diverse mailing list attive per discutere su tutti gli aspetti del programmare con il PHP. Se sei bloccato con un problema per il quale non riesci a trovare una soluzione con le tue sole conoscenze, potresti trovare l'aiuto di qualcuno più esperto in una di queste mailing list. Puoi trovare un elenco di mailing list con link agli arretrati e altre risorse utili online alle pagine di spupporto di PHP.net. Inoltre, sulla pagina dei link in PHP.net troverai un elenco di siti dedicati al PHP con articoli, forum di discussione e numerosi script.


Come aiutare a migliorare la documentazione

Ci sono tre modi per aiutarci a migliorare questa documentazione.

Se trovi errori all'interno di questo manuale, in qualsiasi lingua esso sia, comunicacelo usando lo stesso sistema per segnalare bug su http://bugs.php.net/, classificando il bug come "Errore nella documentazione". Allo stesso indirizzo puoi anche segnalare problemi relativi ad uno specifico formato di manuale.

Nota: Sei però pregato di non abusare del sistema per segnalare bug spedendo richieste di aiuto. Se proprio sei in difficoltà, usa le mailing list o le community segnalate prima.

Contribuendo con l'invio di note, puoi fornire ulteriori esempi, avvertimenti e chiarificazioni per altri lettori, ma sei pregato di non segnalare bug usando il sistema di invio delle note. Per saperne di più sul sistema di invio delle note puoi leggere la sezione Sistema di invio delle note di questa appendice.

Se conosci l'inglese ed altre lingue stere, puoi aiutare nella traduzione del manuale. Se desideri iniziare una nuova traduzione, o aiutare un progetto di traduzione, leggi la pagina http://cvs.php.net/co.php/phpdoc/howto/howto.html.tar.gz.

Il progetto di documentazione PHP usa un canale IRC tramite il quale si può discutere con gli autori del manuale, indicare alcuni aspetti del manuale sui quali vuole essere di aiuto. Questo canale è #phpdoc su irc.freenode.net.


Come generiamo i diversi formati

Questo manuale è scritto in XML usando il DocBook XML DTD e usando DSSSL (Document Style and Semantic Specification Language) per la formattazione, e sperimentalmente XSLT (Extensible Stylesheet Language Transformations) per il mantenimento e la formattazione.

Usare l'XML come formato originale rende possibile generare diversi tipi di formato partendo da un unico sorgente, mantenendo solo un sorgente per tutti i diversi formati. Gli strumenti utilizzati per formattare le versioni inHTML e TeX sono Jade, scritto da James Clark, e The Modular DocBook Stylesheet, scritto da Norman Walsh. Per generare la versione HTML Help per Windows usiamo Microsoft HTML Help Workshop e, ovviamente, anche PHP stesso per qualche conversione addizionale e per la formattazione.

Puoi scaricare il manuale in diverse lingue e formati, compresi l'HTML, il PDF, il PalmPilot DOC, il PalmPilot iSilo e l'HTML Help per Windows da http://www.php.net/docs.php. Nota, per motivi tecnici, non tutti i formati sono disponibili.

Puoi trovare più informazioni su come scaricare il sorgente XML di questo documento su http://cvs.php.net/. La documentazione e racchiusa in moduli phpdoc.


Traduzioni

Il manuale PHP è disponibile non solo in vari formati, am anche in varie lingue. Il testo originale è scritto in inglese, mentre gruppi di persone da tutto il modno si occupano di tradurlo nelle rispettive lingue. Se non esiste la traduzione per un specifico capitolo o funzione la procedura di compila del manuale utilizza la versione inglese del capitolo.

Le persone che si occupano della traduzioni iniziano dal codice XML disponibile da http://cvs.php.net/ e da questo partono per la traduzione nella propria lingua. Non si usa il codice HTML, il testo normale, o la versione PDF. E' il sistema di compila che si occupa della conversione da XML ai vari formati.

Nota: Se si desidera aiutare la traduzione nella propria lingua, occorre entrare in contatto con il gruppo di traduzione/documentazione tramite la mailing list phpdoc: inviare una mail vuota a phpdoc-subscribe@lists.php.net. L'indirizzo della mailing list è phpdoc@lists.php.net. Indicare nel messaggio che si è interessati alla traduzione del manuale in una determinata lingua e si sarà contattati da qualcuno che aiuterà o a cominciare una nuova traduzione o a entrare in contatto con il gruppo di documentazione della propria lingua.

Al momento il manuale è disponibile, anche parzialmente, nelle seguenti lingue: Brasiliano Portoghese, Cinese (semplificato), Cinese (Hong Kong Cantonese), Cinese (Tradizionale), Ceco, Olandese, Finlandese, Francese, Tedesco, Greco, Ebreo, Ungherese, Italiano, Giapponese, Coreano, Polacco, Rumeno, Russo, Slovacco, Sloveno, Spagnolo, Svedese e Turco.

Tutte le versioni possono essere scaricate da: http://www.php.net/docs.php.


Appendice S. Open Publication License

v1.0, 8 June 1999


I. REQUIREMENTS ON BOTH UNMODIFIED AND MODIFIED VERSIONS

The Open Publication works may be reproduced and distributed in whole or in part, in any medium physical or electronic, provided that the terms of this license are adhered to, and that this license or an incorporation of it by reference (with any options elected by the author(s) and/or publisher) is displayed in the reproduction.

Proper form for an incorporation by reference is as follows:

Copyright (c) <year> by <author's name or designee>. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, vX.Y or later (the latest version is presently available at http://www.opencontent.org/openpub/

The reference must be immediately followed with any options elected by the author(s) and/or publisher of the document (see section VI). Commercial redistribution of Open Publication-licensed material is permitted. Any publication in standard (paper) book form shall require the citation of the original publisher and author. The publisher and author's names shall appear on all outer surfaces of the book. On all outer surfaces of the book the original publisher's name shall be as large as the title of the work and cited as possessive with respect to the title.


II. COPYRIGHT

The copyright to each Open Publication is owned by its author(s) or designee.


III. SCOPE OF LICENSE

The following license terms apply to all Open Publication works, unless otherwise explicitly stated in the document.

Mere aggregation of Open Publication works or a portion of an Open Publication work with other works or programs on the same media shall not cause this license to apply to those other works. The aggregate work shall contain a notice specifying the inclusion of the Open Publication material and appropriate copyright notice.

SEVERABILITY. If any part of this license is found to be unenforceable in any jurisdiction, the remaining portions of the license remain in force.

NO WARRANTY. Open Publication works are licensed and provided "as is" without warranty of any kind, express or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose or a warranty of non-infringement.


IV. REQUIREMENTS ON MODIFIED WORKS

All modified versions of documents covered by this license, including translations, anthologies, compilations and partial documents, must meet the following requirements:

  1. The modified version must be labeled as such.

  2. The person making the modifications must be identified and the modifications dated.

  3. Acknowledgement of the original author and publisher if applicable must be retained according to normal academic citation practices.

  4. The location of the original unmodified document must be identified.

  5. The original author's (or authors') name(s) may not be used to assert or imply endorsement of the resulting document without the original author's (or authors') permission.


V. GOOD-PRACTICE RECOMMENDATIONS

In addition to the requirements of this license, it is requested from and strongly recommended of redistributors that:

  1. If you are distributing Open Publication works on hardcopy or CD-ROM, you provide email notification to the authors of your intent to redistribute at least thirty days before your manuscript or media freeze, to give the authors time to provide updated documents. This notification should describe modifications, if any, made to the document.

  2. All substantive modifications (including deletions) be either clearly marked up in the document or else described in an attachment to the document.

  3. Finally, while it is not mandatory under this license, it is considered good form to offer a free copy of any hardcopy and CD-ROM expression of an Open Publication-licensed work to its author(s).


VI. LICENSE OPTIONS

The author(s) and/or publisher of an Open Publication-licensed document may elect certain options by appending language to the reference to or copy of the license. These options are considered part of the license instance and must be included with the license (or its incorporation by reference) in derived works.

A. To prohibit distribution of substantively modified versions without the explicit permission of the author(s). "Substantive modification" is defined as a change to the semantic content of the document, and excludes mere changes in format or typographical corrections.

To accomplish this, add the phrase `Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.' to the license reference or copy.

B. To prohibit any publication of this work or derivative works in whole or in part in standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder.

To accomplish this, add the phrase 'Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.' to the license reference or copy.


Appendice T. Indice delle Funzioni


Indice delle Funzioni

A

abs()
acos()
acosh()
addcslashes()
addslashes()
aggregate()
aggregate_info()
aggregate_methods()
aggregate_methods_by_list()
aggregate_methods_by_regexp()
aggregate_properties()
aggregate_properties_by_list()
aggregate_properties_by_regexp()
aggregation_info()
apache_child_terminate()
apache_get_modules()
apache_get_version()
apache_getenv()
apache_lookup_uri()
apache_note()
apache_request_headers()
apache_reset_timeout()
apache_response_headers()
apache_setenv()
apd_breakpoint()
apd_callstack()
apd_clunk()
apd_continue()
apd_croak()
apd_dump_function_table()
apd_dump_persistent_resources()
apd_dump_regular_resources()
apd_echo()
apd_get_active_symbols()
apd_set_pprof_trace()
apd_set_session()
apd_set_session_trace()
apd_set_socket_session_trace()
array()
array_change_key_case()
array_chunk()
array_combine()
array_count_values()
array_diff()
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
array_diff_ukey()
array_fill()
array_filter()
array_flip()
array_intersect()
array_intersect_assoc()
array_intersect_key()
array_intersect_uassoc()
array_intersect_ukey()
array_key_exists()
array_keys()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_pad()
array_pop()
array_push()
array_rand()
array_reduce()
array_reverse()
array_search()
array_shift()
array_slice()
array_splice()
array_sum()
array_udiff()
array_udiff_assoc()
array_udiff_uassoc()
array_uintersect()
array_uintersect_assoc()
array_uintersect_uassoc()
array_unique()
array_unshift()
array_values()
array_walk()
array_walk_recursive()
ArrayIterator::current()
ArrayIterator::key()
ArrayIterator::next()
ArrayIterator::rewind()
ArrayIterator::seek()
ArrayIterator::valid()
ArrayObject::__construct()
ArrayObject::append()
ArrayObject::count()
ArrayObject::getIterator()
ArrayObject::offsetExists()
ArrayObject::offsetGet()
ArrayObject::offsetSet()
ArrayObject::offsetUnset()
arsort()
ascii2ebcdic()
asin()
asinh()
asort()
aspell_check()
aspell_check_raw()
aspell_new()
aspell_suggest()
assert()
assert_options()
atan()
atan2()
atanh()

C

CachingIterator::__toString()
CachingIterator::hasNext()
CachingIterator::next()
CachingIterator::rewind()
CachingIterator::valid()
CachingRecursiveIterator::getChildren()
CachingRecursiveIterator::hasChildren()
cal_days_in_month()
cal_from_jd()
cal_info()
cal_to_jd()
call_user_func()
call_user_func_array()
call_user_method()
call_user_method_array()
ccvs_add()
ccvs_auth()
ccvs_command()
ccvs_count()
ccvs_delete()
ccvs_done()
ccvs_init()
ccvs_lookup()
ccvs_new()
ccvs_report()
ccvs_return()
ccvs_reverse()
ccvs_sale()
ccvs_status()
ccvs_textvalue()
ccvs_void()
ceil()
chdir()
checkdate()
checkdnsrr()
chgrp()
chmod()
chop()
chown()
chr()
chroot()
chunk_split()
class_exists()
class_implements()
class_parents()
classkit_import()
classkit_method_add()
classkit_method_copy()
classkit_method_redefine()
classkit_method_remove()
classkit_method_rename()
clearstatcache()
closedir()
closelog()
com()
com_addref()
com_create_guid()
com_event_sink()
com_get()
com_get_active_object()
com_invoke()
com_isenum()
com_load()
com_load_typelib()
com_message_pump()
com_print_typeinfo()
com_propget()
com_propput()
com_propset()
com_release()
com_set()
compact()
connection_aborted()
connection_status()
connection_timeout()
constant()
convert_cyr_string()
convert_uudecode()
convert_uuencode()
copy()
cos()
cosh()
count()
count_chars()
cpdf_add_annotation()
cpdf_add_outline()
cpdf_arc()
cpdf_begin_text()
cpdf_circle()
cpdf_clip()
cpdf_close()
cpdf_closepath()
cpdf_closepath_fill_stroke()
cpdf_closepath_stroke()
cpdf_continue_text()
cpdf_curveto()
cpdf_end_text()
cpdf_fill()
cpdf_fill_stroke()
cpdf_finalize()
cpdf_finalize_page()
cpdf_global_set_document_limits()
cpdf_import_jpeg()
cpdf_lineto()
cpdf_moveto()
cpdf_newpath()
cpdf_open()
cpdf_output_buffer()
cpdf_page_init()
cpdf_place_inline_image()
cpdf_rect()
cpdf_restore()
cpdf_rlineto()
cpdf_rmoveto()
cpdf_rotate()
cpdf_rotate_text()
cpdf_save()
cpdf_save_to_file()
cpdf_scale()
cpdf_set_action_url()
cpdf_set_char_spacing()
cpdf_set_creator()
cpdf_set_current_page()
cpdf_set_font()
cpdf_set_font_directories()
cpdf_set_font_map_file()
cpdf_set_horiz_scaling()
cpdf_set_keywords()
cpdf_set_leading()
cpdf_set_page_animation()
cpdf_set_subject()
cpdf_set_text_matrix()
cpdf_set_text_pos()
cpdf_set_text_rendering()
cpdf_set_text_rise()
cpdf_set_title()
cpdf_set_viewer_preferences()
cpdf_set_word_spacing()
cpdf_setdash()
cpdf_setflat()
cpdf_setgray()
cpdf_setgray_fill()
cpdf_setgray_stroke()
cpdf_setlinecap()
cpdf_setlinejoin()
cpdf_setlinewidth()
cpdf_setmiterlimit()
cpdf_setrgbcolor()
cpdf_setrgbcolor_fill()
cpdf_setrgbcolor_stroke()
cpdf_show()
cpdf_show_xy()
cpdf_stringwidth()
cpdf_stroke()
cpdf_text()
cpdf_translate()
crack_check()
crack_closedict()
crack_getlastmessage()
crack_opendict()
crc32()
create_function()
crypt()
ctype_alnum()
ctype_alpha()
ctype_cntrl()
ctype_digit()
ctype_graph()
ctype_lower()
ctype_print()
ctype_punct()
ctype_space()
ctype_upper()
ctype_xdigit()
curl_close()
curl_copy_handle()
curl_errno()
curl_error()
curl_exec()
curl_getinfo()
curl_init()
curl_multi_add_handle()
curl_multi_close()
curl_multi_exec()
curl_multi_getcontent()
curl_multi_info_read()
curl_multi_init()
curl_multi_remove_handle()
curl_multi_select()
curl_setopt()
curl_version()
current()
cybercash_base64_decode()
cybercash_base64_encode()
cybercash_decr()
cybercash_encr()
cyrus_authenticate()
cyrus_bind()
cyrus_close()
cyrus_connect()
cyrus_query()
cyrus_unbind()

D

date()
date_sunrise()
date_sunset()
dba_close()
dba_delete()
dba_exists()
dba_fetch()
dba_firstkey()
dba_handlers()
dba_insert()
dba_key_split()
dba_list()
dba_nextkey()
dba_open()
dba_optimize()
dba_popen()
dba_replace()
dba_sync()
dbase_add_record()
dbase_close()
dbase_create()
dbase_delete_record()
dbase_get_header_info()
dbase_get_record()
dbase_get_record_with_names()
dbase_numfields()
dbase_numrecords()
dbase_open()
dbase_pack()
dbase_replace_record()
dblist()
dbmclose()
dbmdelete()
dbmexists()
dbmfetch()
dbmfirstkey()
dbminsert()
dbmnextkey()
dbmopen()
dbmreplace()
dbplus_add()
dbplus_aql()
dbplus_chdir()
dbplus_close()
dbplus_curr()
dbplus_errcode()
dbplus_errno()
dbplus_find()
dbplus_first()
dbplus_flush()
dbplus_freealllocks()
dbplus_freelock()
dbplus_freerlocks()
dbplus_getlock()
dbplus_getunique()
dbplus_info()
dbplus_last()
dbplus_lockrel()
dbplus_next()
dbplus_open()
dbplus_prev()
dbplus_rchperm()
dbplus_rcreate()
dbplus_rcrtexact()
dbplus_rcrtlike()
dbplus_resolve()
dbplus_restorepos()
dbplus_rkeys()
dbplus_ropen()
dbplus_rquery()
dbplus_rrename()
dbplus_rsecindex()
dbplus_runlink()
dbplus_rzap()
dbplus_savepos()
dbplus_setindex()
dbplus_setindexbynumber()
dbplus_sql()
dbplus_tcl()
dbplus_tremove()
dbplus_undo()
dbplus_undoprepare()
dbplus_unlockrel()
dbplus_unselect()
dbplus_update()
dbplus_xlockrel()
dbplus_xunlockrel()
dbx_close()
dbx_compare()
dbx_connect()
dbx_error()
dbx_escape_string()
dbx_fetch_row()
dbx_query()
dbx_sort()
dcgettext()
dcngettext()
deaggregate()
debug_backtrace()
debug_print_backtrace()
debug_zval_dump()
debugger_off()
debugger_on()
decbin()
dechex()
decoct()
define()
define_syslog_variables()
defined()
deg2rad()
delete()
descriptor->free()
dgettext()
die()
dio_close()
dio_fcntl()
dio_open()
dio_read()
dio_seek()
dio_stat()
dio_tcsetattr()
dio_truncate()
dio_write()
dir()
DirectoryIterator::__construct()
DirectoryIterator::current()
DirectoryIterator::getATime()
DirectoryIterator::getChildren()
DirectoryIterator::getCTime()
DirectoryIterator::getFilename()
DirectoryIterator::getGroup()
DirectoryIterator::getInode()
DirectoryIterator::getMTime()
DirectoryIterator::getOwner()
DirectoryIterator::getPath()
DirectoryIterator::getPathname()
DirectoryIterator::getPerms()
DirectoryIterator::getSize()
DirectoryIterator::getType()
DirectoryIterator::isDir()
DirectoryIterator::isDot()
DirectoryIterator::isExecutable()
DirectoryIterator::isFile()
DirectoryIterator::isLink()
DirectoryIterator::isReadable()
DirectoryIterator::isWritable()
DirectoryIterator::key()
DirectoryIterator::next()
DirectoryIterator::rewind()
DirectoryIterator::valid()
dirname()
disk_free_space()
disk_total_space()
diskfreespace()
dl()
dngettext()
dns_check_record()
dns_get_mx()
dns_get_record()
dom_import_simplexml()
DOMAttr->isId()
DomAttribute->name()
DomAttribute->specified()
DomAttribute->value()
DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()
DOMDocument->__construct()
DomDocument->add_root()
DomDocument->create_attribute()
DomDocument->create_cdata_section()
DomDocument->create_comment()
DomDocument->create_element()
DomDocument->create_element_ns()
DomDocument->create_entity_reference()
DomDocument->create_processing_instruction()
DomDocument->create_text_node()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()
DomDocument->doctype()
DomDocument->document_element()
DomDocument->dump_file()
DomDocument->dump_mem()
DomDocument->get_element_by_id()
DomDocument->get_elements_by_tagname()
DOMDocument->getElementById()
DOMDocument->getElementsByTagName()
DOMDocument->getElementsByTagNameNS()()
DomDocument->html_dump_mem()
DOMDocument->importNode()
DOMDocument->load()
DOMDocument->loadHTML()
DOMDocument->loadHTMLFile()
DOMDocument->loadXML()
DOMDocument->normalize()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()
DOMDocument->save()
DOMDocument->saveHTML()()
DOMDocument->saveHTMLFile()()
DOMDocument->saveXML()()
DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->validate()
DOMDocument->xinclude()
DomDocument->xinclude()
DomDocumentType->entities()
DomDocumentType->internal_subset()
DomDocumentType->name()
DomDocumentType->notations()
DomDocumentType->public_id()
DomDocumentType->system_id()
DomElement->get_attribute()
DomElement->get_attribute_node()
DomElement->get_elements_by_tagname()
DOMElement->getAttribute()
DOMElement->getAttributeNode()
DOMElement->getAttributeNodeNS()
DOMElement->getAttributeNS()
DOMElement->getElementsByTagName()
DOMElement->getElementsByTagNameNS()
DomElement->has_attribute()
DOMElement->hasAttribute()
DOMElement->hasAttributeNS()
DomElement->remove_attribute()
DOMElement->removeAttribute()
DOMElement->removeAttributeNode()
DOMElement->removeAttributeNS()
DomElement->set_attribute()
DOMElement->setAttribute()
DOMElement->setAttributeNode()
DOMElement->setAttributeNodeNS()
DOMElement->setAttributeNS()
DomElement->tagname()
DOMImplementation->createDocument()
DOMImplementation->createDocumentType()
DOMImplementation->hasFeature()()
DOMNamedNodeMap->getNamedItem()
DOMNamedNodeMap->getNamedItemNS()
DOMNamedNodeMap->item()
DomNode->add_namespace()
DomNode->append_child()
DomNode->append_sibling()
DOMNode->appendChild()
DomNode->attributes()
DomNode->child_nodes()
DomNode->clone_node()
DOMNode->cloneNode()
DomNode->dump_node()
DomNode->first_child()
DomNode->get_content()
DomNode->has_attributes()
DomNode->has_child_nodes()
DOMNode->hasAttributes()
DOMNode->hasChildNodes()
DomNode->insert_before()
DOMNode->insertBefore()
DomNode->is_blank_node()
DOMNode->isSameNode()
DOMNode->isSupported()
DomNode->last_child()
DOMNode->lookupNamespaceURI()
DOMNode->lookupPrefix()
DomNode->next_sibling()
DomNode->node_name()
DomNode->node_type()
DomNode->node_value()
DOMNode->normalize()
DomNode->owner_document()
DomNode->parent_node()
DomNode->prefix()
DomNode->previous_sibling()
DomNode->remove_child()
DOMNode->removeChild()
DomNode->replace_child()
DomNode->replace_node()
DOMNode->replaceChild()
DomNode->set_content()
DomNode->set_name()
DomNode->set_namespace()
DomNode->unlink_node()
DOMNodelist->item()
DomProcessingInstruction->data()
DomProcessingInstruction->target()
DOMStringList->item()
DOMText->isWhitespaceInElementContent()
DOMText->splitText()
domxml_new_doc()
domxml_open_file()
domxml_open_mem()
domxml_version()
domxml_xmltree()
domxml_xslt_stylesheet()
domxml_xslt_stylesheet_doc()
domxml_xslt_stylesheet_file()
DOMXPath->__construct()
DOMXPath->evaluate()()
DOMXPath->query()
DOMXPath->registerNamespace()
DomXsltStylesheet->process()
DomXsltStylesheet->result_dump_file()
DomXsltStylesheet->result_dump_mem()
dotnet()
dotnet_load()
doubleval()

F

fam_cancel_monitor()
fam_close()
fam_monitor_collection()
fam_monitor_directory()
fam_monitor_file()
fam_next_event()
fam_open()
fam_pending()
fam_resume_monitor()
fam_suspend_monitor()
fbsql_affected_rows()
fbsql_autocommit()
fbsql_blob_size()
fbsql_change_user()
fbsql_clob_size()
fbsql_close()
fbsql_commit()
fbsql_connect()
fbsql_create_blob()
fbsql_create_clob()
fbsql_create_db()
fbsql_data_seek()
fbsql_database()
fbsql_database_password()
fbsql_db_query()
fbsql_db_status()
fbsql_drop_db()
fbsql_errno()
fbsql_error()
fbsql_fetch_array()
fbsql_fetch_assoc()
fbsql_fetch_field()
fbsql_fetch_lengths()
fbsql_fetch_object()
fbsql_fetch_row()
fbsql_field_flags()
fbsql_field_len()
fbsql_field_name()
fbsql_field_seek()
fbsql_field_table()
fbsql_field_type()
fbsql_free_result()
fbsql_get_autostart_info()
fbsql_hostname()
fbsql_insert_id()
fbsql_list_dbs()
fbsql_list_fields()
fbsql_list_tables()
fbsql_next_result()
fbsql_num_fields()
fbsql_num_rows()
fbsql_password()
fbsql_pconnect()
fbsql_query()
fbsql_read_blob()
fbsql_read_clob()
fbsql_result()
fbsql_rollback()
fbsql_select_db()
fbsql_set_lob_mode()
fbsql_set_password()
fbsql_set_transaction()
fbsql_start_db()
fbsql_stop_db()
fbsql_tablename()
fbsql_username()
fbsql_warnings()
fclose()
fdf_add_doc_javascript()
fdf_add_template()
fdf_close()
fdf_create()
fdf_enum_values()
fdf_errno()
fdf_error()
fdf_get_ap()
fdf_get_attachment()
fdf_get_encoding()
fdf_get_file()
fdf_get_flags()
fdf_get_opt()
fdf_get_status()
fdf_get_value()
fdf_get_version()
fdf_header()
fdf_next_field_name()
fdf_open()
fdf_open_string()
fdf_remove_item()
fdf_save()
fdf_save_string()
fdf_set_ap()
fdf_set_encoding()
fdf_set_file()
fdf_set_flags()
fdf_set_javascript_action()
fdf_set_on_import_javascript()
fdf_set_opt()
fdf_set_status()
fdf_set_submit_form_action()
fdf_set_target_frame()
fdf_set_value()
fdf_set_version()
feof()
fflush()
fgetc()
fgetcsv()
fgets()
fgetss()
file()
file_exists()
file_get_contents()
file_put_contents()
fileatime()
filectime()
filegroup()
fileinode()
filemtime()
fileowner()
fileperms()
filepro()
filepro_fieldcount()
filepro_fieldname()
filepro_fieldtype()
filepro_fieldwidth()
filepro_retrieve()
filepro_rowcount()
filesize()
filetype()
FilterIterator::current()
FilterIterator::getInnerIterator()
FilterIterator::key()
FilterIterator::next()
FilterIterator::rewind()
FilterIterator::valid()
floatval()
flock()
floor()
flush()
fmod()
fnmatch()
fopen()
fpassthru()
fprintf()
fputcsv()
fputs()
fread()
frenchtojd()
fribidi_log2vis()
fscanf()
fseek()
fsockopen()
fstat()
ftell()
ftok()
ftp_alloc()
ftp_cdup()
ftp_chdir()
ftp_chmod()
ftp_close()
ftp_connect()
ftp_delete()
ftp_exec()
ftp_fget()
ftp_fput()
ftp_get()
ftp_get_option()
ftp_login()
ftp_mdtm()
ftp_mkdir()
ftp_nb_continue()
ftp_nb_fget()
ftp_nb_fput()
ftp_nb_get()
ftp_nb_put()
ftp_nlist()
ftp_pasv()
ftp_put()
ftp_pwd()
ftp_quit()
ftp_raw()
ftp_rawlist()
ftp_rename()
ftp_rmdir()
ftp_set_option()
ftp_site()
ftp_size()
ftp_ssl_connect()
ftp_systype()
ftruncate()
func_get_arg()
func_get_args()
func_num_args()
function_exists()
fwrite()

H

header()
headers_list()
headers_sent()
hebrev()
hebrevc()
hexdec()
highlight_file()
highlight_string()
html_entity_decode()
htmlentities()
htmlspecialchars()
http_build_query()
hw_api->checkin()
hw_api->checkout()
hw_api->children()
hw_api->content()
hw_api->copy()
hw_api->dbstat()
hw_api->dcstat()
hw_api->dstanchors()
hw_api->dstofsrcanchor()
hw_api->find()
hw_api->ftstat()
hw_api->hwstat()
hw_api->identify()
hw_api->info()
hw_api->insert()
hw_api->insertanchor()
hw_api->insertcollection()
hw_api->insertdocument()
hw_api->link()
hw_api->lock()
hw_api->move()
hw_api->object()
hw_api->objectbyanchor()
hw_api->parents()
hw_api->remove()
hw_api->replace()
hw_api->setcommittedversion()
hw_api->srcanchors()
hw_api->srcsofdst()
hw_api->unlock()
hw_api->user()
hw_api->userlist()
hw_api_attribute()
hw_api_attribute->key()
hw_api_attribute->langdepvalue()
hw_api_attribute->value()
hw_api_attribute->values()
hw_api_content()
hw_api_content->mimetype()
hw_api_content->read()
hw_api_error->count()
hw_api_error->reason()
hw_api_object()
hw_api_object->assign()
hw_api_object->attreditable()
hw_api_object->count()
hw_api_object->insert()
hw_api_object->remove()
hw_api_object->title()
hw_api_object->value()
hw_api_reason->description()
hw_api_reason->type()
hw_array2objrec()
hw_changeobject()
hw_children()
hw_childrenobj()
hw_close()
hw_connect()
hw_connection_info()
hw_cp()
hw_deleteobject()
hw_docbyanchor()
hw_docbyanchorobj()
hw_document_attributes()
hw_document_bodytag()
hw_document_content()
hw_document_setcontent()
hw_document_size()
hw_dummy()
hw_edittext()
hw_error()
hw_errormsg()
hw_free_document()
hw_getanchors()
hw_getanchorsobj()
hw_getandlock()
hw_getchildcoll()
hw_getchildcollobj()
hw_getchilddoccoll()
hw_getchilddoccollobj()
hw_getobject()
hw_getobjectbyquery()
hw_getobjectbyquerycoll()
hw_getobjectbyquerycollobj()
hw_getobjectbyqueryobj()
hw_getparents()
hw_getparentsobj()
hw_getrellink()
hw_getremote()
hw_getremotechildren()
hw_getsrcbydestobj()
hw_gettext()
hw_getusername()
hw_identify()
hw_incollections()
hw_info()
hw_inscoll()
hw_insdoc()
hw_insertanchors()
hw_insertdocument()
hw_insertobject()
hw_mapid()
hw_modifyobject()
hw_mv()
hw_new_document()
hw_objrec2array()
hw_output_document()
hw_pconnect()
hw_pipedocument()
hw_root()
hw_setlinkroot()
hw_stat()
hw_unlock()
hw_who()
hwapi_hgcsp()
hypot()

I

ibase_add_user()
ibase_affected_rows()
ibase_backup()
ibase_blob_add()
ibase_blob_cancel()
ibase_blob_close()
ibase_blob_create()
ibase_blob_echo()
ibase_blob_get()
ibase_blob_import()
ibase_blob_info()
ibase_blob_open()
ibase_close()
ibase_commit()
ibase_commit_ret()
ibase_connect()
ibase_db_info()
ibase_delete_user()
ibase_drop_db()
ibase_errcode()
ibase_errmsg()
ibase_execute()
ibase_fetch_assoc()
ibase_fetch_object()
ibase_fetch_row()
ibase_field_info()
ibase_free_event_handler()
ibase_free_query()
ibase_free_result()
ibase_gen_id()
ibase_maintain_db()
ibase_modify_user()
ibase_name_result()
ibase_num_fields()
ibase_num_params()
ibase_param_info()
ibase_pconnect()
ibase_prepare()
ibase_query()
ibase_restore()
ibase_rollback()
ibase_rollback_ret()
ibase_server_info()
ibase_service_attach()
ibase_service_detach()
ibase_set_event_handler()
ibase_timefmt()
ibase_trans()
ibase_wait_event()
iconv()
iconv_get_encoding()
iconv_mime_decode()
iconv_mime_decode_headers()
iconv_mime_encode()
iconv_set_encoding()
iconv_strlen()
iconv_strpos()
iconv_strrpos()
iconv_substr()
id3_get_frame_long_name()
id3_get_frame_short_name()
id3_get_genre_id()
id3_get_genre_list()
id3_get_genre_name()
id3_get_tag()
id3_get_version()
id3_remove_tag()
id3_set_tag()
idate()
ifx_affected_rows()
ifx_blobinfile_mode()
ifx_byteasvarchar()
ifx_close()
ifx_connect()
ifx_copy_blob()
ifx_create_blob()
ifx_create_char()
ifx_do()
ifx_error()
ifx_errormsg()
ifx_fetch_row()
ifx_fieldproperties()
ifx_fieldtypes()
ifx_free_blob()
ifx_free_char()
ifx_free_result()
ifx_get_blob()
ifx_get_char()
ifx_getsqlca()
ifx_htmltbl_result()
ifx_nullformat()
ifx_num_fields()
ifx_num_rows()
ifx_pconnect()
ifx_prepare()
ifx_query()
ifx_textasvarchar()
ifx_update_blob()
ifx_update_char()
ifxus_close_slob()
ifxus_create_slob()
ifxus_free_slob()
ifxus_open_slob()
ifxus_read_slob()
ifxus_seek_slob()
ifxus_tell_slob()
ifxus_write_slob()
ignore_user_abort()
image2wbmp()
image_type_to_extension()
image_type_to_mime_type()
imagealphablending()
imageantialias()
imagearc()
imagechar()
imagecharup()
imagecolorallocate()
imagecolorallocatealpha()
imagecolorat()
imagecolorclosest()
imagecolorclosestalpha()
imagecolorclosesthwb()
imagecolordeallocate()
imagecolorexact()
imagecolorexactalpha()
imagecolormatch()
imagecolorresolve()
imagecolorresolvealpha()
imagecolorset()
imagecolorsforindex()
imagecolorstotal()
imagecolortransparent()
imagecopy()
imagecopymerge()
imagecopymergegray()
imagecopyresampled()
imagecopyresized()
imagecreate()
imagecreatefromgd()
imagecreatefromgd2()
imagecreatefromgd2part()
imagecreatefromgif()
imagecreatefromjpeg()
imagecreatefrompng()
imagecreatefromstring()
imagecreatefromwbmp()
imagecreatefromxbm()
imagecreatefromxpm()
imagecreatetruecolor()
imagedashedline()
imagedestroy()
imageellipse()
imagefill()
imagefilledarc()
imagefilledellipse()
imagefilledpolygon()
imagefilledrectangle()
imagefilltoborder()
imagefilter()
imagefontheight()
imagefontwidth()
imageftbbox()
imagefttext()
imagegammacorrect()
imagegd()
imagegd2()
imagegif()
imageinterlace()
imageistruecolor()
imagejpeg()
imagelayereffect()
imageline()
imageloadfont()
imagepalettecopy()
imagepng()
imagepolygon()
imagepsbbox()
imagepscopyfont()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
imagerectangle()
imagerotate()
imagesavealpha()
imagesetbrush()
imagesetpixel()
imagesetstyle()
imagesetthickness()
imagesettile()
imagestring()
imagestringup()
imagesx()
imagesy()
imagetruecolortopalette()
imagettfbbox()
imagettftext()
imagetypes()
imagewbmp()
imagexbm()
imap_8bit()
imap_alerts()
imap_append()
imap_base64()
imap_binary()
imap_body()
imap_bodystruct()
imap_check()
imap_clearflag_full()
imap_close()
imap_createmailbox()
imap_delete()
imap_deletemailbox()
imap_errors()
imap_expunge()
imap_fetch_overview()
imap_fetchbody()
imap_fetchheader()
imap_fetchstructure()
imap_get_quota()
imap_get_quotaroot()
imap_getacl()
imap_getmailboxes()
imap_getsubscribed()
imap_header()
imap_headerinfo()
imap_headers()
imap_last_error()
imap_list()
imap_listmailbox()
imap_listscan()
imap_listsubscribed()
imap_lsub()
imap_mail()
imap_mail_compose()
imap_mail_copy()
imap_mail_move()
imap_mailboxmsginfo()
imap_mime_header_decode()
imap_msgno()
imap_num_msg()
imap_num_recent()
imap_open()
imap_ping()
imap_qprint()
imap_renamemailbox()
imap_reopen()
imap_rfc822_parse_adrlist()
imap_rfc822_parse_headers()
imap_rfc822_write_address()
imap_scanmailbox()
imap_search()
imap_set_quota()
imap_setacl()
imap_setflag_full()
imap_sort()
imap_status()
imap_subscribe()
imap_thread()
imap_timeout()
imap_uid()
imap_undelete()
imap_unsubscribe()
imap_utf7_decode()
imap_utf7_encode()
imap_utf8()
implode()
import_request_variables()
in_array()
inet_ntop()
inet_pton()
ingres_autocommit()
ingres_close()
ingres_commit()
ingres_connect()
ingres_fetch_array()
ingres_fetch_object()
ingres_fetch_row()
ingres_field_length()
ingres_field_name()
ingres_field_nullable()
ingres_field_precision()
ingres_field_scale()
ingres_field_type()
ingres_num_fields()
ingres_num_rows()
ingres_pconnect()
ingres_query()
ingres_rollback()
ini_alter()
ini_get()
ini_get_all()
ini_restore()
ini_set()
interface_exists()
intval()
ip2long()
iptcembed()
iptcparse()
ircg_channel_mode()
ircg_disconnect()
ircg_eval_ecmascript_params()
ircg_fetch_error_msg()
ircg_get_username()
ircg_html_encode()
ircg_ignore_add()
ircg_ignore_del()
ircg_invite()
ircg_is_conn_alive()
ircg_join()
ircg_kick()
ircg_list()
ircg_lookup_format_messages()
ircg_lusers()
ircg_msg()
ircg_names()
ircg_nick()
ircg_nickname_escape()
ircg_nickname_unescape()
ircg_notice()
ircg_oper()
ircg_part()
ircg_pconnect()
ircg_register_format_messages()
ircg_set_current()
ircg_set_file()
ircg_set_on_die()
ircg_topic()
ircg_who()
ircg_whois()
is_a()
is_array()
is_bool()
is_callable()
is_dir()
is_double()
is_executable()
is_file()
is_finite()
is_float()
is_infinite()
is_int()
is_integer()
is_link()
is_long()
is_nan()
is_null()
is_numeric()
is_object()
is_readable()
is_real()
is_resource()
is_scalar()
is_soap_fault()
is_string()
is_subclass_of()
is_uploaded_file()
is_writable()
is_writeable()
isset()
iterator-to-array()
iterator_count()

M

mail()
mailparse_determine_best_xfer_encoding()
mailparse_msg_create()
mailparse_msg_extract_part()
mailparse_msg_extract_part_file()
mailparse_msg_free()
mailparse_msg_get_part()
mailparse_msg_get_part_data()
mailparse_msg_get_structure()
mailparse_msg_parse()
mailparse_msg_parse_file()
mailparse_rfc822_parse_addresses()
mailparse_stream_encode()
mailparse_uudecode_all()
main()
max()
mb_convert_case()
mb_convert_encoding()
mb_convert_kana()
mb_convert_variables()
mb_decode_mimeheader()
mb_decode_numericentity()
mb_detect_encoding()
mb_detect_order()
mb_encode_mimeheader()
mb_encode_numericentity()
mb_ereg()
mb_ereg_match()
mb_ereg_replace()
mb_ereg_search()
mb_ereg_search_getpos()
mb_ereg_search_getregs()
mb_ereg_search_init()
mb_ereg_search_pos()
mb_ereg_search_regs()
mb_ereg_search_setpos()
mb_eregi()
mb_eregi_replace()
mb_get_info()
mb_http_input()
mb_http_output()
mb_internal_encoding()
mb_language()
mb_list_encodings()
mb_output_handler()
mb_parse_str()
mb_preferred_mime_name()
mb_regex_encoding()
mb_regex_set_options()
mb_send_mail()
mb_split()
mb_strcut()
mb_strimwidth()
mb_strlen()
mb_strpos()
mb_strrpos()
mb_strtolower()
mb_strtoupper()
mb_strwidth()
mb_substitute_character()
mb_substr()
mb_substr_count()
mcal_append_event()
mcal_close()
mcal_create_calendar()
mcal_date_compare()
mcal_date_valid()
mcal_day_of_week()
mcal_day_of_year()
mcal_days_in_month()
mcal_delete_calendar()
mcal_delete_event()
mcal_event_add_attribute()
mcal_event_init()
mcal_event_set_alarm()
mcal_event_set_category()
mcal_event_set_class()
mcal_event_set_description()
mcal_event_set_end()
mcal_event_set_recur_daily()
mcal_event_set_recur_monthly_mday()
mcal_event_set_recur_monthly_wday()
mcal_event_set_recur_none()
mcal_event_set_recur_weekly()
mcal_event_set_recur_yearly()
mcal_event_set_start()
mcal_event_set_title()
mcal_expunge()
mcal_fetch_current_stream_event()
mcal_fetch_event()
mcal_is_leap_year()
mcal_list_alarms()
mcal_list_events()
mcal_next_recurrence()
mcal_open()
mcal_popen()
mcal_rename_calendar()
mcal_reopen()
mcal_snooze()
mcal_store_event()
mcal_time_valid()
mcal_week_of_year()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_create_iv()
mcrypt_decrypt()
mcrypt_ecb()
mcrypt_enc_get_algorithms_name()
mcrypt_enc_get_block_size()
mcrypt_enc_get_iv_size()
mcrypt_enc_get_key_size()
mcrypt_enc_get_modes_name()
mcrypt_enc_get_supported_key_sizes()
mcrypt_enc_is_block_algorithm()
mcrypt_enc_is_block_algorithm_mode()
mcrypt_enc_is_block_mode()
mcrypt_enc_self_test()
mcrypt_encrypt()
mcrypt_generic()
mcrypt_generic_deinit()
mcrypt_generic_end()
mcrypt_generic_init()
mcrypt_get_block_size()
mcrypt_get_cipher_name()
mcrypt_get_iv_size()
mcrypt_get_key_size()
mcrypt_list_algorithms()
mcrypt_list_modes()
mcrypt_module_close()
mcrypt_module_get_algo_block_size()
mcrypt_module_get_algo_key_size()
mcrypt_module_get_supported_key_sizes()
mcrypt_module_is_block_algorithm()
mcrypt_module_is_block_algorithm_mode()
mcrypt_module_is_block_mode()
mcrypt_module_open()
mcrypt_module_self_test()
mcrypt_ofb()
mcve_adduser()
mcve_adduserarg()
mcve_bt()
mcve_checkstatus()
mcve_chkpwd()
mcve_chngpwd()
mcve_completeauthorizations()
mcve_connect()
mcve_connectionerror()
mcve_deleteresponse()
mcve_deletetrans()
mcve_deleteusersetup()
mcve_deluser()
mcve_destroyconn()
mcve_destroyengine()
mcve_disableuser()
mcve_edituser()
mcve_enableuser()
mcve_force()
mcve_getcell()
mcve_getcellbynum()
mcve_getcommadelimited()
mcve_getheader()
mcve_getuserarg()
mcve_getuserparam()
mcve_gft()
mcve_gl()
mcve_gut()
mcve_initconn()
mcve_initengine()
mcve_initusersetup()
mcve_iscommadelimited()
mcve_liststats()
mcve_listusers()
mcve_maxconntimeout()
mcve_monitor()
mcve_numcolumns()
mcve_numrows()
mcve_override()
mcve_parsecommadelimited()
mcve_ping()
mcve_preauth()
mcve_preauthcompletion()
mcve_qc()
mcve_responseparam()
mcve_return()
mcve_returncode()
mcve_returnstatus()
mcve_sale()
mcve_setblocking()
mcve_setdropfile()
mcve_setip()
mcve_setssl()
mcve_setssl_files()
mcve_settimeout()
mcve_settle()
mcve_text_avs()
mcve_text_code()
mcve_text_cv()
mcve_transactionauth()
mcve_transactionavs()
mcve_transactionbatch()
mcve_transactioncv()
mcve_transactionid()
mcve_transactionitem()
mcve_transactionssent()
mcve_transactiontext()
mcve_transinqueue()
mcve_transnew()
mcve_transparam()
mcve_transsend()
mcve_ub()
mcve_uwait()
mcve_verifyconnection()
mcve_verifysslcert()
mcve_void()
md5()
md5_file()
mdecrypt_generic()
Memcache::add()
Memcache::close()
Memcache::connect()
Memcache::decrement()
Memcache::delete()
Memcache::flush()
Memcache::get()
Memcache::getStats()
Memcache::getVersion()
Memcache::increment()
Memcache::pconnect()
Memcache::replace()
Memcache::set()
memcache_debug()
memory_get_usage()
metaphone()
method_exists()
mhash()
mhash_count()
mhash_get_block_size()
mhash_get_hash_name()
mhash_keygen_s2k()
microtime()
mime_content_type()
min()
ming_setcubicthreshold()
ming_setscale()
ming_useswfversion()
mkdir()
mktime()
money_format()
move_uploaded_file()
msession_connect()
msession_count()
msession_create()
msession_destroy()
msession_disconnect()
msession_find()
msession_get()
msession_get_array()
msession_get_data()
msession_inc()
msession_list()
msession_listvar()
msession_lock()
msession_plugin()
msession_randstr()
msession_set()
msession_set_array()
msession_set_data()
msession_timeout()
msession_uniq()
msession_unlock()
msg_get_queue()
msg_receive()
msg_remove_queue()
msg_send()
msg_set_queue()
msg_stat_queue()
msql()
msql_affected_rows()
msql_close()
msql_connect()
msql_create_db()
msql_createdb()
msql_data_seek()
msql_db_query()
msql_dbname()
msql_drop_db()
msql_error()
msql_fetch_array()
msql_fetch_field()
msql_fetch_object()
msql_fetch_row()
msql_field_flags()
msql_field_len()
msql_field_name()
msql_field_seek()
msql_field_table()
msql_field_type()
msql_fieldflags()
msql_fieldlen()
msql_fieldname()
msql_fieldtable()
msql_fieldtype()
msql_free_result()
msql_list_dbs()
msql_list_fields()
msql_list_tables()
msql_num_fields()
msql_num_rows()
msql_numfields()
msql_numrows()
msql_pconnect()
msql_query()
msql_regcase()
msql_result()
msql_select_db()
msql_tablename()
mssql_bind()
mssql_close()
mssql_connect()
mssql_data_seek()
mssql_execute()
mssql_fetch_array()
mssql_fetch_assoc()
mssql_fetch_batch()
mssql_fetch_field()
mssql_fetch_object()
mssql_fetch_row()
mssql_field_length()
mssql_field_name()
mssql_field_seek()
mssql_field_type()
mssql_free_result()
mssql_free_statement()
mssql_get_last_message()
mssql_guid_string()
mssql_init()
mssql_min_error_severity()
mssql_min_message_severity()
mssql_next_result()
mssql_num_fields()
mssql_num_rows()
mssql_pconnect()
mssql_query()
mssql_result()
mssql_rows_affected()
mssql_select_db()
mt_getrandmax()
mt_rand()
mt_srand()
muscat_close()
muscat_get()
muscat_give()
muscat_setup()
muscat_setup_net()
mysql_affected_rows()
mysql_change_user()
mysql_client_encoding()
mysql_close()
mysql_connect()
mysql_create_db()
mysql_data_seek()
mysql_db_name()
mysql_db_query()
mysql_drop_db()
mysql_errno()
mysql_error()
mysql_escape_string()
mysql_fetch_array()
mysql_fetch_assoc()
mysql_fetch_field()
mysql_fetch_lengths()
mysql_fetch_object()
mysql_fetch_row()
mysql_field_flags()
mysql_field_len()
mysql_field_name()
mysql_field_seek()
mysql_field_table()
mysql_field_type()
mysql_free_result()
mysql_get_client_info()
mysql_get_host_info()
mysql_get_proto_info()
mysql_get_server_info()
mysql_info()
mysql_insert_id()
mysql_list_dbs()
mysql_list_fields()
mysql_list_processes()
mysql_list_tables()
mysql_num_fields()
mysql_num_rows()
mysql_pconnect()
mysql_ping()
mysql_query()
mysql_real_escape_string()
mysql_result()
mysql_select_db()
mysql_stat()
mysql_tablename()
mysql_thread_id()
mysql_unbuffered_query()
mysqli()()
mysqli->affected_rows()
mysqli->autocommit()
mysqli->change_user()
mysqli->character_set_name()
mysqli->close()
mysqli->commit()
mysqli->disable_reads_from_master()
mysqli->dump_debug_info()
mysqli->errno()
mysqli->fetch_assoc()
mysqli->field_count()
mysqli->get_host_info()
mysqli->info()
mysqli->insert_id()
mysqli->kill()
mysqli->more_results()
mysqli->multi_query()
mysqli->next_result()
mysqli->options()
mysqli->ping()
mysqli->prepare()
mysqli->protocol_version()
mysqli->query()
mysqli->real_connect()
mysqli->real_escape_string()
mysqli->real_query()
mysqli->rollback()
mysqli->rpl_query_type()
mysqli->select_db()
mysqli->send_query()
mysqli->server_info()
mysqli->sqlstate()
mysqli->ssl_set()
mysqli->stat()
mysqli->stmt_init()
mysqli->store_result()
mysqli->thread_id()
mysqli->use_result()
mysqli->warning_count()
mysqli_affected_rows()
mysqli_autocommit()
mysqli_bind_param()
mysqli_bind_result()
mysqli_change_user()
mysqli_character_set_name()
mysqli_client_encoding()
mysqli_close()
mysqli_commit()
mysqli_connect()
mysqli_connect_errno()
mysqli_connect_error()
mysqli_data_seek()
mysqli_debug()
mysqli_disable_reads_from_master()
mysqli_disable_rpl_parse()
mysqli_dump_debug_info()
mysqli_embedded_connect()
mysqli_enable_reads_from_master()
mysqli_enable_rpl_parse()
mysqli_errno()
mysqli_error()
mysqli_escape_string()
mysqli_execute()
mysqli_fetch()
mysqli_fetch_array()
mysqli_fetch_assoc()
mysqli_fetch_field()
mysqli_fetch_field_direct()
mysqli_fetch_fields()
mysqli_fetch_lengths()
mysqli_fetch_object()
mysqli_fetch_row()
mysqli_field_count()
mysqli_field_seek()
mysqli_field_tell()
mysqli_free_result()
mysqli_get_client_info()
mysqli_get_client_version()
mysqli_get_host_info()
mysqli_get_metadata()
mysqli_get_proto_info()
mysqli_get_server_info()
mysqli_get_server_version()
mysqli_info()
mysqli_init()
mysqli_insert_id()
mysqli_kill()
mysqli_master_query()
mysqli_more_results()
mysqli_multi_query()
mysqli_next_result()
mysqli_num_fields()
mysqli_num_rows()
mysqli_options()
mysqli_param_count()
mysqli_ping()
mysqli_prepare()
mysqli_query()
mysqli_real_connect()
mysqli_real_escape_string()
mysqli_real_query()
mysqli_report()
mysqli_rollback()
mysqli_rpl_parse_enabled()
mysqli_rpl_probe()
mysqli_rpl_query_type()
mysqli_select_db()
mysqli_send_long_data()
mysqli_send_query()
mysqli_server_end()
mysqli_server_init()
mysqli_set_opt()
mysqli_sqlstate()
mysqli_ssl_set()
mysqli_stat()
mysqli_stmt->affected_rows()
mysqli_stmt->close()
mysqli_stmt->errno()
mysqli_stmt->error()
mysqli_stmt->store_result()
mysqli_stmt_affected_rows()
mysqli_stmt_bind_param()
mysqli_stmt_bind_result()
mysqli_stmt_close()
mysqli_stmt_data_seek()
mysqli_stmt_errno()
mysqli_stmt_error()
mysqli_stmt_execute()
mysqli_stmt_fetch()
mysqli_stmt_free_result()
mysqli_stmt_init()
mysqli_stmt_num_rows()
mysqli_stmt_param_count()
mysqli_stmt_prepare()
mysqli_stmt_reset()
mysqli_stmt_result_metadata()
mysqli_stmt_send_long_data()
mysqli_stmt_sqlstate()
mysqli_stmt_store_result()
mysqli_store_result()
mysqli_thread_id()
mysqli_thread_safe()
mysqli_use_result()
mysqli_warning_count()

N

natcasesort()
natsort()
ncurses_addch()
ncurses_addchnstr()
ncurses_addchstr()
ncurses_addnstr()
ncurses_addstr()
ncurses_assume_default_colors()
ncurses_attroff()
ncurses_attron()
ncurses_attrset()
ncurses_baudrate()
ncurses_beep()
ncurses_bkgd()
ncurses_bkgdset()
ncurses_border()
ncurses_bottom_panel()
ncurses_can_change_color()
ncurses_cbreak()
ncurses_clear()
ncurses_clrtobot()
ncurses_clrtoeol()
ncurses_color_content()
ncurses_color_set()
ncurses_curs_set()
ncurses_def_prog_mode()
ncurses_def_shell_mode()
ncurses_define_key()
ncurses_del_panel()
ncurses_delay_output()
ncurses_delch()
ncurses_deleteln()
ncurses_delwin()
ncurses_doupdate()
ncurses_echo()
ncurses_echochar()
ncurses_end()
ncurses_erase()
ncurses_erasechar()
ncurses_filter()
ncurses_flash()
ncurses_flushinp()
ncurses_getch()
ncurses_getmaxyx()
ncurses_getmouse()
ncurses_getyx()
ncurses_halfdelay()
ncurses_has_colors()
ncurses_has_ic()
ncurses_has_il()
ncurses_has_key()
ncurses_hide_panel()
ncurses_hline()
ncurses_inch()
ncurses_init()
ncurses_init_color()
ncurses_init_pair()
ncurses_insch()
ncurses_insdelln()
ncurses_insertln()
ncurses_insstr()
ncurses_instr()
ncurses_isendwin()
ncurses_keyok()
ncurses_keypad()
ncurses_killchar()
ncurses_longname()
ncurses_meta()
ncurses_mouse_trafo()
ncurses_mouseinterval()
ncurses_mousemask()
ncurses_move()
ncurses_move_panel()
ncurses_mvaddch()
ncurses_mvaddchnstr()
ncurses_mvaddchstr()
ncurses_mvaddnstr()
ncurses_mvaddstr()
ncurses_mvcur()
ncurses_mvdelch()
ncurses_mvgetch()
ncurses_mvhline()
ncurses_mvinch()
ncurses_mvvline()
ncurses_mvwaddstr()
ncurses_napms()
ncurses_new_panel()
ncurses_newpad()
ncurses_newwin()
ncurses_nl()
ncurses_nocbreak()
ncurses_noecho()
ncurses_nonl()
ncurses_noqiflush()
ncurses_noraw()
ncurses_pair_content()
ncurses_panel_above()
ncurses_panel_below()
ncurses_panel_window()
ncurses_pnoutrefresh()
ncurses_prefresh()
ncurses_putp()
ncurses_qiflush()
ncurses_raw()
ncurses_refresh()
ncurses_replace_panel()
ncurses_reset_prog_mode()
ncurses_reset_shell_mode()
ncurses_resetty()
ncurses_savetty()
ncurses_scr_dump()
ncurses_scr_init()
ncurses_scr_restore()
ncurses_scr_set()
ncurses_scrl()
ncurses_show_panel()
ncurses_slk_attr()
ncurses_slk_attroff()
ncurses_slk_attron()
ncurses_slk_attrset()
ncurses_slk_clear()
ncurses_slk_color()
ncurses_slk_init()
ncurses_slk_noutrefresh()
ncurses_slk_refresh()
ncurses_slk_restore()
ncurses_slk_set()
ncurses_slk_touch()
ncurses_standend()
ncurses_standout()
ncurses_start_color()
ncurses_termattrs()
ncurses_termname()
ncurses_timeout()
ncurses_top_panel()
ncurses_typeahead()
ncurses_ungetch()
ncurses_ungetmouse()
ncurses_update_panels()
ncurses_use_default_colors()
ncurses_use_env()
ncurses_use_extended_names()
ncurses_vidattr()
ncurses_vline()
ncurses_waddch()
ncurses_waddstr()
ncurses_wattroff()
ncurses_wattron()
ncurses_wattrset()
ncurses_wborder()
ncurses_wclear()
ncurses_wcolor_set()
ncurses_werase()
ncurses_wgetch()
ncurses_whline()
ncurses_wmouse_trafo()
ncurses_wmove()
ncurses_wnoutrefresh()
ncurses_wrefresh()
ncurses_wstandend()
ncurses_wstandout()
ncurses_wvline()
next()
ngettext()
nl2br()
nl_langinfo()
notes_body()
notes_copy_db()
notes_create_db()
notes_create_note()
notes_drop_db()
notes_find_note()
notes_header_info()
notes_list_msgs()
notes_mark_read()
notes_mark_unread()
notes_nav_create()
notes_search()
notes_unread()
notes_version()
nsapi_request_headers()
nsapi_response_headers()
nsapi_virtual()
number_format()

O

ob_clean()
ob_end_clean()
ob_end_flush()
ob_flush()
ob_get_clean()
ob_get_contents()
ob_get_flush()
ob_get_length()
ob_get_level()
ob_get_status()
ob_gzhandler()
ob_iconv_handler()
ob_implicit_flush()
ob_list_handlers()
ob_start()
ob_tidyhandler()
OCI-Collection->append()
OCI-Collection->assign()
OCI-Collection->assignElem()
OCI-Collection->free()
OCI-Collection->getElem()
OCI-Collection->max()
OCI-Collection->size()
OCI-Collection->trim()
oci_bind_by_name()
oci_cancel()
oci_close()
oci_commit()
oci_connect()
oci_define_by_name()
oci_error()
oci_execute()
oci_fetch()
oci_fetch_all()
oci_fetch_array()
oci_fetch_assoc()
oci_fetch_object()
oci_fetch_row()
oci_field_is_null()
oci_field_name()
oci_field_precision()
oci_field_scale()
oci_field_size()
oci_field_type()
oci_field_type_raw()
oci_free_statement()
oci_internal_debug()
oci_lob_copy()
oci_lob_is_equal()
oci_new_collection()
oci_new_connect()
oci_new_cursor()
oci_new_descriptor()
oci_num_fields()
oci_num_rows()
oci_parse()
oci_password_change()
oci_pconnect()
oci_result()
oci_rollback()
oci_server_version()
oci_set_prefetch()
oci_statement_type()
ocibindbyname()
ocicancel()
ocicloselob()
ocicollappend()
ocicollassign()
ocicollassignelem()
ocicollgetelem()
ocicollmax()
ocicollsize()
ocicolltrim()
ocicolumnisnull()
ocicolumnname()
ocicolumnprecision()
ocicolumnscale()
ocicolumnsize()
ocicolumntype()
ocicolumntyperaw()
ocicommit()
ocidefinebyname()
ocierror()
ociexecute()
ocifetch()
ocifetchinto()
ocifetchstatement()
ocifreecollection()
ocifreecursor()
ocifreedesc()
ocifreestatement()
ociinternaldebug()
ociloadlob()
ocilogoff()
ocilogon()
ocinewcollection()
ocinewcursor()
ocinewdescriptor()
ocinlogon()
ocinumcols()
ociparse()
ociplogon()
ociresult()
ocirollback()
ocirowcount()
ocisavelob()
ocisavelobfile()
ociserverversion()
ocisetprefetch()
ocistatementtype()
ociwritelobtofile()
ociwritetemporarylob()
octdec()
odbc_autocommit()
odbc_binmode()
odbc_close()
odbc_close_all()
odbc_columnprivileges()
odbc_columns()
odbc_commit()
odbc_connect()
odbc_cursor()
odbc_data_source()
odbc_do()
odbc_error()
odbc_errormsg()
odbc_exec()
odbc_execute()
odbc_fetch_array()
odbc_fetch_into()
odbc_fetch_object()
odbc_fetch_row()
odbc_field_len()
odbc_field_name()
odbc_field_num()
odbc_field_precision()
odbc_field_scale()
odbc_field_type()
odbc_foreignkeys()
odbc_free_result()
odbc_gettypeinfo()
odbc_longreadlen()
odbc_next_result()
odbc_num_fields()
odbc_num_rows()
odbc_pconnect()
odbc_prepare()
odbc_primarykeys()
odbc_procedurecolumns()
odbc_procedures()
odbc_result()
odbc_result_all()
odbc_rollback()
odbc_setoption()
odbc_specialcolumns()
odbc_statistics()
odbc_tableprivileges()
odbc_tables()
openal_buffer_create()
openal_buffer_data()
openal_buffer_destroy()
openal_buffer_get()
openal_buffer_loadwav()
openal_context_create()
openal_context_current()
openal_context_destroy()
openal_context_process()
openal_context_suspend()
openal_device_close()
openal_device_open()
openal_listener_get()
openal_listener_set()
openal_source_create()
openal_source_destroy()
openal_source_get()
openal_source_pause()
openal_source_play()
openal_source_rewind()
openal_source_set()
openal_source_stop()
openal_stream()
opendir()
openlog()
openssl_csr_export()
openssl_csr_export_to_file()
openssl_csr_new()
openssl_csr_sign()
openssl_error_string()
openssl_free_key()
openssl_get_privatekey()
openssl_get_publickey()
openssl_open()
openssl_pkcs7_decrypt()
openssl_pkcs7_encrypt()
openssl_pkcs7_sign()
openssl_pkcs7_verify()
openssl_pkey_export()
openssl_pkey_export_to_file()
openssl_pkey_get_private()
openssl_pkey_get_public()
openssl_pkey_new()
openssl_private_decrypt()
openssl_private_encrypt()
openssl_public_decrypt()
openssl_public_encrypt()
openssl_seal()
openssl_sign()
openssl_verify()
openssl_x509_check_private_key()
openssl_x509_checkpurpose()
openssl_x509_export()
openssl_x509_export_to_file()
openssl_x509_free()
openssl_x509_parse()
openssl_x509_read()
ora_bind()
ora_close()
ora_columnname()
ora_columnsize()
ora_columntype()
ora_commit()
ora_commitoff()
ora_commiton()
ora_do()
ora_error()
ora_errorcode()
ora_exec()
ora_fetch()
ora_fetch_into()
ora_getcolumn()
ora_logoff()
ora_logon()
ora_numcols()
ora_numrows()
ora_open()
ora_parse()
ora_plogon()
ora_rollback()
ord()
output_add_rewrite_var()
output_reset_rewrite_vars()
overload()
override_function()
ovrimos_close()
ovrimos_commit()
ovrimos_connect()
ovrimos_cursor()
ovrimos_exec()
ovrimos_execute()
ovrimos_fetch_into()
ovrimos_fetch_row()
ovrimos_field_len()
ovrimos_field_name()
ovrimos_field_num()
ovrimos_field_type()
ovrimos_free_result()
ovrimos_longreadlen()
ovrimos_num_fields()
ovrimos_num_rows()
ovrimos_prepare()
ovrimos_result()
ovrimos_result_all()
ovrimos_rollback()

P

pack()
ParentIterator::getChildren()
ParentIterator::hasChildren()
ParentIterator::next()
ParentIterator::rewind()
parse_ini_file()
parse_str()
parse_url()
parsekit_compile_file()
parsekit_compile_string()
parsekit_func_arginfo()
passthru()
pathinfo()
pclose()
pcntl_alarm()
pcntl_exec()
pcntl_fork()
pcntl_getpriority()
pcntl_setpriority()
pcntl_signal()
pcntl_wait()
pcntl_waitpid()
pcntl_wexitstatus()
pcntl_wifexited()
pcntl_wifsignaled()
pcntl_wifstopped()
pcntl_wstopsig()
pcntl_wtermsig()
pdf_add_annotation()
pdf_add_bookmark()
pdf_add_launchlink()
pdf_add_locallink()
pdf_add_note()
pdf_add_outline()
pdf_add_pdflink()
pdf_add_thumbnail()
pdf_add_weblink()
pdf_arc()
pdf_arcn()
pdf_attach_file()
pdf_begin_page()
pdf_begin_pattern()
pdf_begin_template()
pdf_circle()
pdf_clip()
pdf_close()
pdf_close_image()
pdf_close_pdi()
pdf_close_pdi_page()
pdf_closepath()
pdf_closepath_fill_stroke()
pdf_closepath_stroke()
pdf_concat()
pdf_continue_text()
pdf_curveto()
pdf_delete()
pdf_end_page()
pdf_end_pattern()
pdf_end_template()
pdf_endpath()
pdf_fill()
pdf_fill_stroke()
pdf_findfont()
pdf_get_buffer()
pdf_get_font()
pdf_get_fontname()
pdf_get_fontsize()
pdf_get_image_height()
pdf_get_image_width()
pdf_get_majorversion()
pdf_get_minorversion()
pdf_get_parameter()
pdf_get_pdi_parameter()
pdf_get_pdi_value()
pdf_get_value()
pdf_initgraphics()
pdf_lineto()
pdf_makespotcolor()
pdf_moveto()
pdf_new()
pdf_open()
pdf_open_ccitt()
pdf_open_file()
pdf_open_gif()
pdf_open_image()
pdf_open_image_file()
pdf_open_jpeg()
pdf_open_memory_image()
pdf_open_pdi()
pdf_open_pdi_page()
pdf_open_png()
pdf_open_tiff()
pdf_place_image()
pdf_place_pdi_page()
pdf_rect()
pdf_restore()
pdf_rotate()
pdf_save()
pdf_scale()
pdf_set_border_color()
pdf_set_border_dash()
pdf_set_border_style()
pdf_set_char_spacing()
pdf_set_duration()
pdf_set_font()
pdf_set_horiz_scaling()
pdf_set_info()
pdf_set_info_author()
pdf_set_info_creator()
pdf_set_info_keywords()
pdf_set_info_subject()
pdf_set_info_title()
pdf_set_leading()
pdf_set_parameter()
pdf_set_text_matrix()
pdf_set_text_pos()
pdf_set_text_rendering()
pdf_set_text_rise()
pdf_set_value()
pdf_set_word_spacing()
pdf_setcolor()
pdf_setdash()
pdf_setflat()
pdf_setfont()
pdf_setgray()
pdf_setgray_fill()
pdf_setgray_stroke()
pdf_setlinecap()
pdf_setlinejoin()
pdf_setlinewidth()
pdf_setmatrix()
pdf_setmiterlimit()
pdf_setpolydash()
pdf_setrgbcolor()
pdf_setrgbcolor_fill()
pdf_setrgbcolor_stroke()
pdf_show()
pdf_show_boxed()
pdf_show_xy()
pdf_skew()
pdf_stringwidth()
pdf_stroke()
pdf_translate()
PDO::__construct()
PDO::beginTransaction()
PDO::commit()
PDO::errorCode()
PDO::errorInfo()
PDO::exec()
PDO::lastInsertId()
PDO::prepare()
PDO::rollBack()
PDO::setAttribute()
PDOStatement::bindColumn()
PDOStatement::bindParam()
PDOStatement::errorCode()
PDOStatement::errorInfo()
PDOStatement::execute()
PDOStatement::fetch()
PDOStatement::fetchAll()
PDOStatement::fetchSingle()
PDOStatement::rowCount()
pfpro_cleanup()
pfpro_init()
pfpro_process()
pfpro_process_raw()
pfpro_version()
pfsockopen()
pg_affected_rows()
pg_cancel_query()
pg_client_encoding()
pg_close()
pg_connect()
pg_connection_busy()
pg_connection_reset()
pg_connection_status()
pg_convert()
pg_copy_from()
pg_copy_to()
pg_dbname()
pg_delete()
pg_end_copy()
pg_escape_bytea()
pg_escape_string()
pg_fetch_all()
pg_fetch_array()
pg_fetch_assoc()
pg_fetch_object()
pg_fetch_result()
pg_fetch_row()
pg_field_is_null()
pg_field_name()
pg_field_num()
pg_field_prtlen()
pg_field_size()
pg_field_type()
pg_free_result()
pg_get_notify()
pg_get_pid()
pg_get_result()
pg_host()
pg_insert()
pg_last_error()
pg_last_notice()
pg_last_oid()
pg_lo_close()
pg_lo_create()
pg_lo_export()
pg_lo_import()
pg_lo_open()
pg_lo_read()
pg_lo_read_all()
pg_lo_seek()
pg_lo_tell()
pg_lo_unlink()
pg_lo_write()
pg_meta_data()
pg_num_fields()
pg_num_rows()
pg_options()
pg_parameter_status()
pg_pconnect()
pg_ping()
pg_port()
pg_put_line()
pg_query()
pg_result_error()
pg_result_seek()
pg_result_status()
pg_select()
pg_send_query()
pg_set_client_encoding()
pg_trace()
pg_tty()
pg_unescape_bytea()
pg_untrace()
pg_update()
pg_version()
php_check_syntax()
php_ini_scanned_files()
php_logo_guid()
php_register_url_stream_wrapper()
php_sapi_name()
php_stream_can_cast()
php_stream_cast()
php_stream_close()
php_stream_closedir()
php_stream_copy_to_mem()
php_stream_copy_to_stream()
php_stream_eof()
php_stream_filter_register_factory()
php_stream_filter_unregister_factory()
php_stream_flush()
php_stream_fopen_from_file()
php_stream_fopen_temporary_file()
php_stream_fopen_tmpfile()
php_stream_getc()
php_stream_gets()
php_stream_is()
php_stream_is_persistent()
php_stream_make_seekable()
php_stream_open_wrapper()
php_stream_open_wrapper_as_file()
php_stream_open_wrapper_ex()
php_stream_opendir()
php_stream_passthru()
php_stream_read()
php_stream_readdir()
php_stream_rewinddir()
php_stream_seek()
php_stream_sock_open_from_socket()
php_stream_sock_open_host()
php_stream_sock_open_unix()
php_stream_stat()
php_stream_stat_path()
php_stream_tell()
php_stream_write()
php_strip_whitespace()
php_uname()
php_unregister_url_stream_wrapper()
phpcredits()
phpinfo()
phpversion()
pi()
png2wbmp()
popen()
pos()
posix_ctermid()
posix_get_last_error()
posix_getcwd()
posix_getegid()
posix_geteuid()
posix_getgid()
posix_getgrgid()
posix_getgrnam()
posix_getgroups()
posix_getlogin()
posix_getpgid()
posix_getpgrp()
posix_getpid()
posix_getppid()
posix_getpwnam()
posix_getpwuid()
posix_getrlimit()
posix_getsid()
posix_getuid()
posix_isatty()
posix_kill()
posix_mkfifo()
posix_setegid()
posix_seteuid()
posix_setgid()
posix_setpgid()
posix_setsid()
posix_setuid()
posix_strerror()
posix_times()
posix_ttyname()
posix_uname()
pow()
preg_grep()
preg_match()
preg_match_all()
preg_quote()
preg_replace()
preg_replace_callback()
preg_split()
prev()
print()
print_r()
printer_abort()
printer_close()
printer_create_brush()
printer_create_dc()
printer_create_font()
printer_create_pen()
printer_delete_brush()
printer_delete_dc()
printer_delete_font()
printer_delete_pen()
printer_draw_bmp()
printer_draw_chord()
printer_draw_elipse()
printer_draw_line()
printer_draw_pie()
printer_draw_rectangle()
printer_draw_roundrect()
printer_draw_text()
printer_end_doc()
printer_end_page()
printer_get_option()
printer_list()
printer_logical_fontheight()
printer_open()
printer_select_brush()
printer_select_font()
printer_select_pen()
printer_set_option()
printer_start_doc()
printer_start_page()
printer_write()
printf()
proc_close()
proc_get_status()
proc_nice()
proc_open()
proc_terminate()
pspell_add_to_personal()
pspell_add_to_session()
pspell_check()
pspell_clear_session()
pspell_config_create()
pspell_config_data_dir()
pspell_config_dict_dir()
pspell_config_ignore()
pspell_config_mode()
pspell_config_personal()
pspell_config_repl()
pspell_config_runtogether()
pspell_config_save_repl()
pspell_new()
pspell_new_config()
pspell_new_personal()
pspell_save_wordlist()
pspell_store_replacement()
pspell_suggest()
putenv()

R

rad2deg()
rand()
range()
Rar::extract()
Rar::getAttr()
Rar::getCrc()
Rar::getFileTime()
Rar::getHostOs()
Rar::getMethod()
Rar::getName()
Rar::getPackedSize()
Rar::getUnpackedSize()
Rar::getVersion()
rar_close()
rar_entry_get()
rar_list()
rar_open()
rawurldecode()
rawurlencode()
read_exif_data()
readdir()
readfile()
readgzfile()
readline()
readline_add_history()
readline_callback_handler_install()
readline_callback_handler_remove()
readline_callback_read_char()
readline_clear_history()
readline_completion_function()
readline_info()
readline_list_history()
readline_on_new_line()
readline_read_history()
readline_redisplay()
readline_write_history()
readlink()
realpath()
recode()
recode_file()
recode_string()
RecursiveDirectoryIterator::getChildren()
RecursiveDirectoryIterator::hasChildren()
RecursiveDirectoryIterator::key()
RecursiveDirectoryIterator::next()
RecursiveDirectoryIterator::rewind()
RecursiveIteratorIterator::current()
RecursiveIteratorIterator::getDepth()
RecursiveIteratorIterator::getSubIterator()
RecursiveIteratorIterator::key()
RecursiveIteratorIterator::next()
RecursiveIteratorIterator::rewind()
RecursiveIteratorIterator::valid()
register_shutdown_function()
register_tick_function()
rename()
rename_function()
reset()
restore_error_handler()
restore_exception_handler()
restore_include_path()
result->current_field()
result->data_seek()
result->fetch_array()
result->fetch_field()
result->fetch_field_direct()
result->fetch_fields()
result->fetch_object()
result->fetch_row()
result->field_count()
result->field_seek()
result->free()
result->lengths()
rewind()
rewinddir()
rmdir()
round()
rsort()
rtrim()

S

scandir()
sem_acquire()
sem_get()
sem_release()
sem_remove()
serialize()
sesam_affected_rows()
sesam_commit()
sesam_connect()
sesam_diagnostic()
sesam_disconnect()
sesam_errormsg()
sesam_execimm()
sesam_fetch_array()
sesam_fetch_result()
sesam_fetch_row()
sesam_field_array()
sesam_field_name()
sesam_free_result()
sesam_num_fields()
sesam_query()
sesam_rollback()
sesam_seek_row()
sesam_settransaction()
session_cache_expire()
session_cache_limiter()
session_commit()
session_decode()
session_destroy()
session_encode()
session_get_cookie_params()
session_id()
session_is_registered()
session_module_name()
session_name()
session_regenerate_id()
session_register()
session_save_path()
session_set_cookie_params()
session_set_save_handler()
session_start()
session_unregister()
session_unset()
session_write_close()
set_error_handler()
set_exception_handler()
set_file_buffer()
set_include_path()
set_magic_quotes_runtime()
set_time_limit()
setcookie()
setlocale()
setrawcookie()
settype()
sha1()
sha1_file()
shell_exec()
shm_attach()
shm_detach()
shm_get_var()
shm_put_var()
shm_remove()
shm_remove_var()
shmop_close()
shmop_delete()
shmop_open()
shmop_read()
shmop_size()
shmop_write()
show_source()
shuffle()
similar_text()
simplexml_import_dom()
simplexml_load_file()
simplexml_load_string()
SimpleXMLElement->asXML()
SimpleXMLElement->attributes()
SimpleXMLElement->children()
SimpleXMLElement->xpath()
SimpleXMLIterator::current()
SimpleXMLIterator::getChildren()
SimpleXMLIterator::hasChildren()
SimpleXMLIterator::key()
SimpleXMLIterator::next()
SimpleXMLIterator::rewind()
SimpleXMLIterator::valid()
sin()
sinh()
sizeof()
sleep()
snmp_get_quick_print()
snmp_get_valueretrieval()
snmp_read_mib()
snmp_set_enum_print()
snmp_set_oid_numeric_print()
snmp_set_quick_print()
snmp_set_valueretrieval()
snmpget()
snmpgetnext()
snmprealwalk()
snmpset()
snmpwalk()
snmpwalkoid()
SoapClient::__call()
SoapClient::__getFunctions()
SoapClient::__getLastRequest()
SoapClient::__getLastResponse()
SoapClient::__getTypes()
SoapClient::SoapClient()
SoapFault::SoapFault()
SoapHeader::SoapHeader()
SoapParam::SoapParam()
SoapServer::addFunction()
SoapServer::getFunctions()
SoapServer::handle()
SoapServer::setClass()
SoapServer::setPersistence()
SoapServer::SoapServer()
SoapVar::SoapVar()
socket_accept()
socket_bind()
socket_clear_error()
socket_close()
socket_connect()
socket_create()
socket_create_listen()
socket_create_pair()
socket_get_option()
socket_get_status()
socket_getpeername()
socket_getsockname()
socket_last_error()
socket_listen()
socket_read()
socket_recv()
socket_recvfrom()
socket_select()
socket_send()
socket_sendto()
socket_set_block()
socket_set_blocking()
socket_set_nonblock()
socket_set_option()
socket_set_timeout()
socket_shutdown()
socket_strerror()
socket_write()
sort()
soundex()
spl_classes()
split()
spliti()
sprintf()
sql_regcase()
sqlite_array_query()
sqlite_busy_timeout()
sqlite_changes()
sqlite_close()
sqlite_column()
sqlite_create_aggregate()
sqlite_create_function()
sqlite_current()
sqlite_error_string()
sqlite_escape_string()
sqlite_exec()
sqlite_factory()
sqlite_fetch_all()
sqlite_fetch_array()
sqlite_fetch_column_types()
sqlite_fetch_object()
sqlite_fetch_single()
sqlite_fetch_string()
sqlite_field_name()
sqlite_has_more()
sqlite_has_prev()
sqlite_last_error()
sqlite_last_insert_rowid()
sqlite_libencoding()
sqlite_libversion()
sqlite_next()
sqlite_num_fields()
sqlite_num_rows()
sqlite_open()
sqlite_popen()
sqlite_prev()
sqlite_query()
sqlite_rewind()
sqlite_seek()
sqlite_single_query()
sqlite_udf_decode_binary()
sqlite_udf_encode_binary()
sqlite_unbuffered_query()
sqrt()
srand()
sscanf()
ssh2_auth_none()
ssh2_auth_password()
ssh2_auth_pubkey_file()
ssh2_connect()
ssh2_exec()
ssh2_fetch_stream()
ssh2_fingerprint()
ssh2_methods_negotiated()
ssh2_scp_recv()
ssh2_scp_send()
ssh2_sftp()
ssh2_sftp_lstat()
ssh2_sftp_mkdir()
ssh2_sftp_readlink()
ssh2_sftp_realpath()
ssh2_sftp_rename()
ssh2_sftp_rmdir()
ssh2_sftp_stat()
ssh2_sftp_symlink()
ssh2_sftp_unlink()
ssh2_shell()
ssh2_tunnel()
stat()
stmt->bind_param()
stmt->bind_result()
stmt->data_seek()
stmt->execute()
stmt->fetch()
stmt->free_result()
stmt->num_rows()
stmt->param_count()
stmt->prepare()
stmt->reset()
stmt->send_long_data()
str_ireplace()
str_pad()
str_repeat()
str_replace()
str_rot13()
str_shuffle()
str_split()
str_word_count()
strcasecmp()
strchr()
strcmp()
strcoll()
strcspn()
stream_context_create()
stream_context_get_default()
stream_context_get_options()
stream_context_set_option()
stream_context_set_params()
stream_copy_to_stream()
stream_filter_append()
stream_filter_prepend()
stream_filter_register()
stream_filter_remove()
stream_get_contents()
stream_get_filters()
stream_get_line()
stream_get_meta_data()
stream_get_transports()
stream_get_wrappers()
stream_register_wrapper()
stream_select()
stream_set_blocking()
stream_set_timeout()
stream_set_write_buffer()
stream_socket_accept()
stream_socket_client()
stream_socket_enable_crypto()
stream_socket_get_name()
stream_socket_pair()
stream_socket_recvfrom()
stream_socket_sendto()
stream_socket_server()
stream_wrapper_register()
stream_wrapper_restore()
stream_wrapper_unregister()
strftime()
strip_tags()
stripcslashes()
stripos()
stripslashes()
stristr()
strlen()
strnatcasecmp()
strnatcmp()
strncasecmp()
strncmp()
strpbrk()
strpos()
strptime()
strrchr()
strrev()
strripos()
strrpos()
strspn()
strstr()
strtok()
strtolower()
strtotime()
strtoupper()
strtr()
strval()
substr()
substr_compare()
substr_count()
substr_replace()
swf_actiongeturl()
swf_actiongotoframe()
swf_actiongotolabel()
swf_actionnextframe()
swf_actionplay()
swf_actionprevframe()
swf_actionsettarget()
swf_actionstop()
swf_actiontogglequality()
swf_actionwaitforframe()
swf_addbuttonrecord()
swf_addcolor()
swf_closefile()
swf_definebitmap()
swf_definefont()
swf_defineline()
swf_definepoly()
swf_definerect()
swf_definetext()
swf_endbutton()
swf_enddoaction()
swf_endshape()
swf_endsymbol()
swf_fontsize()
swf_fontslant()
swf_fonttracking()
swf_getbitmapinfo()
swf_getfontinfo()
swf_getframe()
swf_labelframe()
swf_lookat()
swf_modifyobject()
swf_mulcolor()
swf_nextid()
swf_oncondition()
swf_openfile()
swf_ortho()
swf_ortho2()
swf_perspective()
swf_placeobject()
swf_polarview()
swf_popmatrix()
swf_posround()
swf_pushmatrix()
swf_removeobject()
swf_rotate()
swf_scale()
swf_setfont()
swf_setframe()
swf_shapearc()
swf_shapecurveto()
swf_shapecurveto3()
swf_shapefillbitmapclip()
swf_shapefillbitmaptile()
swf_shapefilloff()
swf_shapefillsolid()
swf_shapelinesolid()
swf_shapelineto()
swf_shapemoveto()
swf_showframe()
swf_startbutton()
swf_startdoaction()
swf_startshape()
swf_startsymbol()
swf_textwidth()
swf_translate()
swf_viewport()
swfaction()
swfbitmap()
SWFBitmap->getHeight()
SWFBitmap->getWidth()
swfbutton()
SWFbutton->addAction()
SWFbutton->addShape()
SWFbutton->setAction()
SWFbutton->setdown()
SWFbutton->setHit()
SWFbutton->setOver()
SWFbutton->setUp()
swfbutton_keypress()
swfdisplayitem()
SWFDisplayItem->addColor()
SWFDisplayItem->move()
SWFDisplayItem->moveTo()
SWFDisplayItem->multColor()
SWFDisplayItem->remove()
SWFDisplayItem->Rotate()
SWFDisplayItem->rotateTo()
SWFDisplayItem->scale()
SWFDisplayItem->scaleTo()
SWFDisplayItem->setDepth()
SWFDisplayItem->setName()
SWFDisplayItem->setRatio()
SWFDisplayItem->skewX()
SWFDisplayItem->skewXTo()
SWFDisplayItem->skewY()
SWFDisplayItem->skewYTo()
swffill()
SWFFill->moveTo()
SWFFill->rotateTo()
SWFFill->scaleTo()
SWFFill->skewXTo()
SWFFill->skewYTo()
swffont()
swffont->getwidth()
swfgradient()
SWFGradient->addEntry()
swfmorph()
SWFMorph->getshape1()
SWFMorph->getshape2()
swfmovie()
SWFMovie->add()
SWFMovie->nextframe()
SWFMovie->output()
swfmovie->remove()
SWFMovie->save()
SWFMovie->setbackground()
SWFMovie->setdimension()
SWFMovie->setframes()
SWFMovie->setrate()
SWFMovie->streammp3()
swfshape()
SWFShape->addFill()
SWFShape->drawCurve()
SWFShape->drawCurveTo()
SWFShape->drawLine()
SWFShape->drawLineTo()
SWFShape->movePen()
SWFShape->movePenTo()
SWFShape->setLeftFill()
SWFShape->setLine()
SWFShape->setRightFill()
swfsprite()
swfsprite->add()
SWFSprite->nextframe()
SWFSprite->remove()
SWFSprite->setframes()
swftext()
SWFText->addString()
SWFText->getWidth()
SWFText->moveTo()
SWFText->setColor()
SWFText->setFont()
SWFText->setHeight()
SWFText->setSpacing()
swftextfield()
SWFTextField->addstring()
SWFTextField->align()
SWFTextField->setbounds()
SWFTextField->setcolor()
SWFTextField->setFont()
SWFTextField->setHeight()
SWFTextField->setindentation()
SWFTextField->setLeftMargin()
SWFTextField->setLineSpacing()
SWFTextField->setMargins()
SWFTextField->setname()
SWFTextField->setrightMargin()
sybase_affected_rows()
sybase_close()
sybase_connect()
sybase_data_seek()
sybase_deadlock_retry_count()
sybase_fetch_array()
sybase_fetch_assoc()
sybase_fetch_field()
sybase_fetch_object()
sybase_fetch_row()
sybase_field_seek()
sybase_free_result()
sybase_get_last_message()
sybase_min_client_severity()
sybase_min_error_severity()
sybase_min_message_severity()
sybase_min_server_severity()
sybase_num_fields()
sybase_num_rows()
sybase_pconnect()
sybase_query()
sybase_result()
sybase_select_db()
sybase_set_message_handler()
sybase_unbuffered_query()
symlink()
syslog()
system()

X

xattr_get()
xattr_list()
xattr_remove()
xattr_set()
xattr_supported()
xdiff_file_diff()
xdiff_file_diff_binary()
xdiff_file_merge3()
xdiff_file_patch()
xdiff_file_patch_binary()
xdiff_string_diff()
xdiff_string_diff_binary()
xdiff_string_merge3()
xdiff_string_patch()
xdiff_string_patch_binary()
xml_error_string()
xml_get_current_byte_index()
xml_get_current_column_number()
xml_get_current_line_number()
xml_get_error_code()
xml_parse()
xml_parse_into_struct()
xml_parser_create()
xml_parser_create_ns()
xml_parser_free()
xml_parser_get_option()
xml_parser_set_option()
xml_set_character_data_handler()
xml_set_default_handler()
xml_set_element_handler()
xml_set_end_namespace_decl_handler()
xml_set_external_entity_ref_handler()
xml_set_notation_decl_handler()
xml_set_object()
xml_set_processing_instruction_handler()
xml_set_start_namespace_decl_handler()
xml_set_unparsed_entity_decl_handler()
xmlrpc_decode()
xmlrpc_decode_request()
xmlrpc_encode()
xmlrpc_encode_request()
xmlrpc_get_type()
xmlrpc_is_fault()
xmlrpc_parse_method_descriptions()
xmlrpc_server_add_introspection_data()
xmlrpc_server_call_method()
xmlrpc_server_create()
xmlrpc_server_destroy()
xmlrpc_server_register_introspection_callback()
xmlrpc_server_register_method()
xmlrpc_set_type()
xpath_eval()
xpath_eval_expression()
xpath_new_context()
xptr_eval()
xptr_new_context()
xsl_xsltprocessor_get_parameter()
xsl_xsltprocessor_has_exslt_support()
xsl_xsltprocessor_import_stylesheet()
xsl_xsltprocessor_register_php_functions()
xsl_xsltprocessor_remove_parameter()
xsl_xsltprocessor_set_parameter()
xsl_xsltprocessor_transform_to_doc()
xsl_xsltprocessor_transform_to_uri()
xsl_xsltprocessor_transform_to_xml()
xslt_backend_info()
xslt_backend_name()
xslt_backend_version()
xslt_create()
xslt_errno()
xslt_error()
xslt_free()
xslt_getopt()
xslt_process()
xslt_set_base()
xslt_set_encoding()
xslt_set_error_handler()
xslt_set_log()
xslt_set_object()
xslt_set_sax_handler()
xslt_set_sax_handlers()
xslt_set_scheme_handler()
xslt_set_scheme_handlers()
xslt_setopt()