Manuale PHP

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

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

17-07-2004

Copyright

Questo manuale è © Copyright 1997-2004 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.

I membri del gruppo di Documentazione PHP (PHP Documentation Group) sono elencati nella pagina iniziale di questo manuale. In caso si desideri contattare il gruppo, scrivere a phpdoc@lists.php.net.

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
I. Guida Rapida
1. Introduzione
2. Una semplice introduzione
3. Installazione
4. Runtime Configuration
II. Struttura del Linguaggio
5. Sintassi Fondamentale
6. Types
7. Variables
8. Costanti
9. Expressions
10. Operatori
11. Strutture di controllo
12. Funzioni
13. Classi e Oggetti
14. Classes and Objects (PHP 5)
15. Spiegazioni sui riferimenti
III. Security
16. Security
IV. Caratteristiche
17. Autenticazione HTTP usando PHP
18. Cookies
19. Dealing with XForms
20. Caricare file
21. Utilizzo di file remoti
22. Gestione della connessione
23. Connessioni Persistenti ai Database
24. Modalità sicura (Safe mode)
25. Utilizzo di PHP da linea di comando
V. Guida Funzioni
I. Funzioni Apache
II. Funzioni di Array
III. Funzioni Aspell [deprecated]
IV. Funzioni Matematiche BCMath a precisione arbitraria
V. Funzioni di compressione Bzip2
VI. Funzioni Calendar
VII. Funzioni API CCVS [deprecate]
VIII. Funzioni di supporto COM per Windows
IX. Funzioni per Classi/Oggetti
X. Funzioni ClibPDF
XI. Funzioni di Crack
XII. Funzioni CURL, Client URL Library
XIII. Funzioni di pagamento Cybercash
XIV. Funzioni di amministrazione Cyrus IMAP
XV. Funzioni di tipo dei caratteri
XVI. Database (dbm-style) Abstraction Layer Functions
XVII. Funzioni di Data e Ora
XVIII. Funzioni dBase
XIX. Funzioni DBM
XX. dbx Functions
XXI. DB++ Functions
XXII. Funzioni per l'IO diretto
XXIII. Funzioni per le directory
XXIV. DOM Functions
XXV. Funzioni DOM XML
XXVI. Funzioni .NET
XXVII. Funzioni di gestione degli errori e di logging
XXVIII. File Alteration Monitor Functions
XXIX. FrontBase Functions
XXX. Funzioni filePro
XXXI. Filesystem functions
XXXII. Funzioni Forms Data Format
XXXIII. Funzioni FriBiDi
XXXIV. Funzioni FTP
XXXV. Function Handling Functions
XXXVI. Gettext
XXXVII. Funzioni GMP
XXXVIII. Funzioni HTTP
XXXIX. Hyperwave Functions
XL. Hyperwave API Functions
XLI. funzioni iconv
XLII. Funzioni per le immagini
XLIII. IMAP, POP3 and NNTP Functions
XLIV. Informix Functions
XLV. Funzioni InterBase
XLVI. ID3 Functions
XLVII. Ingres II Functions
XLVIII. IRC Gateway Functions
XLIX. PHP / Java Integration
L. LDAP Functions
LI. LZF Functions
LII. Funzioni di Mail
LIII. mailparse Functions
LIV. Funzioni Matematiche
LV. Multibyte String Functions
LVI. MCAL Functions
LVII. Mcrypt Encryption Functions
LVIII. MCVE Payment Functions
LIX. Memcache Functions
LX. Mhash Functions
LXI. Mimetype Functions
LXII. Funzioni per Microsoft SQL Server
LXIII. Ming functions for Flash
LXIV. Miscellaneous Functions
LXV. mnoGoSearch Functions
LXVI. mSQL Functions
LXVII. MySQL Functions
LXVIII. Improved MySQL Extension
LXIX. Mohawk Software Session Handler Functions
LXX. muscat Functions
LXXI. Funzioni di rete
LXXII. Ncurses Terminal Screen Control Functions
LXXIII. Lotus Notes Functions
LXXIV. NSAPI-specific Functions
LXXV. Funzioni ODBC Unificate
LXXVI. Object Aggregation/Composition Functions
LXXVII. Funzioni Oracle 8
LXXVIII. OpenSSL Functions
LXXIX. Funzioni Oracle
LXXX. Ovrimos SQL Functions
LXXXI. Output Control Functions
LXXXII. Proprietà object e method call overloading
LXXXIII. PDF functions
LXXXIV. Verisign Payflow Pro Functions
LXXXV. PHP Opzioni&Informazioni
LXXXVI. Funzioni POSIX
LXXXVII. Funzioni PostgreSQL
LXXXVIII. Process Control Functions
LXXXIX. Funzioni per l'esecuzione di programmi
XC. Funzioni per le Stampanti
XCI. Pspell Functions
XCII. GNU Readline
XCIII. GNU Recode Functions
XCIV. Funzioni per le espressioni regolari (Perl compatibili)
XCV. Funzioni qtdom
XCVI. Funzioni per le espressioni regolari (POSIX estesa)
XCVII. Funzioni per i semafori, la memoria condivisa ed IPC
XCVIII. SESAM Database Functions
XCIX. Funzioni di gestione della sessione
C. Funzioni relative alla memoria condivisa
CI. SimpleXML functions
CII. SOAP Functions
CIII. SQLite
CIV. Shockwave Flash Functions
CV. Funzioni per SNMP
CVI. Funzioni relative ai Socket
CVII. Standard PHP Library (SPL) Functions
CVIII. Stream Functions
CIX. Stringhe
CX. Sybase Functions
CXI. TCP Wrappers Functions
CXII. Tidy Functions
CXIII. Tokenizer Functions
CXIV. URL Functions
CXV. Funzioni di Variabili
CXVI. Funzioni vpopmail
CXVII. Funzioni W32api
CXVIII. WDDX Functions
CXIX. Funzioni relative al parser XML
CXX. Funzioni XMLRPC
CXXI. xdiff Functions
CXXII. XSL functions
CXXIII. Funzioni XSLT
CXXIV. YAZ Functions
CXXV. YP/NIS Functions
CXXVI. Funzioni per File Zip (Accesso di Sola Lettura)
CXXVII. Funzioni di compressione Zlib
VI. Zend API
26. Overview
27. Extension Possibilities
28. Source Layout
29. PHP's Automatic Build System
30. Creating Extensions
31. Using Extensions
32. Troubleshooting
33. Source Discussion
34. Accepting Arguments
35. Creating Variables
36. Duplicating Variable Contents: The Copy Constructor
37. Returning Values
38. Printing Information
39. Startup and Shutdown Functions
40. Calling User Functions
41. Initialization File Support
42. Where to Go from Here
43. Reference: Some Configuration Macros
44. API Macros
VII. PHP API: Interfacce per gli autori di estensioni
45. Streams API for PHP Extension Authors
VIII. FAQ: Frequently Asked Questions (domande e risposte ricorrenti)
46. Informazioni Generali
47. Mailing list
48. Ottenere PHP
49. Database issues
50. Installazione
51. Problemi di installazione
52. Using PHP
53. PHP and HTML
54. PHP e COM
55. PHP e gli altri linguaggi di programmazione
56. Migrazione da PHP 2 a PHP 3
57. Migrazione da PHP 3 a PHP 4
58. 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. Extending PHP 3
G. Configure options
H. List of core php.ini directives
I. Lista dei sinonimi delle funzioni PHP
J. Parole riservate nel PHP
K. List of Resource Types
L. List of Supported Protocols/Wrappers
M. List of Available Filters
N. List of Supported Socket Transports
O. PHP type comparison tables
P. List of Parser Tokens
Q. Informazioni sul manuale
R. Open Publication License
S. Indice delle Funzioni
T. 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'.

Vedere anche: Storia del PHP.


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


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. 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 (task scheduler di Windows) o per tasks di solo testo. Vedere la sezione Uso di righe di comando in PHP per maggiori informazioni.

  • La creazione di applicazioni client-side GUI. Probabilmente PHP non è il linguaggio più adatto per scrivere applicazioni windowing, 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 dalla versione corrente di PHP, molte librerie di codice e grandi applicazioni (compresa PEAR library) sono state scritte usando codice OOP.

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 DIngresOracle (OCI7 and OCI8)
dBaseInterBaseOvrimos
EmpressFrontBasePostgreSQL
FilePro (read-only)mSQLSolid
HyperwaveDirect MS-SQLSybase
IBM DB2MySQLVelocis
InformixODBCUnix dbm

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, supportiamo gli standard SAX e DOM. Si può usare la nostra estensione XSLT per trasformare i documenti XML.

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

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


Considerazioni generali sull'installazione

Prima di installare, occorre sapere che cosa dsi desidera fare con il PHP. Esistono tre campi principali in cui utilizzare il PHP, come descritto nella sezione Cosa può fare il PHP?:

  • Scripting Server-side

  • Scripting da linea di comando

  • Applicazioni GUI Client-side

Per il primo, e più comune utilizzo, occorrono tre cose: il PHP, un server web ed un browser web. Probabilmente si possiede già un browser web, e, in base alla configurazione del sistema operativo, si potrebbe anche avere un server web (es. Apache su Linux, oppure IIS su Windows). Si potrebbe anche affittare dello spazio web da una azienda. In Questo caso non si ha nulla da impostare, ma soltanto scrivere gli script PHP, scaricarli sul server che si è affittato, e vedere il risultato.

Nel caso si decida di attivare web ed PHP in autonomia, si hanno due metodologie per collegare il PHP al server web. Per molti server il PHP ha un modulo apposito (chiamato anche SAPI). Tra questi: Apache, Microsoft Internet Information Server, Netscape e iPlanet servers. Diversi altri server hanno il supporto per ISAPI, il modulo d'interfaccia Microsoft (OmniHTTPd ad esempio). Se il PHP non ha un modulo per il server web prescelto, si può sempre utilizzare il PHP come CGI. Ciò significa configurare il server per eseguirà la versione da linea di comando di PHP (php.exe su Windows) per processare tutti i file PHP richiesti al server.

Se si è interessati ad utilizzare PHP da linea di comando (es. sviluppare script che producano immagini offline, o che elaborino file di testo in base a parametri passati), occorre avere l'eseguibile per la linea di comando. Per maggiori dettagli, leggere la sezione su scrivere applicazioni PHP da linea di comando. In questo caso non occorre ne il serve web, ne il browser.

Con il PHP si possono anche scrivere applicazioni grafiche client-side utlizzando l'estensione PHP-GTK. In questo caso si ha un approccio completamente differente rispetto a scrivere una pagina web, dato che non si produce codice HTML, ma si gestiscono finestre e oggetti all'interno di queste. Per maggiori dettagli su PHP-GTK, visitare il sito dedicato a questa estensione. PHP-GTK non è incluso nella distribuzione ufficiale di PHP.

Da questo punto in poi, questo capitolo tratterà come settare il PHP con vari server web sia su Unix sia su Windows con i moduli per i server oppure come CGI.

Si può scaricare i sorgenti e gli eseguibili per Windows da http://www.php.net/downloads.php. Si suggerisce di utilizzare il mirror più vicino per scaricare le distribuzioni.


Installazione su Unix/HP-UX

Questa sezione contiene note e suggerimenti per l'installazione di PHP su sistemi HP-UX. (Contributo di paul_mckay at clearwater-it dot co dot uk).

Nota: Queste note sono state scritte per PHP 4.0.4 e Apache 1.3.9.

  1. Occorre gzip, scaricare l'eseguibile da http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z decomprimere il file e installarlo con swinstall.

  2. Serve gcc, scaricare la distribuzione con l'eseguibile da http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz. decomprimere il file e installare gcc con swinstall.

  3. Occorrono le binutils GNU, si possono scaricare da http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz. decomprimere il file e installare le binutils con swinstall.

  4. A questo punto serve bison, scaricare la distribuzione con l'eseguibile da http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz, installare come i precedenti

  5. Ora serve flex, occorre scaricare il sorgente da uno dei mirror di http://www.gnu.org. Si trova in una directory non GNU del sito ftp. Scaricare il file, gunzip, quindi tar -xvf. Entrare nella directory di flex appena creata ed eseguire ./configure, seguito da make, e quindi make install.

    Se si verifica un errore, probabilmente è dovuto al fatto che gcc o uno degli altri eseguibili non si trovano in PATH, pertanto aggiungerli in PATH.

  6. Scaricare i sorgenti di PHP e Apache.

  7. Eseguire gunzip e tar -xvf. Ora dobbiamo modificare un paio di file in modo da poterli compilare.

  8. Per primo il file configure, occorre modificarlo perchè sembra che perda traccia del fatto di essere su una macchina hpux, esistono metodi migliori per fare ciò, ma il più semplice consiste nel mettere lt_target=hpux10.20 alla linea 47286 di configure.

  9. Quindi occorre intervenire sul file di Apache GuessOS. Nella directory apache_1.3.9/src/helpers cambiare la linea 89 da echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 a: echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0

  10. Non si può installare il PHP come oggetto condiviso in HP-UX, pertanto occorre compilarlo come statico, basta seguire le istruzioni alla pagina di Apache.

  11. PHP e Apache dovrebbero essersi compilati correttamente, ma Apache non parte. Occorre creare un nuovo utente per Apache, es www, o apache. Quindi cambiare le linee 252 e 253 del file conf/httpd.conf di Apache in questo modo:

    User nobody 
    Group nogroup

    si dovrebbe avere qualcosa tipo

    User www 
    Group sys

    Questo perchè non si può eseguire Apache come utente nobody in HP-UX. A questo punto Apache e PHP dovrebbero funzionare.


Installazione su Unix/Linux

Questa sezione contiene note e suggerimenti specifici dell'installazione di PHP su distribuzioni Unix.


Uso dei pacchetti

Diverse distribuzioni Linux hanno un qualche metodo per installare i pacchetti tipo RPM. Questo può aiutare nell'impostare una configurazione standard, ma se si desidera avere delle caratteristiche differenti (tipo un server sicuro, driver per database differenti) occorre compilare il PHP e/o il server web. Se non si è pratici nella compilazione del software, potrebbe essere conveniente cercare qualcuno che abbia già pacchettizzato una versione di PHP con le caratteristiche desiderate.


Unix/Mac OS X installs

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


Using Packages

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


Compiling for OS X server

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

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

Those tips are graciously provided by Marc Liyanage.

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

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

Do this to install:

  1. Open a terminal window.

  2. Type wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz, wait for 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.


Unix/OpenBSD installs

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


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.3.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.3.tgz or php4-imap-4.3.3.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Esempio 3-1. OpenBSD Package Install Example

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

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


Using Ports

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


Unix/Solaris installs

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


Required software

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


Installation on Unix systems

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

Prerequisite knowledge and software:

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

  • An ANSI C compiler (if compiling)

  • flex (for compiling)

  • bison (for compiling)

  • A web server

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

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

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


Apache Module Quick Reference

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

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

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

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

Building

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


Installation on Windows systems

This section applies to Windows 98/Me and Windows NT/2000/XP. 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 InstallShield installer.

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

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


Windows InstallShield

The Windows PHP installer 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, configures the web server as well.

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

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

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

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

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

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 on your Windows webserver. The original version of this guide was compiled by Bob Silva, and can be found at http://www.umesd.k12.or.us/php/win32install.html. You need to download the zip binary distribution from the downloads page at http://www.php.net/downloads.php.

PHP 4 for Windows comes in three flavours - a CGI executable (php.exe), a CLI executable (sapi/php.exe) and some other SAPI modules:

php4apache.dll - Apache 1.3.x module
php4apache2.dll - Apache 2.0.x module
php4isapi.dll - ISAPI Module for ISAPI compliant webservers like IIS 4.0/PWS 4.0 or newer.
php4nsapi.dll - Netscape/iPlanet module

The latter form is new to PHP 4, and provides significantly improved performance and some new functionality. The CLI version is designed to 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 in the 4.1 release, however, you may find that you encounter possible server errors or other server modules such as ASP failing, in older systems.

DCOM and MDAC requirements: If you choose one of the SAPI modules and use Windows 95, be sure to download and install the DCOM update from the Microsoft DCOM pages. If you use Microsoft Windows 9x/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at http://msdn.microsoft.com/data/.

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

  • Extract the distribution file to a directory of your choice, c:\ is a good start. The zip package expands to a foldername like php-4.3.1-Win32 which is assumed to be renamed to php. For the sake of convenience and to be version independent the following steps assume your extracted version of PHP lives in c:\php. You might choose any other location but you probably do not want to use a path in which spaces are included (for example: C:\Program Files\PHP is not a good idea). Some web servers will crash if you do. The structure of your directory you extracted the zip file will look like:

c:\php
   |
   +--cli
   |  |
   |  |-php.exe           -- CLI executable - ONLY for commandline scripting
   |
   |
   +--dlls                -- support dlls for extensions --> Windows system directory
   |  |
   |  |-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 dlls
   |  |
   |  |-php4apache.dll
   |  |
   |  |-php4apache2.dll
   |  |
   |  |-php4isapi.dll
   |  |
   |  |-..
   |
   |-install.txt
   |
   |-..
   |
   |-php.exe              -- CGI executable
   |
   |-..
   |
   |-php.ini-dist
   |
   |-php.ini-recommended
   | 
   |-php4ts.dll           -- main dll --> Windows system directory
   | 
   |-...

The CGI binary - c:\php\php.exe -, the CLI binary - c:\php\cli\php.exe -, and the SAPI modules - c:\php\sapi\*.dll - rely on the main dll c:\php\php4ts.dll. You have to make sure, that this dll 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. In case you use a SAPI module the same directory from where your webserver loads the dll (e.g. php4apache.dll).
Any directory in your Windows PATH environment variable.

  • The best bet is to make php4ts.dll available, regardless which interface (CGI or SAPI module) you plan to use. To do so, you have to copy this dll to a directory on your Windows path. The best place is your Windows system directory:

    C:\Windows\System for Windows 9x/ME
    C:\WINNT\System32 for Windows NT/2000 or C:\WINNT40\System32 for NT/2000 server
    C:\Windows\System32 for Windows XP

    If you plan to use a SAPI module from c:\php\sapi and do not like to copy dlls to your Windows system directory, you have the alternative choice to simply copy php4ts.dll to the sapi folder of your extracted zip package, c:\php\sapi.

  • 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 and in addition 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 where PHP is able to find and rename it to php.ini. By default PHP searches php.ini in your Windows directory:

    On Windows 9x/ME/XP copy your chosen ini file to your %WINDIR%, which is typically C:\Windows.
    On Windows NT/2000 copy your chosen ini file to your %WINDIR% or %SYSTEMROOT%, which is typically C:\WINNT or C:\WINNT40 for NT/2000 servers.

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

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 webservers document_root. For example:

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

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

  • On PWS and IIS, you can set the browscap 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.

Following this instructions you are done with the basic steps to setup PHP on Windows. The next step is to choose a webserver and enable it to run PHP. Installation instructions for the following webservers are available:


Building from source

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

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

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


Requisiti

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

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

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


Putting it all together

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

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

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

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

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

Following this steps your directory structure looks like this:

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

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

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


Configure MVC ++

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

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

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

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


Build resolv.lib

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

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

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

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

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

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


Compiling

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

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

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

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

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

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

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

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.

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


Installation of Windows extensions

After installing PHP and a webserver on Windows, you will probably want to install some extensions for added functionality. 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_' in PHP 4 (and 'php3_' in PHP 3). This prevents confusion between PHP extensions and their supporting libraries.

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

The default location PHP searches for extensions is c:\php4\extensions. 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. Please do not forget the last backslash. 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 ; form the extension you want to load.

    Esempio 3-3. 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 but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. Copy the bundled DLLs from c:\php\dlls folder to your Windows PATH, safe places are:

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

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

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 3-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
php3_crypt.dllCrypt functionsunknown
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
php3_dbm.dllBerkeley DB2 libraryunknown
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.dllRead EXIF headers from JPEGNone
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 functionsPHP 3: php3_imap4r1.dll
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)
php3_msql1.dllmSQL 1 clientunknown
php3_msql2.dllmSQL 2 clientunknown
php_mssql.dllMSSQL functionsRequires: ntwdblib.dll (bundled)
php3_mysql.dllMySQL functionsBuilt-in in PHP 4
php3_nsmail.dllNetscape mail functionsunknown
php3_oci73.dllOracle functionsunknown
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_sockets.dllSocket functionsNone
php_sybase_ct.dllSybase functionsRequires: Sybase client libraries
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


Servers-CGI/linea di comando

Per default il PHP viene compilato come programma CGI. Ciò crea un interprete di linea di comando che può essere utilizzato sia per elaborazioni CGI sia per script non connessi con il web. Se si utilizza un server web il PHP ha dei moduli atti allo scopo, questa dovrebbe essere la soluzione preferenziale per ragioni di performance. Tuttavia la versione CGI permette agli utenti di Apache di eseguire pagine PHP sotto differenti user id. Se si desidera utilizzare il PHP come CGI è opportuno leggere con attenzione il capitolo Security chapter

Dalla versione 4.3.0 di PHP sono state inserite nuove caratteristiche. Una nuova SAPI, chiamata CLI, è stata aggiunta è ha lo stesso nome dell'eseguibile CGI. Che cosa si installa nella directory {PREFIX}/bin/php dipende dalla line di configurazione, ciò è descritto dettagliatamente nel capitolo Uso del PHP da linea di comando . Per maggiori dettagli leggere quel capitolo del manuale.


Testing

Se si ha compilato il PHP come programma CGI, si può testare l'eseguibile eseguendo make test. E' sempre una buona norma testare l'eseguibile che si è appena compilato. In questo modo si possono intercettare immediatamente eventuali problemi relativi alla piattaforma e non impazzire in una fase successiva.


Benchmarking

Se si compila il PHP 3 come programma CGI, si possono eseguire dei banchmark digitando make bench. Occorre notare che se si è abilitato il safe mode il benchmark non è in grado di concludersi correttamente se richiede più di 30 secondi. Questo perchè la funzione safe mode non può utilizzare la funzione set_time_limit(). Utilizzare il parametro max_execution_time per impostare il tempo massimo di esecuzione di uno script. Il comando make bench ignora il file di configurazione.

Nota: make bench è soltanto disponibile per PHP 3.


Utilizzo delle variabili

Alcuni server passano delle variabili d'ambiente che non sono definite nelle specifiche CGI/1.1. Soltanto le seguenti variabili sono standard, tutte le altre sono da considerarsi come estensioni del fornitore: 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 e SERVER_SOFTWARE


Server-Apache

Questa sezione contiene note e suggerimenti specifici dell'installazione di PHP con server Apache, sia per le versioni Unix sia per le versioni Windows. Esiste, inoltre, una pagina separata per le istruzioni e note su Apache 2.


Dettagli sull'installazione di PHP con Apache su Unix

Si possono selezionare gli argomenti da aggiungere al comando configure di linea 10 dalla Lista completa delle opzioni di configurazione. In queste note viene omesso il numero di versione per evitare di avere istruzioni non corrette. Nella realtà occorre sostituire 'xxx' con i valori di versione corretti.

Esempio 3-4. Istruzioni per l'installazione (versione di Apache con modulo condiviso) di PHP 4.

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx
10. Ora configuriamo il PHP. In questa fase si personalizza il PHP
    agendo sulle varie opzioni, tipo quali estensioni abilitare, Eseguire
    ./configure --help per avere una lista delle opzioni disponibili. Nell'esempio seguente si illustra 
    una semplice configurazione per il supporto di Apache 1 e MySQL. Il percorso a
    apxs nella vostra installazione può differire rispetto all'esempio.

    ./configure --with-mysql --with-apxs=/www/bin/apxs
10. ./configure --with-mysql --with-apxs=/www/bin/apxs
11. make
12. make install

  Se si decide di cambiare le opzioni di configurazione dopo l'installazione
  occorre ripere gli ultimi tre passi. Per attivare il nuovo modulo occorre
  riavviare Apache. Non è richiesta la ricompila di Apache.

  Nota: a meno di non avere dato indicazioni differenti, 'make install' installa anche PEAR,
  vari tools PHP tipo phpize e PHP CLI.

13. Configurazione del php.ini:
 
   cp php.ini-dist /usr/local/lib/php.ini

  Si può modificare il file .ini per impostare le opzioni di PHP.
  Se si desidera avere questo file in un'altra directory, utilizzare
  --with-config-file-path=/percorso al punto 10.

  Se si preferisce utilizzare php.ini-recommended, verificare l'elenco delle differenze rispetto 
  al php.ini e come queste influiscano sul comportamento del PHP.

14.  Modificare httpd.conf per caricare il modulo PHP.
     Il percorso nel lato destro dell'struzione LoadModule deve puntare  al percorso
     del modulo PHP nel sistema. Make install potrebbe averlo già aggiunto, 
     verificare per sicurezza.
  
     Con PHP 4:
       LoadModule php4_module libexec/libphp4.so

     Con PHP 45
       LoadModule php5_module libexec/libphp5.so

15. Nella sezione AddModule di httpd.conf, aggiungere sotto
    ClearModuleList:

    For PHP 4:  
      AddModule mod_php4.c
 
    For PHP 5: 
       AddModule mod_php5.c

16. Indicare ad Apache to considerare alcune estensioni tipo PHP.
    Si possono avere più estensioni interpretate come PHP aggiungendole alla riga usando 
    uno spazio tra una estensione e l'altra. Nell'esempio si aggiungerà l'estensione
    .phtml

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

    E' comune, inoltre, aggiungere l'estensione phps per visualizzare
    il codice PHP colorato. Ciò può essere fatto con:

        AddType application/x-httpd-php-source .phps

17. Utilizzare le normali procedure per avviare il server Apache. (Occorre
    riavviare il server, e non forzare una ricarica tramite i segnali
    HUP o USR1.)

In base all'installazione di Apache e al tipo di Unix, esistono vari modi per fermare e avviare il server. Di seguito saranno illustrati alcuni metodi tipici per riavviare il server in differenti configurazioni di Apache/unix. Si deve sostituire /path/to/ con il percorso in cui risiedono queste applicazioni nel sistema.

Esempio 3-5. Esempio della sequenza di comandi per riavviare Apache

1. Diverse varianti di Linux e SysV:
/etc/rc.d/init.d/httpd restart

2. Utilizzando apachectl:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl e httpsdctl (tramite OpenSSL), simile a apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Usando mod_ssl, o un'altro server SSL, si può fermare e riavviare
   il server manualmente:
/path/to/apachectl stop
/path/to/apachectl startssl

La directory degli eseguibili apachectl e http(s)dctl spesso varia. Se nel sistema esistono i comandi locate oppure whereis oppure which, si possono utilizzare per localizzare i programmi di controllo del server.

Di seguito saranno illustrati differenti esempi di compila di PHP per Apache:

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

Questo crea la libreria condivisa libphp4.so che è il modulo caricato da Apache tramite la linea LoadModule del file httpd.conf. Il supporto a PostgreSQL è compreso nella libreria libphp4.so.

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

Questo crea la libreria condivisa libphp4.so per Apache, ma crea anche una libreria condivisa pgsql.so che viene caricata in PHP o tramite le direttive del php.ini o caricata direttamente dallo script tramite la funzione dl().

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

Questo crea una libreria libmodphp4.a, un file mod_php4.c e altri file di contorno e li copia nella directory src/modules/php4 nell'albero dei sorgenti di Apache. Quindi si può compilare Apache utilizzando --activate-module=src/modules/php4/libphp4.a e quindi il sistema di compila di Apache creerà il file libphp4.a e lo includerà staticamente nell'eseguibile httpd. Il supporto per PostgreSQL verrà incluso direttamente in questo httpd, pertanto si avrà un unico eseguibile httpd comprendente tutto Apache e tutto il PHP.

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

Come l'istruzione precedente, tranne che invece di includere PostgreSQL direttamente nel file finale httpd, si avrà una libreria condivisa pgsql.so che può essere caricata in PHP o tramite le direttive del php.ini o direttamente dallo script tramite la funzione dl().

Quando si compila il PHP nei differenti modi, si dovrebbe considerare i vantaggi e gli svantaggi di ciascun metodo. Compilarlo come libreria condivisa permette di compilare Apache separatamente, e quindi non si ha la necessità di ricompilarlo ogni volta che si desideri cambiare il PHP. Compilare il PHP all'interno di Apache (in modo statico) permette al PHP di essere caricato ed eseguito più velocemente. Per maggiori dettagli vedere la pagian di Apache sul supporto DSO.

Nota: Attaulmente il file httpd.conf fornito di default contiene una sezione come la seguente:

User nobody
Group "#-1"

A meno che non venga cambiata in "Group nogroup" o qualcosa di simile (è anche comune l'uso di "Group daemon") il PHP non sarà in grado di aprire i file.

Nota: Accertarsi di avere specificato la versione di apxs installate quando si usa --with-apxs=/path/to/apxs. NON usare la versione di apxs presente nei sorgenti di Apache, ma quella installata nel sistema.


Installazione di PHP su Windows con Apache 1.3.x

Esistono due metodi per installare PHP e Apache 1.3.x in Windows. Uno consiste nell'utilizzare l'eseguibile CGI (php.exe), la seconda consiste nell'usare il modulo DLL per Apache. In entrambi i casi occorre fermare il server Apache, editare il file httpd.conf per indicare ad Apache di utilizzare PHP.

Occorre notare che ora il modulo SAPI sotto Windows è stato reso molto più stabile, noi raccomandiamo l'uso di questo piuttosto che l'eseguibile CGI poichè è molto più trasparente e sicuro.

Sebbene vi possano essere alcune varianti nella configurazione di PHP con Apache, queste sono abbastanza semplici da essere utilizzate dai neofiti. Consultare la documentazione di Apache per maggiori dettagli sulle direttive di configurazione.

Se si decomprime il pacchetto PHP nella directory c:\php\ come descritto nella sezione Passi per l'installazione manuale, occorre inserire queste linee nella configurazione di Apache per attivare l'eseguibile CGI:

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

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

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

Occorre rilevare che la seconda riga può essere presente nelle nuove versioni di httpd.conf, ma è commentata. Ricordarsi, inoltre, di sostituire c:/php/ con la corretta directory del PHP.

Avvertimento

Utilizzando la configurazione CGI, il server è aperto a possibili attacchi. Leggere il capitolo CGI security per imparare a difendersi da questi attacchi.

Se si desidera utilizzare PHP come modulo di Apache, occorre copiare php4ts.dll nella directory windows/system (per Windows 9x/Me), winnt/system32 (per Windows NT/2000) o windows/system32 (per Windows XP) sostituendo ogni vecchio file. Quindi si deve aggiungere le seguenti linee al file httpd.conf

  • Aprire httpd.conf con l'editor preferito e localizzare la direttiva LoadModule e aggiungere la seguente linea alla fine dell'elenco: LoadModule php4_module c:/php/sapi/php4apache.dll, oppure per il PHP 5 LoadModule php5_module "c:/php/sapi/php5apache.dll".

  • Si può rilevare che, dopo l'uso dell'installatore di Apache, occorre definire la direttiva AddModule per mod_php4.c. Questa è particolarmente importante se viene definita la direttiva ClearModuleList, che può essere trovata più sotto di qualche riga. Quando si troverà l'elenco delle istruzioni AddModule, aggiungere la seguente linea alla fine dell'elenco: AddModule mod_php4.c Per il PHP 5 utilizzare: AddModule mod_php5.c

  • Cercare una frase simile a # AddType allows you to tweak mime.types. Si troverà alcune righe tipo AddType, aggiungere la seguente linea alla fine dell'elenco: AddType application/x-httpd-php .php. Si può scegliere qualsiasi estensione si desideri elaborare tramite PHP. Da parte nostra suggeriamo .php. Si può anche includere .html e .php3 per avere compatibilità con il passato.

Dopo avere cambiato il file di configurazione, ricordarsi di riavviare il server, ad esempio, NET STOP APACHE seguito da NET START APACHE, se si esegue Apache come servizio di Windows, oppure utilizzare le opportune icone.

Esistono due metodi per attivare la funzionalità di visualizzazione del sorgente; tuttavia il loro funzionamento dipende dall'installazione. Se si ha configurato Apache per utilizzare PHP come modulo SAPI, allora aggiungendo la seguente linea al file httpd.conf (nello stesso punto in cui si è inserito AddType application/x-httpd-php .php) si può attivare questa caratteristica: AddType application/x-httpd-php-source .phps.

Se si è scelto di configurare Apache per utilizzare PHP come eseguibile CGI, allora occorre utilizzare la funzione show_source(). Per ottenere ciò creare uno script PHP e aggiungere questa riga: <?php show_source ("original_php_script.php"); ?>. Sostituire original_php_script.php con il nome del file di cui si vuole vedere il sorgente.

Nota: Nella versione Windows di Apache tutti i backslash nelle righe con percorsi tipo "c:\directory\file.ext", devono essere sostituiti con lo slash, tipo "c:/directory/file.ext".


Server-Apache 2.0

Questa sezione contiene note e suggerimenti specifici per l'installazione di PHP, con Apache 2.0, sia per sistemi Unix sia per sistemi Windows.

Avvertimento

Non utilizzare Apache 2.0 e PHP in ambienti di produzione sia con Unix sia con Windows.

Riteniamo sia opportuno dare uno sguardo alla Documentazione di Apache per avere le nozioni di base per comprendere Apache 2.0.


Note di compatibilità tra PHP e Apache 2.0

Se seguente versioni di PHP funzionano correttamente con le ultime versioni di Apache 2.0:

Queste versioni di PHP sono compatibili con Apache 2.0.40 e successive.

Nota: Il supporto tramite SAPI ad Apache 2.0 è cominciato da 4.2.0. PHP 4.2.3 funziona con Apache 2.0.39, non utilizzare nessuna altra versione di Apache con PHP 4.2.3. Tuttavia si raccomanda di utilizzare il PHP 4.3.0, o successivo, con la più recente versione di Apache2.

Tutte le versioni di PHP menzionate, lavorano con Apache 1.3.x.


PHP e Apache 2 su Linux

Scaricare la più recente versione di Apache 2.0 e la versione di PHP dai siti menzionati in precendenza. Questa guida rapida copre soltanto le basi per partire con Apache 2.0 e PHP. Per maggiori dettagli leggere la documentazione di Apache. In questo esempio è stata omesso il numero di versione per evitare problemi nelle istruzioni presentate. Nell'installazione reale occorre sostituire 'NN' con il corretto numero della versione installata.

Esempio 3-6. Istruzioni per l'installazione (Apache 2 con modulo condiviso)

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

    A questo punto si ha Apache 2.0 disponibile in /usr/local/apache2,
    configurato con il supporto dei moduli caricabili.
    Per testare l'installazione utilizzare la solita procedura per attivare il
    server Apache, es.:
    /usr/local/apache2/bin/apachectl start
    e quindi fermare il server per attivare la configurazione con PHP:
    /usr/local/apache2/bin/apachectl stop.

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

    Modificare il php.ini per impostare le opzioni di PHP.
    Se si desidera pozionare questo file in altra directory, utilizzare
    --with-config-file-path=/path al passo 10.

14. Modificare httpd.conf e verificare la presenza delle seguenti
    linee:
  
   LoadModule php4_module modules/libphp4.so
   AddType application/x-httpd-php .php

  Si può segliere qualsiasi estensione di desideri. Il nostro suggerimento
  è di utilizzare .php.

  Il percorso indicato nel lato destro della riga LoadModule deve puntare 
  al percorso in cui si trova il modulo PHP. L'esempio illustrato è coerente
  con i parametri sin qui impostati. 

15. Utilizzare la solita procedura per avviare Apache, es.:
   /usr/local/apache2/bin/apachectl start

Seguendo i passi illustrati si ottiene un server Apache 2.0 funzionante con il supporto PHP come modulo SAPI. Ovviamente esistono molte altre opzioni di configurazione sia per Apache sia per PHP. Per maggiori dettagli utilizzare ./configure --help nei sorgenti di ciascun prodotto. Nel caso si desideri compilare la versione multithread di Apache 2.0 occorre sovrascrivere il modulo MPM standard prefork con worker o con perchild. Per ottenere ciò accodare alla linea di configurazione indicata nel passo 6 l'opzione --with-mpm=worker o --with-mpm=perchild. Occorre essere consapevoli delle conseguenze di ciò che si sta facendo. Per maggiori dettagli leggere la documenatzione di Apache sul modulo MPM.

Nota: Per potere compilare la versione multithread di Apache occorre che il sistema supporti i thread. Questo implica la compila di PHP con il modulo sperimentale Zend Thread Safety (ZTS). Pertanto non tutte le estensioni potranno essere disponibili. Si raccomanda, quindi, di compilare Apache con il modulo MPM standard prefork.


PHP e Apache 2.0 su Windows

Si consideri di leggere le note specifiche per Windows di Apache 2.0.

Avvertimento

Apache 2.0 è concepito per essere eseguito su Windows NT 4.0, Windows 2000 oppure Windows XP. In questo momento il supporto per Windows 9x è incompleto. Al momento non ci si aspetta che Apache 2.0 funzioni su quest'ultime piattaforme.

Scaricare la più recente versione di Apache 2.0 e la versione di PHP dai siti menzionati in precendenza. Seguire i passi per l'installazione manuale e tornare a questo pagina per integrare il PHP con Apache.

Esistono due metodi per configurare PHP e Apache 2.0 su Windows. Uno consiste nell'uso dell'eseguibile CGI, l'altro consiste nell'utilizzo del modulo DLL per Apache. In entrambi i casi occorre fermare Apache, modificare il file httpd.conf per configurare Apache.

Occorre inserire queste tre linee nel file di configurazione httpd.conf di Apache per impostare l'eseguibile CGI:

Esempio 3-7. PHP con Apache 2.0 come CGI

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

Se si desidera utilizzare il PHP come modulo di Apache 2.0, occorre copiare php4ts.dll nella directory winnt/system32 (per Windows NT/2000) o windows/system32 (per Windows XP), sovrascrivendo gli eventuali vecchi file. Quindi occorre inserire queste due righe nel file di configurazione di Apache httpd.conf per impostare il modulo PHP

Esempio 3-8. PHP su Apache 2.0 come Modulo

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

Nota: Nei precedenti esempi ricordarsi di sostituire c:/php/ con il percorso alPHP. Prestare attenzione di avere impostato php4apache2.dll nella direttiva LoadModule e nonphp4apche.dll. Quest'ultimo è utilizzato per Apache 1.3.x.

Avvertimento

Non mischiare i file dll da differenti versioni di PHP. Si ha solo la possibilità di utilizzare le dll e le estensioni fornite con la versione scaricata.


Server-Caudium

Il PHP 4 può essere compilato come module Pike per il server web Caudium. Attenzione: non è supportato dal Php 3. Seguire le seguenti istruzioni per installare il PHP 4 con Caudium.

Esempio 3-9. Istruzioni di installazione per Caudium

1.  Essere certi di avere installato Caudium prima di installare
    il PHP 4. Il Php per potere funzionare ha bisogno di Pike
    versione  7.0.268 o successive. Per praticità di illustrazione
    in questo esempio assumeremo che Caudium sia installato in
    /opt/caudium/server/.
2.  Posizionarsi nella directory php-x.y.z (dove x.y.z è il numero di versione).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Riavviare Caudium se è attivo.
7.  Entrare nell'interfaccia grafica di configurazione e andare 
    nella sezione virtual server da dove si inserirà il PHP.
8.  Cliccare su Add Module localizzare e aggiungere il modulo PHP 4 Script Suppor.
9.  Se la documentazione informa che 'PHP 4 interpreter isn't
    available', verificare di avere riavviato il server. Se lo si è
    fatto, cercare nel file /opt/caudium/logs/debug/default.1
    la presenza di errori collegati a <filename>PHP4.so</filename>.
    Verificare anche la presenza del file 
    <filename>caudium/server/lib/[pike-version]/PHP4.so</filename>.
10. Configurare il modulo PHP Script Support se necessario..

Si può compilare il modulo per Caudium con il supporto dei vari moduli disponibili per PHP 4, Vedere la lista completa delle opzioni di configurazione options per maggiori informazioni.

Nota: Quando si compila il PHP con il supporto a MySQL occorre essere certi di utilizzare il normale client di MySQL. Altrimenti si possono verificare del conflitti se Pike supporta MySQL. Per fare ciò occorre specificare la directory di installazione di MySQL nell'opzione --with-mysql.


Servers-fhttpd

Per compilare il PHP come modulo fhttpd, rispondere "yes" alla domanda "Build as an fhttpd module?" (l'opzione di configurazione --with-fhttpd=DIR) e specificare la directory base dei sorgenti di fhttpd. Per default la directory è /usr/local/src/fhttpd. Se si usa fhttpd, compilare il PHP come modulo da la possibilità di avere prestazioni migliori e la capacità dell'esecuzione remota.

Nota: Il supporto per fhttpd non è più disponibile a partire da PHP 4.3.0.


Server IIS/PWS

Questa sezione contiene note e suggerimenti specifici per IIS (Microsoft Internet Information Server). Installare il PHP su PWS/IIS 3, PWS 4 o recenti e IIS 4 o recenti.

Importante per utenti CGI: Leggere la faq su cgi.force_redirect per dettagli importanti. Questa direttiva deve essere impostata a 0.


Windows e PWS/IIS 3

Il metodo raccomandato per l'installazione con questi server è di utilizzare il file REG incluso con la distribuzione (pws-php4cgi.reg). Può essere necessario modificare questo file per adeguarlo alle estensioni usate e alle directory in cui è installato il PHP-. Oppure si può seguire i seguenti passi per farlo manualmente.

Avvertimento

Queste istruzioni richiedono di lavorare direttamente sul registry di Windows. Un errore potrebbe lasciare il sistema in uno stato instabile. Si raccomanda di fare una copia di backup del registry prima di cominciare. Il gruppo di sviluppo di PHP non è responsabile se si danneggia il registry.

  • Eseguire Regedit.

  • Posizionarsi in: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.

  • Nel menu modifica selezionare: Nuovo->Stringa (New->String Value).

  • Digitare l'estensione che si desidera utilizzare per gli script PHP, Ad esempio .php.

  • Fare un doppio click su 'nuovo valore stringa' e inserire il percorso a php.exe nel campo valore. es.: c:\php\php.exe.

  • Ripetere questi passi per ciascuna estensione si desideri associare agli script PHP.

I seguenti passi non influiscono sull'installazione del server web e si applicano solo se si desidera che gli script php vengano eseguiti quando sono lanciati da linea di comando (es. run c:\myscripts\test.php) o da un doppio click sugli stessi da esplora risorse. Si può anche saltare questi passi e optare per caricare i file PHP in un editor quando si fa un doppio click su di essi.

  • Posizionarsi in: HKEY_CLASSES_ROOT

  • Nel menu modifica selezionare: nuovo->chiave (New->Key).

  • Dare come nome della chiave l'estensione che si desidera configurare es: .php.

  • Evidenziare la nuova chiave e nel pannello di destra, fare un doppio click su "default value" e inserire phpfile.

  • Ripetere il passo precedente per ogni estensione che si desidera inserire.

  • Ora crea un'altra chiave Nuovo->Chiave (New->Key) sotto HKEY_CLASSES_ROOT e chiamarla phpfile.

  • Evidenziare la nuova chiave phpfile e nel pannello di destra fare un doppio click su "default value" ed inserire PHP Script.

  • Click destro sulla chiave phpfile e selezionare Nuovo->Chiave(New->Key), chiamarla Shell.

  • Click destro sulla chiave Shell e selezionare Nuovo->Chiave(New->Key), chiamarla open.

  • Click destro sulla chiave open e selezionare Nuovo->Chiave(New->Key), chiamarla command.

  • Evidenziare la nuova chiave command e nel pannello di destra fare un doppio click su "default value" ed inserire il percorso a php.exe. es: c:\php\php.exe -q %1. (non dimenticarsi del %1).

  • Uscire da Regedit.

  • Se si usa PWS con Windows, riavviare il PC.

A questo punto gli utenti di PWS ed IIS 3 hanno il sistema operante. Gli utenti di IIS3 possono utilizzare un tool di Steven Genusa per configurare la mappatura degli script.


Windows con PWS 4 e successivi

Quando si installa il PHP su sistemi Windows con PWS 4 o versioni successive, si ha due opzioni. Una consiste nell'impostare il PHP come CGI, l'altra consiste nell'usare il modulo ISAPI.

Se si sceglie la soluzione CGI, eseguire i seguenti passi:

  • Modificare il file pws-php4cgi.reg (vedere nella directory SAPI) per inserire il percorso di php.exe. I backslash devono essere preceduti dal carattere di escape '\' ad esempio: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\php.exe" Ora inserire questo file di registro nel sistema; dovrebbe bastare un doppio click sul file.

  • Nel PWS Manager, click destro nella direttory a cui si vuole aggiungere il supporto PHP e selezionare Proprietà (Properties). Spuntare il checkbox 'Execute' e confermare.

Se si opta per il modulo ISAPI, questi sono i passi:

  • Modificare il file pws-php4cgi.reg (vedere nella directory SAPI) per inserire il percorso di php4isapi.dll. I backslash devono essere preceduti dal carattere di escape '\' ad esempio: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\sapi\\php4isapi.dll" Ora inserire questo file di registro nel sistema; dovrebbe bastare un doppio click sul file.

  • Nel PWS Manager, click destro nella direttory a cui si vuole aggiungere il supporto PHP e selezionare Proprietà (Properties). Spuntare il checkbox 'Execute' e confermare.


Windows NT/2000/XP con IIS 4 o successivi

Seguire queste istruzioni per installare il PHP su sistemi NT/2000/XP con IIS 4 o successivi. Si hanno a disposizione due opzioni. Una consiste nell'impostare il PHP come CGI, l'altra consiste nell'usare il modulo ISAPI.

In emtranbi i casi occorre avviare la Microsoft Management Console (può essere presente come 'Internet Services Manager', sia nel Windows NT 4.0 Option Pack o nel Pannello di controllo (Control Panel)=>Administrative Tools sotto Windows 2000/XP). Quindi click destro sul nodo Web server (questo molto probabilmente comparirà come 'Default Web Server'), e selezionare 'Proprietà' ('Properties').

Se si desidera installare il PHP come CGI seguire i seguenti passi:

  • Sotto 'Home Directory', 'Virtual Directory', o 'Directory', cliccare sul bottone 'Configuration', ed entrare in App Mappings.

  • Premere Add, e nel box Executable digitare. c:\php\php.exe (assumendo che il PHP si trovi in c:\php\).

  • Nel box Extension, digitare l'estensione dei file che si vuole associare come script PHP. Lasciare bianco 'Method exclusions' e selezionare il checkbox Script engine. Si potrebbe anche selezionare il box 'check that file exists', con una ridotta penalizzazione nella velocità, IIS (o PWS) controlleranno che lo script esista ed eseguiranno l'autentificazione prima di lanciare il PHP. Questo significa avere più errori di tipo 404 piuttosto che avere degli errori CGI dovuti al fatto che il PHP non ha dato in output alcun dato.

    Occorre eseguire il passo precedente per ogni estensione che si desideri associare al PHP. .php and .phtml sono le più comuni, anche .php3 può essere richiesta per compatibilità verso il passato.

  • Impostare le opzioni di sicurezza. (Può essere fatto dal Internet Service Manager), e se il server utilizza come file system NTFS, aggiungere i diritti di esecuzione per I_USR alla directory che contiene il php.exe.

Per impostare il modulo ISAPI occorre:

  • Se non si desidera eseguire l'autenticazione HTTP con il PHP, si può (si dovrebbe) saltare questo passo. Nei filtri ISAPI, aggiungere un nuovo filtro. Indicare PHP come nome del filtro, e indicare il percorso di php4isapi.dll.

  • Nella 'Home Directory', cliccare sul bottone 'Configuration'. Aggiungere una nuova riga nel 'Application Mappings'. Indicare il percorso di php4isapi.dll come Executable, dare .php come estensione, lasciare bianco Method exclusions, e selezionare il checkbox Script engine.

  • Fermare completamente IIS (NET STOP iisadmin)

  • Attivare IIS (NET START w3svc)


Servers-Netscape, iPlanet and SunONE

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

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


Installing PHP with NES/iPlanet/SunONE Webserver on Sun Solaris

To build PHP with NES/iPlanet/SunONE 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 NES/iPlanet/SunONE. Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for SunONE to find all the shared libs. This can best done in the start script for your SunONE webserver. Windows users can probably skip this step. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.

  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 OS, for Unix it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
    Init fn="load-modules" funcs="php4_init,php4_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 [SunONE 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").


Installing PHP with NES/iPlanet/SunONE on Windows

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

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

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

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

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

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

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

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

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

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

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

  • 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 [SunONE 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 iPlanet/SunONE/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the webserver itsself) 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 Unix 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,..., you should turn on register_globals in php.ini and change the variable order to (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 SunONE 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!!!


Servers-OmniHTTPd Server

This section contains notes and hints specific to OmniHTTPd.


OmniHTTPd 2.0b1 and up for Windows

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

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

  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:\path-to-php-dir\php.exe, 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.


Servers-Sambar

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


Sambar Windows

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

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

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

    Esempio 3-10. ISAPI configuration of Sambar

    *.php = c:\php\php4isapi.dll
    (This line assumes that PHP was installed in c:\php.)

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


Servers-Xitami

This section contains notes and hints specific to Xitami.


Xitami for Windows

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

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

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

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

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

  • Press the 'Save' icon.

  • Restart the server to reflect changes.


Servers-Other web servers

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


Problems?

Read the FAQ

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


Other problems

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

The default location of php.ini is a compile time option (see the FAQ entry), but can be changed for the CGI and CLI version with the -c command line switch, see the chapter about using PHP from the command line. You can also use the environment variable PHPRC for an additional path to search for a php.ini file.

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 themselfs. The list of the core directives is available in the appendix. Probably not all the PHP directives are documented in the manual though. For a completel 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 4-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"


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 table found within the ini_set() documentation.

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


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

Modi per uscire dalla modalità HTML

Quando il PHP inizia a esaminare un file, visualizzerà il contenuto del file sino a quando non incontra uno dei tag speciali indicanti l'inizio del codice da interpretare come istruzioni PHP. A questo punto il parser eseguirà tutto il codice trovato sino a quando non incontrerà i tag di chiusura, che indicano al parser di tornare alla modalità di visualizzazione. Questo meccanismo permette di inserire codice PHP all'interno di codice HTML: tutto ciò che si trova all'esterno dei tag PHP sarà lasciato inalterato, mentre tutto ciò che si trova all'interno sarà eseguito come codice PHP.

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 possono essere attivati o disattivati tramite il file di configurazione php.ini. Sebbene i tag brevi o quelli in stile ASP possano essere pratici, il supporto di questi non è garantito in tutte le versioni. Quindi, se si intende inserire codice PHP all'interno di testi XMl o XHTML, occorre utilizzare <?php. . .?> per essere conformi allo standard XML.  

I tag supportati dal PHP sono:     

Esempio 5-1. Metodi per uscire dalla modalità HTML

1.  <?php echo("se si vogliono produrre documenti XHTML o XML, si utilizzi questo modo\n"); ?>

2.  <? echo ("questo è il più semplice, ovvero come istruzione SGML\n"); ?>
    <?= espressione ?>  Questa è un'abbreviazione per "<? echo espressione ?>"
 
3.  <script language="php">
        echo ("alcuni editor (tipo FrontPage) non 
               amano le istruzioni di elaborazione");
    </script>

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

Il primo, <?php. . .?>, è il metodo preferenziale, dato che permette l'utilizzo del PHP all'interno di codice conforme a specifiche XML come XHTML.

Il secondo metodo è disponibile solo se sono stati abilitati i tags abbreviati. Ciò può essere impostato sia utilizzando la funzione short_tags() (solo PHP 3), sia abilitando nel file di configurazione del PHP l'opzione short_open_tag, oppure compilando il PHP utilizzando l'opzione --enable-short-tags nel comando configure. Sebbene siano abilitati nel php.ini-dist riilasciato, l'uso dei tag brevi è vivamente sconsigliato.

Il quarto modo è disponibile solo se sono stati attivati nel file di configurazione i tag in stile ASP tramite l'opzione asp_tags.

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.    

Il tag di chiusura di un blocco include il carattere di 'a capo' immediatamente seguente, se presente. Inoltre, il tag di chiusura viene considerato automaticamente come punto e virgola; pertanto non occorre inserire il punto e virgola alla fine dell'ultima riga del blocco php.      

Il PHP permette strutture tipo le seguenti:

Esempio 5-2. Modi avanzati per uscire dalla modalità HTML

<?php
if ($expression) {
    ?>
    <strong>Questa è vera.</strong>
    <?php
} else {
    ?>
    <strong>Questa è falsa.</strong>
    <?php
}
?>
Questo esempio agisce come atteso, poichè il PHP rileva il tag di chiusura ?>, e da questo punto, inizia a dare in output tutto ciò che trova fino a quando non rileva un'altro tag di apertura. Certamente l'esempio dato è macchinoso, ma per l'output di grossi blocchi di testo, l'uscire dalla modalità di parsing PHP, è generalmente più efficiente piuttosto che inviare il testo tramite ripetute funzioni echo() o print().


Separazione delle istruzioni

Le istruzioni sono separate come nel C o in Perl - ogni istruzione termina con un punto e virgola.

Il tag di chiusura (?>) implica anche la fine di un'istruzione, perciò le seguenti sono equivalenti:

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


Commenti

Il PHP supporta i commenti dei linguaggi 'C', 'C++' e della shell 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.

<h1>Questo &egrave; un <?# echo "semplice";?> esempio.</h1>
<p>L'intestazione qui sopra dir&agrave; 'Questo &egrave; un esempio'.

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

  Lo stile di commento su linea singola commenta il testo fino alla fine della riga oppure alla fine del blocco di codice PHP, dipende da cosa si incontra prima. Questo significa che il codice HTML posizionato dopo // ?> SARA' visualizzato: ?> indica di uscire dal modo PHP e di ritornare in modalità HTML, e, quindi, // non hanno più effetto.     


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


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 goes also for hexadecimal specified integers:
var_dump( 0x80000000 );
// output: float(2147483648)

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


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

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 here doc as with strings.

Esempio 6-2. 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 6-3. 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().

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

The above example would produce the following output:
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: The output from the above is:
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 6-4. 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 6-5. Collection

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

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

?>

This will output:

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

Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:

Esempio 6-6. Collection

<?php
foreach ($colors as $key => $color) {
    // won't work:
    //$color = strtoupper($color);
    
    // works:
    $colors[$key] = strtoupper($color);
}
print_r($colors);
?>

This will output:

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

This example creates a one-based array.

Esempio 6-7. One-based index

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

This will output:

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

Esempio 6-8. 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 6-9. 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 6-10. 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. 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


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 6-11. Callback function examples

<?php 

// simple callback example
function my_callback_function() {
    echo 'hello world!';
}
call_user_func('my_callback_function'); 

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

// static class method call without instantiating an object
call_user_func(array('MyClass', 'myCallbackMethod')); 

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

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

PHP 4 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. Dalla versione 5.0.0 di PHP gli array predefiniti di PHP, variabili predefinite possono essere disabilitati usando la direttiva register_long_arrays.

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 modifiying 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 HTTP GET. 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 7-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 7-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 7-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
    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 7-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 7-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 7-6. Static variables with recursive functions

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

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

Nota: Static variables maybe 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 7-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. This means you cannot do things like ${$_GET}. If you are looking for a way to handle availability of superglobals and the old HTTP_*_VARS, you might want to try referencing them.


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 7-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 7-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 7-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. In 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 7-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 8. 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]*

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 8-1. Definizione di costanti

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


Costanti predefinite

Il PHP mette a disposizione ad ogni script diverse costanti predefinite. Alcune di queste, tuttavia, sono create dai vari moduli, e, pertanto, saranno disponibili solo quando questi moduli sono caricati, sia dinamicamente sia staticamente.

Esistono quattro 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 8-1. Le costanti "magiche" del PHP

NomeDescrizione
__LINE__ Il numero di linea corrente.
__FILE__ Il nome e percorso assoluto del file.
__FUNCTION__ Nome della funzione. (Aggiunta nel PHP 4.3.0.)
__CLASS__ Nome della classe. (Aggiunta nel PHP 4.3.0.)
__METHOD__ Nome del metodo della classe (Aggiunta nel PHP 5.0.0.)

La lista di tutte le costanti predefinite è presente nella sezione reserved predefined constants.


Capitolo 9. 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, 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 10. Operatori


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.

La seguente tabella fornisce una lista della precedenza degli operatori con gli operatori a più bassa precedenza listati prima.

Tabella 10-1. Precedenza degli operatori

AssociativitàOperatori
sinistra,
sinistraor
sinistraxor
sinistraand
destraprint
sinistra = += -= *= /= .= %= &= |= ^= ~= <<= >>=
sinistra? :
sinistra||
sinistra&&
sinistra|
sinistra^
sinistra&
non associativi== != === !==
non associativi< <= > >=
sinistra<< >>
sinistra+ - .
sinistra* / %
destra! ~ ++ -- (int) (float) (string) (array) (object) @
destra[
non associativinew


Operatori aritmetici

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

Tabella 10-2. Operatori aritmetici

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


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:

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

$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. PHP 4 supporta 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 di questa 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 10-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")

Operatori di confronto

Gli operatori di confronto, come suggerisce il loro nome, permettono di confrontare due valori.

Tabella 10-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. (Solo 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. (Solo 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.

Un altro operatore condizionale è l'operatore "?:" (o ternario), che opera come in C e molti altri linguaggi.

(espressione1) ? (espressione2) : (espressione3);

Questa espressione vale espressione2 se espressione1 è TRUE, e espressione3 se espressione1 è FALSE.


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 di thumb è: 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().

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

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

Nota: L'operatore backtick è disabilitato quando è abilitata safe mode oppure quando è disabilitata shell_exec().

Vedere anche escapeshellcmd(), exec(), passthru(), popen(), shell_exec() e system().


Operatori di incremento/decremento

PHP supporta lo stile C degli operatori di pre- e post-incremento e decremento.

Tabella 10-5. 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&gt;Post-incremento</h3&gt;";
$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";
?>


Operatori logici

Tabella 10-6. 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 a destra e a sinistra. Il secondo è l'operatore di assegnazione concatenata ('.='), che aggiunge alla fine dell'argomento sul lato destro l'argomento sul lato sinistro. Per favore consultare Operatori di assegnazione per maggiori informazioni.

$a = "Ciao ";
$b = $a . "Mondo!"; // ora $b contiene "Ciao Mondo!"

$a = "Ciao ";
$a .= "Mondo!";     // ora $a contiene "Ciao Mondo!"


Capitolo 11. 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:

if (espressione)
    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:

if ($a > $b)
    print "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:

if ($a > $b) {
    print "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:

if ($a > $b) {
    print "a è maggiore di b";
} else {
    print "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:

if ($a > $b) {
    print "a è maggiore di b";
} elseif ($a == $b) {
    print "a è uguale a b";
} else {
    print "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:

if ($a == 5):
    print "a è uguale a 5";
    print "...";
elseif ($a == 6):
    print "a è uguale a 6";
    print "!!!";
else:
    print "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:

/* esempio 1 */

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

/* esempio 2 */

$i = 1;
while ($i <= 10):
    print $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:

$i = 0;
do {
   print $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à:

do {
    if ($i < 5) {
        print "i non è abbastanza grande";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
    print "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:

/* esempio 1 */

for ($i = 1; $i <= 10; $i++) {
    print $i;
}

/* esempio 2 */

for ($i = 1;;$i++) {
    if ($i > 10) {
        break;
    }
    print $i;
}

/* esempio 3 */

$i = 1;
for (;;) {
    if ($i > 10) {
        break;
    }
    print $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;

Alcuni linguaggi permettono l'uso della struttura di controllo foreach per attraversare un array o una tabella hash. PHP 3 non premette l'uso di tale ciclo mentre PHP 4 si (vedere foreach). In PHP 3 è possibile combinare while con la funzione list() e each() per ottenere la stessa funzionalià. Si veda la documentazione di queste funzioni per ulteriori esempi.


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. Esistono due possibili notazioni sintattiche; la seconda è un'utile estensione della prima:

foreach(array_expression as $value) istruzione
foreach(array_expression as $key => $value) istruzione

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.

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: È importante notare che foreach opera su una copia dell'array, non sull'array stesso, 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.

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:

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:

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:

/* esempio 1 foreach: solo il valore */

$a = array (1, 2, 3, 17);

foreach ($a as $v) {
   print "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) {
    print "\$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) {
    print "\$a[$k] => $v.\n";
}

/* esempio 4 foreach: array multidimensionali */

$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach($a as $v1) {
    foreach ($v1 as $v2) {
        print "$v2\n";
    }
}

/* esempio 5 foreach: array dinamici */

foreach(array(1, 2, 3, 4, 5) as $v) {
    print "$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.

$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 all'inizio del ciclo successivo.

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.

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


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.

Gli esempi seguenti mostrano due maniere differenti di scrivere la stessa cosa, uno utilizzando una serie di if, l'altro utilizzando switch :

if ($i == 0) {
    print "i è uguale a 0";
}
if ($i == 1) {
    print "i è uguale a 1";
}
if ($i == 2) {
    print "i è uguale a 2";
}

switch ($i) {
    case 0:
        print "i è uguale a 0";
        break;
    case 1:
        print "i è uguale a 1";
        break;
    case 2:
        print "i è uguale a 2";
        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:

switch ($i) {
    case 0:
        print "i è uguale a 0";
    case 1:
        print "i è uguale a 1";
    case 2:
        print "i è uguale a 2";
}

In questo caso se $i è uguale a 0, PHP eseguirà tutte le istruzioni contenute nei blocchi case. Se $i è uguale a 1, PHP eseguirà le istruzioni degli ultimi due blocchi case e solamente se $i è uguale a 2 otterremo il risultato voluto e si visualizzerà solo '$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.

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:

switch ($i) {
    case 0:
        print "i è uguale a 0";
        break;
    case 1:
        print "i è uguale a 1";
        break;
    case 2:
        print "i è uguale a 2";
        break;
    default:
        print "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.

switch ($i):
    case 0:
        print "i è uguale a 0";
        break;
    case 1:
        print "i è uguale a 1";
        break;
    case 2:
        print "i è uguale a 2";
        break;
    default:
        print "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.


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 11-1. 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 nel file di configurazione, 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 non sono richieste --infatti, è più comune evitarle che usarle, nonostante ciò non c'è motivo di preferire un modo o l'altro.


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

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.

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.

Esempio 11-3. 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 11-4. 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) 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.

Esempio 11-5. 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 11-6. 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.

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 11-7. 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. Pochi altri modi di "includere" file in variabili sono con fopen(), file() o usando include() insieme con Output Control Functions.

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.

Nota: require_once() è stato aggiunto in PHP 4.0.1pl2

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.

Nota: include_once() è stato aggiunto in PHP 4.0.1pl2

Vedere anche include(), require(), require_once(), get_required_files(), get_included_files(), readfile() e virtual().


Capitolo 12. Funzioni

Funzioni definite dall'utente

Una funzione può essere definita usando la seguente sintassi:

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.

PHP non supporta l'overloading di funzioni, non è possibile indefinire o ridefinire funzioni precedentemente dichiarate.

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.


Argomenti delle funzioni

L'informazione può essere passata alle funzioni tramite la lista degli argomenti, che sono liste di variabili e/o costanti 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.

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:

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:

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.

Il valore predefinito deve essere un'espressione costante, non (per esempio) una variabile o un membro di classe.

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:

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:

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.


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.

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.

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:

function &restituisce_riferimento()
{
    return $un_riferimento;
}

$nuovo_riferimento =& restituisce_riferimento();

Per maggiori informazioni sui riferimenti, consultare References Explained.


old_function

L'istruzione old_function permette di dichiarare una funzione usando una sintassi identica a PHP/FI2 (eccetto il dover sostituire 'function' con 'old_function'.

Questa è una caratteristica deprecata, e dovrebbe essere usata solo da convertitori PHP/FI2->PHP 3.

Avvertimento

Le funzioni dichiarate come old_function non possono essere chiamate da codice interno di PHP. Tra le altre cose, questo significa che non possono essere usate in funzioni come usort(), array_walk(), e register_shutdown_function(). Si può aggirare questa limitazione scrivendo una funzione contenitore (nel normale stile di PHP 3) per chiamare la old_function.


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(), unset(), isset(), empty() e include(). Ad ogni modo, il costrutto print() è un'eccezione e funzionerà. Questa è una delle maggiori differenze tra le funzioni PHP e i costrutti di linguaggio.

Esempio 12-1. Esempio di funzioni variabili

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

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

$func = 'foo';
$func();
$func = 'bar';
$func('test');
?>

Vedere anche variabili variabili e function_exists().


Capitolo 13. Classi e Oggetti

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;
        } 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. Il seguente codice non funziona:

<?php
class test {
?>
<?php
    function test() {
        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
/* questo non funziona in PHP 4. */
class Cart
{
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    var $items = array("VCR", "TV");
}

/* Questo è corretto. */
class Cart
{
    var $todays_date;
    var $name;
    var $owner;
    var $items;

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

Attenzione

In PHP 3 i costruttori si comportano diversamente rispetto a PHP 4. La semantica di PHP 4 è decisamente da preferire.

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 3, una funzione si transforma in in un costruttore quando ha lo stesso nome di una classe. In PHP 4, una funzione diventa un costruttore, quando ha lo stesso nome di una classe ed è definita all'interno della classe stessa - la differenza è sottile, ma cruciale (si veda sotto).

<?php
// Funziona in PHP 3 e PHP 4.
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
// Funziona in PHP 3 and PHP 4.
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.

Attenzione

In PHP 3, le classi e i costruttori derivati presentano un certo numero di limitazioni. I seguenti esempi dovrebbero essere letti con attenzione per capire queste limitazioni.

<?php
class A
{
    function A()
    {
      echo "Sono il costtruttore di A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "Sono una normale funzione.<br>\n";
    }
}

// nessun costruttore è chiamato in PHP 3.
$b = new B;
?>

In PHP 3, nessun costruttore è stato chiamanto nel suddetto esempio. La regola in PHP 3 è: 'un costruttore è una funzione che ha lo stesso nome di una classe'. Il nome della classe è B e non c'è nessuna funzione B() nella classe B.

Questa regola è stata cambiata in PHP 4, la nuova regola dice: 'Se una classe non ha un costruttore proprio, verrà chiamato il costruttore della classe base, se esiste'. Il suddetto esempio avrebbe stampato 'Sono il costruttore di A.' in PHP 4.

<?php
class A
{
    function A()
    {
        echo "Sono il costruttore 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
{
    function C()
    {
        echo "Sono una normale funzione.<br>\n";
    }
}

// This will call B() as a constructor.
$b = new B;
?>

In PHP 3, la funzione B() della classe A si transformerà improvvisamente in un costruttore per la classe B, anche se questo non era previsto. La regola in PHP 3 è: 'un costruttore è una funzione che ha lo stesso nome di una classe'. PHP 3 non si preoccupa se la funzione è stata definita nella classe B o se è stata ereditata.

La regola è stata corretta in PHP 4 ed è diventata: 'un costruttore è una funzione con lo stesso nome della classe in cui è definita'. Così in PHP 4, la classe B non avendo una funzione costruttore avrebbe richiamato il costruttore della sua classe base, e sarebbe stato stampato 'io sono il costruttore di A.'.

Attenzione

Nè PHP 3 nè PHP 4 chiamano costruttori di una classe base automaticamente da un costruttore di una classe derivata. È responsabilità del programmatore propagare la chiamata ai costruttori dove è necessario.

Nota: Non ci sono distruttori in PHP 3 o in PHP 4. Potete usare register_shutdown_function() per simulare la maggior parte degli effetti dei distruttori.

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.


::

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");
  fputs($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();

/*
output:
class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11
*/
?>


Confronto di oggetti in PHP 4

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 13-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);
?>
Si ha:
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 13-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);
?>
L'output previsto è:
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


Confronto di oggetti in PHP 5

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 PHP 5, il confronto tra oggetti è più complicato che in PHP 4, ed è in armonia con quello che ci si può aspettare da un linguaggio orientato agli oggetti (non che PHP 5 lo sia veramente).

Quando si usa l'operatore di confronto (==), le variabili oggetto sono confrontate in modo semplice, cioè: due istanze di oggetto sono uguali se hanno gli stessi attributi e valori, e sono istanze della stessa classe, definita nello stesso spazio dei nomi.

Diversamente, quando usiamo l'operatore di identità (===), le variabili oggetto sono identiche se e solo se si riferiscono alla stessa istanza della stessa classe (in un particolare spazio dei nomi).

Un esempio chiarirà questa regola.

Esempio 13-3. Esempio di confronto di oggetti 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 {
    var $flag;

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

namespace Other {

    class Flag {
        var $flag;

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

}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new Other::Flag();

echo "Due istanze della stessa classe\n";
compareObjects($o, $p);

echo "\nDue riferimenti alla stessa istanza\n";
compareObjects($o, $q);

echo "\nIstanze di classi di diversi spazi dei nomi e simili nomi di classe\n";
compareObjects($o, $r);
?>
L'esempio stampa:
Due istanze della stessa classe
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Due riferimenti alla stessa istanza
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Istanze di classi di diversi spazi dei nomi e simili nomi di classe
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE


Capitolo 14. Classes and Objects (PHP 5)

Introduction

Intro to oop5 for php


Constructors and Destructors

Constructor

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. In order to run a parent constructor, a call to parent::__construct() is required.

Esempio 14-1. 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

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as Java: When the last reference to an object is destroyed the object's destructor, which is a class method named __destruct() that receives no parameters, is called before the object is freed from memory.

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


Visibility

The visibility of a member or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be allow access to any caller. Protected limits access access to only classes inherited. Protected limits visiblity only to the class that defines the item.


Members Visibility

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

Esempio 14-3. Member declaration

<?php

class MyClass {
   public    $public     = "MyClass::public!\n";
   protected $protected  = "MyClass::Protected!\n";
   protected $protected2 = "MyClass::Protected2!\n";
   private   $private    = "MyClass::private!\n";

   function printHello() {
      print "MyClass::printHello() " . $this->private;
      print "MyClass::printHello() " . $this->protected;
      print "MyClass::printHello() " . $this->protected2;
   }
}

class MyClass2 extends MyClass {
   protected $protected = "MyClass2::protected!\n";

   function printHello() {

      MyClass::printHello();    

      print "MyClass2::printHello() " . $this->public; 
      print "MyClass2::printHello() " . $this->protected; 
      print "MyClass2::printHello() " . $this->protected2;

      /* Will result in a Fatal Error: */
      //print "MyClass2::printHello() " . $this->private; /* Fatal Error */

   }
}

$obj = new MyClass();

print "Main:: " . $obj->public;
//print $obj->private; /* Fatal Error */
//print $obj->protected;  /* Fatal Error */
//print $obj->protected2;  /* Fatal Error */

$obj->printHello(); /* Should print */

$obj2 = new MyClass2();
print "Main:: " . $obj2->private; /* Undefined */ 

//print $obj2->protected;   /* Fatal Error */ 
//print $obj2->protected2;  /* Fatal Error */ 

$obj2->printHello();
?>

Nota: The use PHP 4 use of declaring a variable with the keyword 'var' is no longer valid for PHP 5 objects. For compatiblity a variable declared in php will be assumed with public visiblity, and a E_STRICT warning will be issued.


::

.


Object Abstraction

PHP 5 introduces abstract classes and methods. An abstract method only declares the method's signature and does not provide an implementation. A class that contains abstract methods needs to be declared abstract.

Esempio 14-4.

<?php
abstract class AbstractClass {
   abstract public function test();
}

class ImplementedClass extends AbstractClass {
   public function test() {
       echo "ImplementedClass::test() called.\n";
   }
}

$o = new ImplementedClass;
$o->test();
?>

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


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 the developer asks to create a new copy of an object, PHP 5 will check if a __clone() method has been defined or not. If not, it will call a default __clone() which will copy all of the object's properties. If a __clone() method is defined, then it will be responsible to set the necessary properties in the created object. For convenience, the engine will supply a function that imports all of the properties from the source object, so that they can start with a by-value replica of the source object, and only override properties that need to be changed.

Esempio 14-5. Cloning an object

<?php
class MyCloneable {
   static $id = 0;

   function MyCloneable() {
       $this->id = self::$id++;
   }

   function __clone() {
       $this->address = "New York";
       $this->id = self::$id++;
   }
}

$obj = new MyCloneable();

$obj->name = "Hello";
$obj->address = "Tel-Aviv";

print $obj->id . "\n";

$obj_cloned = clone $obj;

print $obj_cloned->id . "\n";
print $obj_cloned->name . "\n";
print $obj_cloned->address . "\n";
?>

Comparing objects

In PHP 5, object comparison is a 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 14-6. 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 {
    var $flag;

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

class OtherFlag {
    var $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);
?>
This example will output:
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 14-7. Basic usage of the reflection API

<?php
  Reflection::export(new ReflectionClass('Exception'));
?>
We will see:
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> method __construct ] {
    }

    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 ] {
    }
  }
}


ReflectionFunction

The ReflectionFunction class lets you reverse-engineer functions.

<?php
  class ReflectionFunction implements Reflector {
      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 bool returnsReference()
      public ReflectionParameter[] getParameters()
  }
?>

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 14-8. 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 {
      public object __construct(string name)
      public string __toString()
      public static string export()
      public string getName()
      public ReflectionClass getClass()
      public bool allowsNull()
      public bool isPassedByReference()
  }
?>

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 14-9. Using the ReflectionParameter class

<?php
    function foo($a, $b, $c) { }
    function bar(Exception $a, &$b, $c) { }
    function baz($a = 1, $b = NULL, ReflectionFunction $c) { }
    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".
            "}\n",
            $i, 
            $param->getName(),
            var_export($param->getClass(), 1),
            var_export($param->allowsNull(), 1),
            var_export($param->isPassedByReference(), 1)
        );
    }
?>

ReflectionClass

The ReflectionClass class lets you reverse-engineer classes.

<?php
  class ReflectionClass implements Reflector {
      public __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 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 bool isInstantiable()
      public bool isInterface()
      public bool isFinal()
      public bool isAbstract()
      public int getModifiers()
      public bool isInstance(stdclass object)
      public stdclass newInstance(mixed* args)
      public ReflectionClass[] getInterfaces()
      public ReflectionClass getParentClass()
      public bool isSubclassOf(ReflectionClass class)
  }
?>

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 14-10. 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 static string export()
      public mixed invoke(stdclass object, mixed* args)
      public bool isFinal()
      public bool isAbstract()
      public bool isPublic()
      public bool isPrivate()
      public bool isProtected()
      public bool isStatic()
      public bool isConstructor()
      public int getModifiers()
      public ReflectionClass getDeclaringClass()

      /* Inherited from ReflectionFunction */
      public string __toString()
      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()
  }
?>

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 14-11. Using the ReflectionMethod class

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

      /**
       * Increment counter
       *
       * @final
       * @static
       * @access  public
       * @return  int
       */
      final public static function increment()
      {
          self::$c++;
          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 {
      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()
  }
?>

To introspect a method, 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 14-12. 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 {
      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()
  }
?>

To introspect a method, 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 14-13. 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",
      $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)
  );
?>

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


Capitolo 15. 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:

$a =& $b

$a e $b puntano alla stessa variabile.

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.

Questa sintassi si può usare con le funzioni, nella restituzione per riferimento, e con l'operatore new (da PHP 4.0.4 in poi):

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

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:

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:

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


Passaggio per riferimento

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

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.

Le seguenti cose possono essere passate per riferimento:

  • Variabili, es. foo($a)

  • Operatore New, es. foo(new foobar())

  • Riferimento restituito da una funazione, es.

    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:

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

foo(bar());
foo($a = 5) // Expressione: non una variabile
foo(5) // Constante: non una variabile

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. Per restituire per riferimento, si usa questa sintassi:

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.


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:

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

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

III. Security

Sommario
16. Security

Capitolo 16. Security


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.


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.


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.


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 abilitites in some other way.

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

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


Filesystem Security

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

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

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

Esempio 16-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 16-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 16-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 16-4. More secure file name checking

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

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

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

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


Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret 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 estabilish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of 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 16-5. Using hashed password field

<?php

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

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

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

?>

SQL Injection

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

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

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

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

<?php

$offset = argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL 
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($query);

?>
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL

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

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

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

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

A feasible way to gain passwords is to circumvent your search result pages. 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 16-7. 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 16-8. 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 16-9. 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 16-10. 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 input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily cracked.

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


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 16-11. 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 occured in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:

Esempio 16-12. 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, by using E_NONE, you insulate your code from probing.

Esempio 16-13. Finding dangerous variables with E_ALL

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


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 (poison) your scripts will 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 16-14. 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 16-15. 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 16-16. 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 unitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

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


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 16-17. Dangerous Variable Usage

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

// Write logging of their access... or maybe an /etc/passwd entry?
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).


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 16-18. Hiding PHP as another language

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

Esempio 16-19. Using unknown types for PHP extensions

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

Esempio 16-20. Using HTML types for PHP extensions

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


Keeping Current

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

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


Capitolo 17. 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 PHP_AUTH_TYPE impostate con, rispettivamente: nome, password e tipo di autenticazione. Queste variabili predefinite possono essere trovate negli array $_SERVER e $HTTP_SERVER_VARS. Solamente il tipo di autenticazione "Basic" è al momento supportato. Fare riferimento alla funzione header() per ulteriori informazioni.

Nota sulla versione di PHP: Le variabili autoglobali, come $_SERVER, esistono in PHP dalla versione 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 17-1. Esempio di Autenticazione HTTP

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

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.

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. In questo caso, la variabile REMOTE_USER può essere usata per identificare un utente autenticato esternamente. Così, $_SERVER['REMOTE_USER'].

Nota sulla Configurazione: PHP usa la presenza di una direttiva AuthType per determinare se viene utilizzata l'autenticazione esterna. Evitare questa direttiva nel contesto dove si intende usare l'autenticazione con PHP (altrimenti ogni tentativo di autenticazione fallirà).

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

Nota: Se è abilitato safe mode viene aggiunto lo uid dello script al realm dell'header WWW-Authenticate.


Capitolo 18. 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 la funzione setcookie(). 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 veda la funzione setcookie().


Capitolo 19. 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 19-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 interrested 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 19-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 20. Caricare file

Metodo POST per caricamento di file

PHP è in grado di ricevere file caricati da qualsiasi browser compatibile con le specifiche RFC-1867 (che comprende Netscape Navigator 3 o successivo, Microsoft Internet Explorer 3 con una modifica di Microsoft, o versioni successive senza modifica). 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.

Note relative alla configurazione: Si vedano i parametri file_uploads, upload_max_filesize, upload_tmp_dir, e post_max_size 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.

La schermata di caricamento di un file può essere costruita con una form particolare, di questo tipo:

Esempio 20-1. Form di caricamento file

<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000">
Invia questo file: <input name="userfile" type="file">
<input type="submit" value="Invia File">
</form>
Il valore della action _URL_ dovrebbe puntare a un file PHP. Il campo nascosto MAX_FILE_SIZE deve precedere il campo di immissione del file e il suo valore è la dimensione massima accettata del file. Il valore è in byte.

Avvertimento

Il valore MAX_FILE_SIZE è consigliato al browser. E' facile aggirare questo valore, 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.

Le variabili definite per i file inviati differiscono in base alla versione di PHP ed alla configurazione. La variabile globale $_FILES esiste a partire dalla versione 4.1.0 di PHP. La matrice $HTTP_POST_FILES esiste dalla versione 4.0.0. Tutte queste matrici conterranno tutte le informazioni dei file inviati. Si consiglia di preferire l'uso di $_FILES. Se il parametro register_globals è impostato a on, esisteranno anche le relative variabili. Attenzione che per default il parametro register_globals viene impostato a off dalla versione 4.2.0 di PHP.

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.

$_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. Il campo ['error'] è stato aggiunto nella versione 4.2.0 di PHP.

Nota: Nelle versioni di PHP precedenti alla 4.1.0 questa variabile era chiamata $HTTP_POST_FILES e non era una variabile autoglobal come è $_FILES. La versione 3 di PHP non supporta $HTTP_POST_FILES.

Quando register_globals è impostato a on nel php.ini, sono disponibili variabili addizionali. Da esempio, $userfile_name sarà uguale a $_FILES['userfile']['name'], $userfile_type sarà uguale a $_FILES['userfile']['type'], eccetera. Si ricordi che a partire dalla versione 4.2.0 di PHP il parametro register_globals viene impostato a off per default. E' preferibile non fare affidamento su questo parametro.

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 20-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.
// Nelle versioni di PHP precedenti alla 4.0.3, si utilizzi copy() e is_uploaded_file() anzichè move_uploaded_file

$uploaddir = '/var/www/uploads/';
print "<pre>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir . $_FILES['userfile']['name'])) { 
    print "Il file è valido, e inviato con successo.  Ecco alcune informazioni:\n"; 
    print_r($_FILES);
} else {
    print "Possibile attacco tramite file upload! Alcune informazioni:\n"; 
    print_r($_FILES);
}
 
?>

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.

Il file sarà eliminato dalla directory temporanea al termine della richiesta se non è stato mosso e rinominato.


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.

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.

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 http CERN 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 http CERN 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.


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 è presente dalla versione 3.0.10.

Esempio 20-3. 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 20-4. 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 : /percorso/nomefile.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 21. Utilizzo di file remoti

Se allow_url_fopen è abilitato in php.ini, si possono usare URL FTP e HTTP 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 L 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 XLII, 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 21-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 21-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. */
fputs ($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 22. 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 TRUE 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 sia connection_timeout() sia connection_aborted() restituiranno TRUE. Si può anche verificare entrambi gli stati tramite una chiamata singola utilizzando la funzione connection_status(). Questa restituisce un campo di bit con l'indicazione degli stati attivi. Quindi, ad esempio, se entrambi gli stati sono attivi, la funzione restituirà 3.


Capitolo 23. Connessioni Persistenti ai Database

Connessioni persistenti sono collegamenti SQL 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).

Nota: Ci sono altre estensioni che permettono di usare connessioni persistenti, ad esempio l'estensione IMAP.

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 SQL, 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. In questa situazione, usare una connessione persistente, permette di stabilire una e una sola connessione al database SQL per ogni processo figlio, poiché ciascun processo figlio necessita di collegarsi al database SQL solo la prima volta che richiama una pagina che ne fa uso. Quando viene richamata un'altra pagina che necessita di una connessione al server SQL, essa può riutilizzare la connessione che lo stesso processo figlio aveva stabilito in precedenza.

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(), imap_popen(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ocipLogon(), odbc_pconnect(), ora_pLogon(), pfsockopen(), pg_pconnect() e sybase_pconnect().


Capitolo 24. 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.

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 24-1. 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 25. 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 make install 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 {PREFIX}/bin/php 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.

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 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 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 25-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 25-2. Costanti specifiche per CLI

    CostanteDescrizione
    STDIN Un flusso già aperto allo stdin. Questo evita di aprirlo con
    $stdin = fopen('php://stdin', 'r');
    STDOUT Un flusso già aperto allo stdout. Questo evita di aprirlo con
    $stdout = fopen('php://stdout', 'w');
    STDERR Un flusso già aperto allo stderr. Questo evita di aprirlo con
    $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] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help

  args...          Arguments passed to script. Use -- args when first argument 
                   starts with - or script is read from stdin

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

Tabella 25-3. Opzioni della linea di comando,

OptionDescription
-s

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.

-w

Visualizza il sorgente senza gli spazi e i commenti.

Nota: Questa opzione non funziona abbinata all'opzione -r.

-f

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.

-v

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

-c

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

-a

Esegue il PHP in modo interattivo.

-d

Questa opzione permette di impostare valori personalizzati per qualsiasi delle direttive di configurazione previste in php.ini. La sintassi è:
-d configuration_directive[=value]

Esempi:
# 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

Genera informazioni estese per il debugger/profiler.

-z

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

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

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]

-i 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 che l'output è in formato HTML e quindi abbastanza lungo.
-r

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 o inviate una mail a phpdoc@lists.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.

-h Con questa opzione si ha l'elenco dei comandi di linea ed una breve descrizione di questi.

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

V. Guida Funzioni

Sommario
I. Funzioni Apache
II. Funzioni di Array
III. Funzioni Aspell [deprecated]
IV. Funzioni Matematiche BCMath a precisione arbitraria
V. Funzioni di compressione Bzip2
VI. Funzioni Calendar
VII. Funzioni API CCVS [deprecate]
VIII. Funzioni di supporto COM per Windows
IX. Funzioni per Classi/Oggetti
X. Funzioni ClibPDF
XI. Funzioni di Crack
XII. Funzioni CURL, Client URL Library
XIII. Funzioni di pagamento Cybercash
XIV. Funzioni di amministrazione Cyrus IMAP
XV. Funzioni di tipo dei caratteri
XVI. Database (dbm-style) Abstraction Layer Functions
XVII. Funzioni di Data e Ora
XVIII. Funzioni dBase
XIX. Funzioni DBM
XX. dbx Functions
XXI. DB++ Functions
XXII. Funzioni per l'IO diretto
XXIII. Funzioni per le directory
XXIV. DOM Functions
XXV. Funzioni DOM XML
XXVI. Funzioni .NET
XXVII. Funzioni di gestione degli errori e di logging
XXVIII. File Alteration Monitor Functions
XXIX. FrontBase Functions
XXX. Funzioni filePro
XXXI. Filesystem functions
XXXII. Funzioni Forms Data Format
XXXIII. Funzioni FriBiDi
XXXIV. Funzioni FTP
XXXV. Function Handling Functions
XXXVI. Gettext
XXXVII. Funzioni GMP
XXXVIII. Funzioni HTTP
XXXIX. Hyperwave Functions
XL. Hyperwave API Functions
XLI. funzioni iconv
XLII. Funzioni per le immagini
XLIII. IMAP, POP3 and NNTP Functions
XLIV. Informix Functions
XLV. Funzioni InterBase
XLVI. ID3 Functions
XLVII. Ingres II Functions
XLVIII. IRC Gateway Functions
XLIX. PHP / Java Integration
L. LDAP Functions
LI. LZF Functions
LII. Funzioni di Mail
LIII. mailparse Functions
LIV. Funzioni Matematiche
LV. Multibyte String Functions
LVI. MCAL Functions
LVII. Mcrypt Encryption Functions
LVIII. MCVE Payment Functions
LIX. Memcache Functions
LX. Mhash Functions
LXI. Mimetype Functions
LXII. Funzioni per Microsoft SQL Server
LXIII. Ming functions for Flash
LXIV. Miscellaneous Functions
LXV. mnoGoSearch Functions
LXVI. mSQL Functions
LXVII. MySQL Functions
LXVIII. Improved MySQL Extension
LXIX. Mohawk Software Session Handler Functions
LXX. muscat Functions
LXXI. Funzioni di rete
LXXII. Ncurses Terminal Screen Control Functions
LXXIII. Lotus Notes Functions
LXXIV. NSAPI-specific Functions
LXXV. Funzioni ODBC Unificate
LXXVI. Object Aggregation/Composition Functions
LXXVII. Funzioni Oracle 8
LXXVIII. OpenSSL Functions
LXXIX. Funzioni Oracle
LXXX. Ovrimos SQL Functions
LXXXI. Output Control Functions
LXXXII. Proprietà object e method call overloading
LXXXIII. PDF functions
LXXXIV. Verisign Payflow Pro Functions
LXXXV. PHP Opzioni&Informazioni
LXXXVI. Funzioni POSIX
LXXXVII. Funzioni PostgreSQL
LXXXVIII. Process Control Functions
LXXXIX. Funzioni per l'esecuzione di programmi
XC. Funzioni per le Stampanti
XCI. Pspell Functions
XCII. GNU Readline
XCIII. GNU Recode Functions
XCIV. Funzioni per le espressioni regolari (Perl compatibili)
XCV. Funzioni qtdom
XCVI. Funzioni per le espressioni regolari (POSIX estesa)
XCVII. Funzioni per i semafori, la memoria condivisa ed IPC
XCVIII. SESAM Database Functions
XCIX. Funzioni di gestione della sessione
C. Funzioni relative alla memoria condivisa
CI. SimpleXML functions
CII. SOAP Functions
CIII. SQLite
CIV. Shockwave Flash Functions
CV. Funzioni per SNMP
CVI. Funzioni relative ai Socket
CVII. Standard PHP Library (SPL) Functions
CVIII. Stream Functions
CIX. Stringhe
CX. Sybase Functions
CXI. TCP Wrappers Functions
CXII. Tidy Functions
CXIII. Tokenizer Functions
CXIV. URL Functions
CXV. Funzioni di Variabili
CXVI. Funzioni vpopmail
CXVII. Funzioni W32api
CXVIII. WDDX Functions
CXIX. Funzioni relative al parser XML
CXX. Funzioni XMLRPC
CXXI. xdiff Functions
CXXII. XSL functions
CXXIII. Funzioni XSLT
CXXIV. YAZ Functions
CXXV. YP/NIS Functions
CXXVI. Funzioni per File Zip (Accesso di Sola Lettura)
CXXVII. Funzioni di compressione Zlib

I. Funzioni Apache

Introduzione

Queste funzioni sono disponibili unicamente quando PHP è eseguito come modulo Apache.

Nota: La variabile del server PATH_TRANSLATED non viene più impostata implicitamente sotto Apache 2 SAPI, diversamente da quanto accadeva in Apache 1, dove questa veniva impostata allo stesso valore della variabile SCRIPT_FILENAME qualora non fosse già riempita. Questa modifica è stata fatta per adeguarsi alle specifiche CGI. Consultare il bug #23610 per ulteriori informazioni.


Installazione

Per l'installazione di PHP su Apache vedere la sezione Apache nel capitolo che tratta l'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_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

Description

array apache_get_modules ( void )

This function returns an array with the loaded Apache modules.

Esempio 1. apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

The above example will output something similar to:

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

Description

string apache_get_version ( void )

apache_get_version() returns the version of Apache as string, or FALSE on failure.

Esempio 1. apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

The printout of the above program will look similar to:

Apache/1.3.29 (Unix) PHP/4.3.4

See also phpinfo().

apache_getenv

(PHP 4 >= 4.3.0, PHP 5)

apache_getenv --  Get an Apache subprocess_env variable

Description

string apache_getenv ( string variable [, bool walk_to_top])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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_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])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

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

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_uassoc --  Computes the difference of arrays with additional index check which is performed by a user supplied callback function
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 -- 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 due 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_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. 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_udiff -- Computes the difference of arrays by using a callback function for data comparison.
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
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 risultato di questo programma sarà:

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 risultato di questo programma sarà:

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 risultato di questo programma sarà:

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

The result is:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

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

(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 risultato di questo sarà:

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

Questo mostrerà:

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_diff() e array_diff_assoc().

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

Questo restituisce:

//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 risultato di questo programma sarà;

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

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 due o più array

Descrizione

array array_merge ( array array1, array array2 [, array ...])

array_merge() fonde gli elementi di due 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.

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
)

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

Array_multisort() Può essere usata per ordinare parecchi array allo stesso tempo, oppure un array multidimensionale, rispetto a una o più dimensioni. Mantiene le associazioni delle chiavi durante l'ordinamento, 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

Sorting type flags:

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

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Esempio 1. Ordinamre più array

<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $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 nel secondo array che corrispondono agli elementi identici nel primo array (100 e 100) vengono pure ordinati.

Esempio 2. Ordinare un array multi-dimensionale

<?php
$ar = array(array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
?>

In questo esempio, dopo l'ordinamento, il primo array conterrà 10, 100, 100, "a" (ordinato come stringhe ordine crescente), e il secondo conterrà 1, 3, "2", 1 (ordinati come numeri, in ordine decrescente).

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_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. Suggerimento: se replacement è composto solo da un elemento non è necessario porlo nel costrutto array(), a meno che l'elemento stesso non sia un array.

Valgono le seguenti equivalenze:

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, -1)
array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y))
$a[$x] = $y 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 risultato di questo programma sarà:

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. The data is compared by using 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);
?>

The result is:

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. The data is compared by using a callback function. The index check is done by a callback function also

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

The result is:

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

The result is:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

Nota: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is 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_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_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));
?>

Questo mostrerà:

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, string funcname [, mixed userdata])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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 create_function(), list(), foreach, each() e call_user_func_array().

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.

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

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

Se var non è un array, verrà restituito 1 (eccezione: count(NULL) restituisce 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.

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

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

?>

Nota: La funzione sizeof() è un alias per count().

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

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

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

III. 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"; 
    }
}

?>

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

Nel PHP 4, 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.

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.

Esempio 1. esempio di bccomp()

<?php
echo bccomp('1', '2') . "\n";

echo bccomp('1.00001', '1', 3) . "\n";
echo bccomp('1.00001', '1', 5);
?>

Questo mostrerà:

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

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.

Esempio 1. esempio di bcmod()

<?php
echo bcmod(4, 2) . "\n";
echo bcmod(2, 4);
?>

L'esempio mostrerà:

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

Esempio 1. esempio di bcmul()

<?php
echo bcmul(1.34747474747, 35, 3) . "\n";
echo bcmul(2, 4);
?>

L'esempio mostrerà:

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

Esempio 1. bcpow() example

<?php

echo bcpow(4.2, 3, 2); // 74.08

?>

Vedere anche bcsqrt() 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.

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. 

?>

Nota: Dal momento che questo metodo utilizza l'operatore modulo, numeri non naturali possono dare risultati indefiniti. Un numero naturale è un intero positivo maggiore di zero.

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.

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.

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.

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

V. 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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.0.4, 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().

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

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

VIII. 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 in
com.allow_dcom"0"PHP_INI_SYSTEM
com.autoregister_typelib"0"PHP_INI_SYSTEM
com.autoregister_verbose"0"PHP_INI_SYSTEM
com.autoregister_casesensitive"1"PHP_INI_SYSTEM
com.typelib_file""PHP_INI_SYSTEM
Per ulteriori dettagli e 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.

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. Variant is modified "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 ( object 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

(no version information, might be only in CVS)

com_get_active_object --  Returns a handle to an already running instance of a COM object

Description

object 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 requestested 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 >= 4.0.5)

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 3>= 3.0.3)

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 3>= 3.0.3)

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

com_propget -- Alias di com_get()

Descrizione

Questa funzione è un alias di com_get().

com_propput

com_propput -- Alias di com_set()

Descrizione

Questa funzione è un alias di com_set().

com_propset

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 >= 4.0.5)

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

object variant_cast ( object 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 10 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

object 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 ( object 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 ( object 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. Variant is modified "in-place"

Description

void variant_set_type ( object 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 ( object 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.

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

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 oggetto [, array array_parametri])

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 oggetto [, 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)

Questa funzione restituisce TRUE se la classe indicata dal parametro nome_classe è stata definita, altrimenti restituisce FALSE .

Vedere anche 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";
}

?>

Produrrà:

miaclasse
funzione1
funzione2

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

?>

Produrrà:

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

?>

L'esempio precedente 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());
?>

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

The above example will output something similar to: :

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

?>

L'output del programma precedente sarà:

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

?>

L'esempio visualizzerà:

Io sono figlio di dad
Pure io sono figlio di dad

Vedere anche get_class(), is_subclass_of()

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 ( object oggetto, string nome_classe)

Questa funzione restituisce TRUE se obj, appartiene ad una sottoclasse di nome_classe, altrimenti FALSE.

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

Questo script visualizzerà :

bool(true)

X. 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, 750);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 740);
cpdf_lineto($cpdf, 330, 740);
cpdf_stroke($cpdf);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

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)

cpdf_add_annotation -- Aggiunge un'annotazione

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

cpdf_add_outline

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_add_outline -- Aggiunge un segnalibro per la pagina corrente

Descrizione

void cpdf_add_outline ( int documento pdf, 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)

cpdf_arc -- Disegna un arco

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_circle().

cpdf_begin_text

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

cpdf_begin_text -- Avvia una sezione di testo

Descrizione

void cpdf_begin_text ( int documento pdf)

La funzione cpdf_begin_text() avvia una sezione di testo. 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)

cpdf_circle -- Disegna un cerchio

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_arc().

cpdf_clip

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

cpdf_clip -- Taglia dal path corrente

Descrizione

void cpdf_clip ( int documento pdf)

La funzione cpdf_clip() taglia tutti i disegni dal path corrente.

cpdf_close

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

cpdf_close -- Chiude il documento PDF

Descrizione

void cpdf_close ( int documento pdf)

La funzione cpdf_close() chiude il documento pdf. 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)

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

void cpdf_closepath_fill_stroke ( int pdf document)

The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_closepath_stroke

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

cpdf_closepath_stroke -- Chiude il path e disegna una linea lungo il path

Descrizione

void cpdf_closepath_stroke ( int documento pdf)

La funzione cpdf_closepath_stroke() è una combinazione di cpdf_closepath() e cpdf_stroke(). Dopo libera il path.

Vedere anche cpdf_closepath() e cpdf_stroke().

cpdf_closepath

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

cpdf_closepath -- Chiude la path corrente

Descrizione

void cpdf_closepath ( int documento pdf)

La funzione cpdf_closepath() chiude la path corrente.

cpdf_continue_text

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

cpdf_continue_text -- Scrive del testo nella riga seguente

Descrizione

void cpdf_continue_text ( int documento pdf, string testo)

La funzione cpdf_continue_text() scrive la stringa testo nella riga seguente.

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)

cpdf_curveto -- Disegna una curva

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando 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)

cpdf_end_text -- Termina la sezione di testo

Descrizione

void cpdf_end_text ( int documento pdf)

La funzione cpdf_end_text() termina una sezione di testo cominciata con cpdf_begin_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_begin_text().

cpdf_fill_stroke

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

cpdf_fill_stroke -- Fill and stroke current path

Description

void cpdf_fill_stroke ( int pdf document)

The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_fill

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

cpdf_fill -- Riempie il path corrente

Descrizione

void cpdf_fill ( int documento pdf)

La funzione cpdf_fill() riempie l'interno del path corrente con il colore di riempimento corrente.

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)

cpdf_finalize_page -- Chiude la pagina

Descrizione

void cpdf_finalize_page ( int documento pdf, int numero della pagina)

La funzione cpdf_finalize_page() chiude la pagina numero numero della pagina.

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)

cpdf_finalize -- Chiude il documento

Descrizione

void cpdf_finalize ( int documento pdf)

La funzione cpdf_finalize() chiude il documento. Bisogna comunque richiamare cpdf_close()

Vedere anche cpdf_close().

cpdf_global_set_document_limits

(PHP 4 , PHP 5)

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

void cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects)

The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.

See also cpdf_open().

cpdf_import_jpeg

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_import_jpeg -- Apre un'immagine JPEG

Descrizione

int cpdf_import_jpeg ( int documento pdf, string nome del file, float x-coor, float y-coor, float angolo, float larghezza, float altezza, float scala-x, float scala-y [, 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 facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_place_inline_image().

cpdf_lineto

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

cpdf_lineto -- Disegna una linea

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_moveto(), cpdf_rmoveto() e cpdf_curveto().

cpdf_moveto

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

cpdf_moveto -- Setta il punto corrente

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

cpdf_newpath

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_newpath -- Inizia un nuovo path

Descrizione

void cpdf_newpath ( int documento pdf)

La funzione cpdf_newpath() inizia un nuovo path sul documento indicato dal parametro documento pdf.

cpdf_open

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

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)

cpdf_output_buffer -- Scrive il documento pdf nel buffer di memoria

Description

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

Vedere anche cpdf_open().

cpdf_page_init

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

cpdf_page_init -- Inizia una nuova pagina

Descrizione

void cpdf_page_init ( int documento pdf, int numero di pagina, int orientamento, float altezza, float larghezza [, float unità])

La funzione cpdf_page_init() inizia una nuova pagina con altezza height e larghezza width. 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)

cpdf_place_inline_image -- Inserisce un'immagine nella pagina

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_import_jpeg().

cpdf_rect

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

cpdf_rect -- Disegna un rettangolo

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

cpdf_restore

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

cpdf_restore -- Ristabilisce le impostazioni salvate in precedenza

Descrizione

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

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)

cpdf_rlineto -- Disegna una linea

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_moveto(), cpdf_rmoveto() e cpdf_curveto().

cpdf_rmoveto

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_rmoveto -- Setta il punto corrente

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_moveto().

cpdf_rotate_text

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_rotate_text --  Setta l'angolo di rotazione del testo

Descrizione

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

cpdf_rotate -- Effettua una rotazione

Descrizione

void cpdf_rotate ( int documento pdf, float angolo)

La funzione cpdf_rotate() effettua una rotazione di angolo gradi.

cpdf_save_to_file

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

cpdf_save_to_file -- Salva il documento pdf in un file

Descrizione

void cpdf_save_to_file ( int documento pdf, string nome del file)

La funzione cpdf_save_to_file() salva il documento pdf in un file se è stato creato in memoria.

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)

cpdf_save -- Salva le impostazioni correnti

Descrizione

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

Vedere anche cpdf_restore().

cpdf_scale

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

cpdf_scale -- Applica il coefficiente di scala

Descrizione

void cpdf_scale ( int documento pdf, float scala-x, float scala-y)

La funzione cpdf_scale() applica il coefficiente di scala in entrambe le direzioni.

cpdf_set_action_url

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_set_action_url --  Imposta un link

Descrizione

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

cpdf_set_char_spacing -- Imposta la spaziatura fra caratteri

Descrizione

void cpdf_set_char_spacing ( int documento pdf, float spaziatura)

La funzione cpdf_set_char_spacing() imposta la spaziatura fra caratteri.

Vedere anche cpdf_set_word_spacing() e cpdf_set_leading().

cpdf_set_creator

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

cpdf_set_creator -- Imposta il campo creatore nel documento pdf

Descrizione

void cpdf_set_creator ( string creatore)

La funzione cpdf_set_creator() imposta il creatore del documento pdf.

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)

cpdf_set_current_page -- Imposta la pagina corrente

Descrizione

void cpdf_set_current_page ( int documento pdf, int numero di 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().

Vedere anche cpdf_finalize_page().

cpdf_set_font_directories

(PHP 4 >= 4.0.6, PHP 5)

cpdf_set_font_directories --  Imposta le directory in cui cercare quando si utilizzano font esterni

Descrizione

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

cpdf_set_font_map_file --  Imposta la tabella di associazione tra nome di file e nome di font, quando si usano font esterni

Descrizione

void cpdf_set_font_map_file ( int documento pdf, string nome del 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)

cpdf_set_font -- Seleziona l'aspetto e la dimensione del font corrente

Descrizione

void cpdf_set_font ( int documento pdf, string nome del 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.

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)

cpdf_set_horiz_scaling -- Imposta il fattore di scala orizzontale del testo

Descrizione

void cpdf_set_horiz_scaling ( int documento pdf, float scala)

La funzione cpdf_set_horiz_scaling() imposta il fattore di scala orizzontale a scala percento.

cpdf_set_keywords

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

cpdf_set_keywords -- Imposta i campi chiave del documento pdf

Descrizione

void cpdf_set_keywords ( string parole chiave)

La funzione cpdf_set_keywords() imposta le parole chiave di un documento pdf.

Vedere anche cpdf_set_title(), cpdf_set_creator() e cpdf_set_subject().

cpdf_set_leading

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

cpdf_set_leading -- Imposta la distanza fra righe di testo

Descrizione

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

Vedere cpdf_continue_text().

cpdf_set_page_animation

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

cpdf_set_page_animation -- Sets duration between pages

Description

void cpdf_set_page_animation ( int pdf document, int transition, float duration)

The cpdf_set_page_animation() function set the transition between following pages.

The value of transition can be

0 for none,
1 for two lines sweeping across the screen reveal the page,
2 for multiple lines sweeping across the screen reveal the page,
3 for a box reveals the page,
4 for a single line sweeping across the screen reveals the page,
5 for the old page dissolves to reveal the page,
6 for the dissolve effect moves from one screen edge to another,
7 for the old page is simply replaced by the new page (default)

The value of duration is the number of seconds between page flipping.

cpdf_set_subject

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

cpdf_set_subject -- Imposta il campo soggetto del documento pdf

Descrizione

void cpdf_set_subject ( string soggetto)

La funzione cpdf_set_subject() imposta il soggetto del documento pdf.

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)

cpdf_set_text_matrix -- Imposta la matrice di testo

Descrizione

void cpdf_set_text_matrix ( int documento pdf, array matrice)

La funzione cpdf_set_text_matrix() imposta una matrice che descrive una trasformazione applicata sul font corrente.

cpdf_set_text_pos

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

cpdf_set_text_pos -- Imposta la posizione del testo

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando l'unità corrente.

Vedere anche cpdf_show() e cpdf_text().

cpdf_set_text_rendering

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

cpdf_set_text_rendering -- Determines how text is rendered

Description

void cpdf_set_text_rendering ( int pdf document, int mode)

The cpdf_set_text_rendering() function determines how text is rendered.

The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.

cpdf_set_text_rise

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

cpdf_set_text_rise -- Sets the text rise

Description

void cpdf_set_text_rise ( int pdf document, float value)

The cpdf_set_text_rise() function sets the text rising to value units.

cpdf_set_title

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

cpdf_set_title -- Imposta il campo titolo del documento pdf

Descrizione

void cpdf_set_title ( string titolo)

La funzione cpdf_set_title() imposta il titolo di un documento pdf.

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)

cpdf_set_viewer_preferences --  How to show the document in the viewer

Description

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

cpdf_set_word_spacing -- Imposta la spaziatura fra parole

Descrizione

void cpdf_set_word_spacing ( int documento pdf, float spaziatura)

La funzione cpdf_set_word_spacing() imposta la spaziatura fra parole.

Vedere cpdf_set_char_spacing() e cpdf_set_leading().

cpdf_setdash

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

cpdf_setdash -- Sets dash pattern

Description

void cpdf_setdash ( int pdf document, float white, float black)

The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.

cpdf_setflat

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

cpdf_setflat -- Sets flatness

Description

void cpdf_setflat ( int pdf document, float value)

The cpdf_setflat() function set the flatness to a value between 0 and 100.

cpdf_setgray_fill

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

cpdf_setgray_fill -- Imposta il grigio come colore per il riempimento

Descrizione

void cpdf_setgray_fill ( int documento pdf, float valore)

La funzione cpdf_setgray_fill() imposta il valore corrente di grigio come riempimento del path.

Vedere anche cpdf_setrgbcolor_fill().

cpdf_setgray_stroke

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

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

void cpdf_setgray_stroke ( int pdf document, float gray value)

The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.

See also cpdf_setrgbcolor_stroke().

cpdf_setgray

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

cpdf_setgray -- Imposta il grigio come colore per il disegno e il riempimento

Descrizione

void cpdf_setgray ( int documento pdf, float valore di grigio)

La funzione cpdf_setgray() imposta come colore per il disegno e il riempimento il valore di grigio passato.

Vedere anche cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().

cpdf_setlinecap

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

cpdf_setlinecap -- Sets linecap parameter

Description

void cpdf_setlinecap ( int pdf document, int value)

The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.

cpdf_setlinejoin

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

cpdf_setlinejoin -- Sets linejoin parameter

Description

void cpdf_setlinejoin ( int pdf document, long value)

The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.

cpdf_setlinewidth

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

cpdf_setlinewidth -- Imposta la larghezza delle linee

Description

void cpdf_setlinewidth ( int documento pdf, float larghezza)

La funzione cpdf_setlinewidth() imposta la larghezza delle linee a larghezza.

cpdf_setmiterlimit

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

cpdf_setmiterlimit -- Sets miter limit

Description

void cpdf_setmiterlimit ( int pdf document, float value)

The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.

cpdf_setrgbcolor_fill

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

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

void cpdf_setrgbcolor_fill ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().

cpdf_setrgbcolor_stroke

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

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

void cpdf_setrgbcolor_stroke ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.

See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_setrgbcolor

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

cpdf_setrgbcolor -- Imposta il valore del colore rgb come colore per il disegno e il riempimento

Descrizione

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

Vedere anche cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().

cpdf_show_xy

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

cpdf_show_xy -- Output text at position

Description

void cpdf_show_xy ( int pdf document, string text, float x-coor, float y-coor [, int mode])

The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Nota: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.

See also cpdf_text().

cpdf_show

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

cpdf_show -- Scrive il testo alla posizione corrente

Descrizione

void cpdf_show ( int documento pdf, string testo)

La funzione cpdf_show() scrive la stringa in testo alla posizione corrente.

Vedere anche cpdf_text(), cpdf_begin_text() e cpdf_end_text().

cpdf_stringwidth

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

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)

cpdf_stroke -- Disegna una linea lungo il path

Description

void cpdf_stroke ( int documento pdf)

La funzione cpdf_stroke() disegna una linea lungo il path corrente.

Vedere anche cpdf_closepath() e cpdf_closepath_stroke().

cpdf_text

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

cpdf_text -- Scrive il testo con i parametri

Descrizione

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

Il parametro facoltativo modo determina l'unità di lunghezza. Se è 0 o è omesso viene utilizzata l'unità di default specificata per la pagina. Altrimenti le coordinate sono misurate in punti postscript trascurando 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)

cpdf_translate -- Sets origin of coordinate system

Description

void cpdf_translate ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

XI. 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 rimosso da PHP 5 ed inserito tra le librerie PECL.


Requisiti

Maggiori informazioni riguardo CrackLib possono essere trovate, insieme alla libreria, a http://www.crypticide.org/users/alecm/.


Installazione

Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto per Crack utilizzando --with-crack[=DIR] option.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Opzioni di configurazione per Crack

NomeDefaultModificabile
crack.default_dictionaryNULLPHP_INI_SYSTEM
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

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)

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)

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)

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)

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

XII. 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_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)


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

curl_copy_handle

(PHP 5)

curl_copy_handle --  Copy a cURL handle along with all of it's preferences

Description

resource curl_copy_handle ( resource ch)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

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

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

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

  • "header_size"

  • "request_size"

  • "filetime"

  • "ssl_verify_result"

  • "redirect_count"

  • "total_time"

  • "namelookup_time"

  • "connect_time"

  • "pretransfer_time"

  • "size_upload"

  • "size_download"

  • "speed_download"

  • "speed_upload"

  • "download_content_length"

  • "upload_content_length"

  • "starttransfer_time"

  • "redirect_time"

curl_init

(PHP 4 >= 4.0.2, 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
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
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)

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, string opzione, mixed valore)

La funzione curl_setopt() imposta le opzioni per una sessione CURL identificata dal parametro ch. Il parametro opzione indica l'opzione che si vuole impostare e valore è il valore dell'opzione data da opzione.

Il valore dovrebbe essere di tipo long per le seguenti opzioni (specificato nel parametro opzione):

  • CURLOPT_INFILESIZE: Quando si carica un file su un server remoto, questa opzione dovrebbe essere usata per dire a PHP quale dimensione attendersi dal file in arrivo.

  • CURLOPT_VERBOSE: Impostare questa opzione a un valore diverso da zero se si vuole che CURL to segnali tutto quello che sta avvenendo.

  • CURLOPT_HEADER: Impostare questa opzione a un valore diverso da zero se si vuole che gli header vengano inclusi nell'output.

  • CURLOPT_NOPROGRESS: Impostare questa opzione a un valore diverso da zero se non si vuole che PHP mostri l'indicazione di avanzamento nei trasferimenti CURL.

    Nota: PHP imposta automaticamente questa opzione a un valore non-zero, esso dovrebbe essere cambiato solo per eseguire il debug.

  • CURLOPT_NOBODY: Impostare questa opzione a un valore diverso da zero se non si desidera l'inclusione del body nell'output.

  • CURLOPT_FAILONERROR: Impostare questa opzione a un valore diverso da zero se si vuole che PHP termini senza generare messaggi se il codice HTTP restituito è maggiore di 300. Il comportamento di default è di restituire la pagina comunque, ignorando la presenza del codice.

  • CURLOPT_UPLOAD: Impostare questa opzione a un valore diverso da zero se si vuole che PHP si prepari per un upload.

  • CURLOPT_POST: Impostare questa opzione a un valore diverso da zero se si vuole che PHP esegua un comune HTTP POST. Questo POST è di tipo application/x-www-form-urlencoded, molto spesso usato nei form HTML.

  • CURLOPT_FTPLISTONLY: Impostare questa opzione a un valore diverso da zero e PHP semplicemente elencherà i nomi in una directory FTP.

  • CURLOPT_FTPAPPEND: Impostare questa opzione a un valore diverso da zero e PHP accoderà l'output al file remoto invece di sovrascrivere.

  • CURLOPT_NETRC: Impostare questa opzione a un valore diverso da zero e PHP leggerà il vostro file ~./netrc al fine di trovare username e password per il server remoto verso il quale si sta eseguendo la connessione.

  • CURLOPT_FOLLOWLOCATION: Impostare questa opzione a un valore diverso da zero per seguire ogni header "Location: " che il server dovesse inviare come parte degli header HTTP (si noti che questo è ricorsivo, PHP seguirà tutti gli header "Location: " che dovessero essere inviati.)

  • CURLOPT_PUT: Impostare questa opzione a un valore diverso da zero per eseguire un HTTP PUT su un file. Il file su cui eseguire PUT deve essere impostato con CURLOPT_INFILE e CURLOPT_INFILESIZE.

  • CURLOPT_MUTE: Impostare questa opzione a un valore diverso da zero e PHP resterà silenzioso riguardo alle funzioni CURL.

  • CURLOPT_TIMEOUT: Passa un tipo di dato long come parametro che contiene il tempo massimo, in secondi, che si è disposti a concedere alle funzioni CURL.

  • CURLOPT_LOW_SPEED_LIMIT: Passa un tipo di dato long come parametro contenente la velocità di trasferimento espressa in byte al secondo, velocità al di sotto della quale il trasferimento dovrà rimanere per CURLOPT_LOW_SPEED_TIME secondi affinché PHP lo consideri troppo lento e lo termini.

  • CURLOPT_LOW_SPEED_TIME: Passa un tipo di dato long come parametro che contiene il tempo in secondi che il trasferimento dovrà rimanere al di sotto del valore CURLOPT_LOW_SPEED_LIMIT affinché PHP lo consideri troppo lento e lo termini.

  • CURLOPT_RESUME_FROM: Passa un tipo di dato long come parametro che contiene l'offset, in byte, dal quale partire per effettuare il trasferimento.

  • CURLOPT_CAINFO: Passa il nome di un file contenente uno o più certificati da validare con la controparte. Questo ha senso solo quando viene usato con il parametro CURLOPT_SSL_VERIFYPEER.

  • CURLOPT_SSL_VERIFYPEER: Passa un long che se impostato a zero ferma la verifica dei certificati da parte di curl (per default curl 7.10 ha questa opzione impostata a TRUE). Si possono specificare certificati alternativi usando l'opzione CURLOPT_CAINFO (aggiunta in curl 7.9.8) oppure si può specificare una directory contenente i certificati usando CURLOPT_CAPATH. Dalla versione 7.10 curl installa un'area di default. Può essere necessario impostare il parametro CURLOPT_SSL_VERIFYHOST a 1 oppure 0 se CURLOPT_SSL_VERIFYPEER è disabilitato (per default è impostato a 2).

  • CURLOPT_SSLVERSION: Passa un tipo di dato long come parametro che contiene la versione SSL (2 o 3) da usare. Di default PHP cercherà di determinare questo dato sè, ciononostante, in alcuni casi andrà impostato manualmente.

  • CURLOPT_SSL_VERIFYHOST: Passa un tipo di dato long se CURL deve verificare il common name del peer certificate durante l'handshake SSL. Un valore di 1 denota che si deve cercare l'esistenza del common name, un valore di 2 denota che dovremo assicurarci che corrisponda all'hostname fornito.

  • CURLOPT_TIMECONDITION: Passa un tipo di dato long come parametro che che definisce come trattare CURLOPT_TIMEVALUE. Si può impostare questo parametro a TIMECOND_IFMODSINCE o TIMECOND_ISUNMODSINCE. Questa è una caratteristica del solo HTTP.

  • CURLOPT_TIMEVALUE: Passa un tipo di dato long come parametro che rappresenta il tempo espresso in secondi trascorsi dal 1 Gennaio 1970. Il tempo verrà usato come specificato dall'opzione CURLOPT_TIMECONDITION o di default verrà usato TIMECOND_IFMODSINCE.

  • CURLOPT_RETURNTRANSFER: Passa un valore diverso da zero se si desidera che CURL restituisca direttamente il trasferimento invece di stamparlo.

Il parametro valore deve essere una stringa per i seguenti valori del parametro opzione:

  • CURLOPT_URL: Questo è l'URL che si desidera far salvare da PHP. Si può anche impostare questa opzione quando si inizializza una sessione con la funzione curl_init().

  • CURLOPT_USERPWD: Passa una stringa formattata come [username]:[password], che sarà usata da PHP per la connessione.

  • CURLOPT_PROXYUSERPWD: Passa una stringa formattata come [username]:[password], per la connessione al proxy HTTP.

  • CURLOPT_RANGE: Passa il range richiesto. Deve essere nel formato "X-Y", dove X o Y possono essere omessi. I trasferimenti HTTP supportano anche intervalli multipli, separati da virgole come in X-Y,N-M.

  • CURLOPT_POSTFIELDS: Passa una stringa contenente tutti i dati da inviare durante una richiesta HTTP "POST".

  • CURLOPT_REFERER: Passa una stringa contenente l'header "referer" che verrà usato in una richiesta HTTP.

  • CURLOPT_USERAGENT: Passa una stringa contenente l'header "user-agent" che sarà usato nella richiesta HTTP.

  • CURLOPT_FTPPORT: Passa una stringa contenente il valore che verrà usato per ottenere l'indirizzo IP da usarsi per l'istruzione "POST" dell'ftp. L'istruzione POST dice al server remoto di collegarsi al nostro indirizzo IP specificato. La stringa può essere un semplice indirizzo IP, un hostname, il nome di una interfaccia di rete (sotto Unix) o semplicemente un '-' per indicare di usare l'indirizzo IP di default del sistema.

  • CURLOPT_COOKIE: Passa una stringa contenente il contenuto del cookie da impostare nell'header HTTP.

  • CURLOPT_SSLCERT: Passa una stringa contenente il filename del certificato formattato secondo PEM.

  • CURLOPT_SSLCERTPASSWD: Passa una stringa contenente la password richiesta per usare il certificato CURLOPT_SSLCERT .

  • CURLOPT_COOKIEFILE: Passa una stringa contenente il nome del file contenente i dati relativi al cookie. Il file del cookie può essere in formato Netscape o semplicemente un dump degli header in stile HTTP.

  • CURLOPT_CUSTOMREQUEST: Passa una stringa da usare al posto di GET o HEAD nell'effettuare una richiesta HTTP. Questo è utile per effettuare un DELETE o altre, più oscure richieste HTTP. Valori validi sono cose del tipo GET, POST e così via; per esempio non inserire qui una richiesta HTTP intera. Per esempio, inserire 'GET /index.html HTTP/1.0\r\n\r\n' sarebbe sbagliato.

    Nota: Non eseguire se non si è sicuri che il proprio server supporti il comando.

  • CURLOPT_PROXY: Indica il nome del server proxy HTTP attraverso il quale inviare le richieste.

  • CURLOPT_INTERFACE: Passa il nome dell'interfaccia di rete da usare in uscita. Questo può essere il nome di un'interfaccia, un indirizzo IP o un nome di host.

  • CURLOPT_KRB4LEVEL: Passa il security level KRB4 (Kerberos 4). Ognuna delle seguenti stringhe (in ordine dalla meno alla più potente): 'clear', 'safe', 'confidential', 'private'. Se la stringa inviata non corrisponde a nessuna di queste, verrà usata 'private'. Se si imposta a NULL, la security KRB4 verrà disabilitata. La security KRB4, al momento, funziona solamente con le transazioni FTP.

  • CURLOPT_HTTPHEADER: Passa un array di campi header HTTP da impostare.

  • CURLOPT_QUOTE: Passa un array di comandi FTP da eseguire sul server, prima della richiesta FTP.

  • CURLOPT_POSTQUOTE: Passa un array di comandi FTP da eseguire sul server, dopo che la richiesta FTP è stata eseguita.

Le opzioni seguenti richiedono un descrittore a file che è ottenuto usando la funzione fopen():

  • CURLOPT_FILE: Il file dove mettere l'output del trasferimento, di default è STDOUT.

  • CURLOPT_INFILE: Il file da cui proviene l'input del trasferimento.

  • CURLOPT_WRITEHEADER: Il file sul quale scrivere la parte di output contenente gli header.

  • CURLOPT_STDERR: Il file sul quale scrivere gli errori invece di stderr.

curl_version

(PHP 4 >= 4.0.2, PHP 5)

curl_version -- Restituisce la versione di CURL in uso

Descrizione

string curl_version ( void )

La funzione curl_version() restituisce una stringa contenente la versione di CURL attualmente in uso.

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

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)

cybercash_base64_encode -- Codifica dei dati in base64 per Cybercash

Descrizione

string cybercash_base64_encode ( string inbuff)

cybercash_decr

(PHP 4 <= 4.2.3)

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)

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

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

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)

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)

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)

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)

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)

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.

XV. 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]. La funzione è equivalente a (ctype_alpha($text) || ctype_digit($text)).

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)), ma altri linguaggi hanno lettere che non sono considerate nè maiuscole nè minuscole.

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.

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.

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.

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.

Vedere anche ctype_alpha() e ctype_upper().

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.

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.

Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().

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

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.

Vedere anche ctype_alpha() e ctype_lower().

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.

Vedere anche ctype_digit().

XVI. 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 missconfigurations.


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

for ($i = 0; $i < count($handle_later); $i++) {
    dba_delete($handle_later[$i], $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 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

Description

void dba_close ( resource handle)

dba_close() closes the established database and frees all resources specified by handle.

handle is a database handle returned by dba_open().

dba_close() does not return any value.

See also dba_open(), and dba_popen()

dba_delete

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

dba_delete -- Delete DBA entry specified by key

Description

bool dba_delete ( string key, resource handle)

dba_delete() deletes the entry specified by key from the database specified with handle.

key is the key of the entry which is deleted.

handle is a database handle returned by dba_open().

dba_delete() returns TRUE or FALSE, if the entry is deleted or not deleted, respectively.

See also dba_exists(), dba_fetch(), dba_insert(), and dba_replace().

dba_exists

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

dba_exists -- Check whether key exists

Description

bool dba_exists ( string key, resource handle)

dba_exists() checks whether the specified key exists in the database specified by handle.

Key is the key the check is performed for.

Handle is a database handle returned by dba_open().

dba_exists() returns TRUE or FALSE, if the key is found or not found, respectively.

See also: dba_fetch(), dba_delete(), dba_insert(), and dba_replace().

dba_fetch

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

dba_fetch -- Fetch data specified by key

Description

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.

Key is the key the data is specified by.

Skip is the number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

Handle is a database handle returned by dba_open().

dba_fetch() returns the associated string or FALSE, if the key/data pair is found or not found, respectively.

Nota: The skip parameter is available since PHP 4.3 to support cdb's capability of multiple keys having the same name.

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

See also dba_exists(), dba_delete(), dba_insert(), dba_replace() and dba_key_split().

dba_firstkey

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

dba_firstkey -- Fetch first key

Description

string dba_firstkey ( resource handle)

dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.

Handle is a database handle returned by dba_open().

dba_firstkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also dba_nextkey(), dba_key_split() and example 2 in the DBA examples

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers -- List handlers available

Description

array dba_handlers ( void )

dba_handlers() returns an array with all handlers supported by this extension.

When the internal cdb library is used you will see 'cdb' and 'cdb_make'.

dba_insert

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

dba_insert -- Insert entry

Description

bool dba_insert ( string key, string value, resource handle)

dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_insert() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also dba_exists() dba_delete() dba_fetch() dba_replace()

dba_key_split

(PHP 5)

dba_key_split -- Splits a key in string representation into array representation

Description

mixed dba_key_split ( mixed key)

dba_key_split() returns an array of the form array(0=>group,1=>value_name). This function will return FALSE if key is NULL or FALSE.

key is the key in string representation.

See also dba_firstkey(), dba_nextkey(), and dba_fetch().

dba_list

(PHP 4 >= 4.3.0, PHP 5)

dba_list -- List all open database files

Description

array dba_list ( void )

dba_list() returns an associative array with all open database files. This array is in the form: resourceid=>filename.

dba_nextkey

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

dba_nextkey -- Fetch next key

Description

string dba_nextkey ( resource handle)

dba_nextkey() returns the next key of the database specified by handle and advances the internal key pointer.

handle is a database handle returned by dba_open().

dba_nextkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also dba_firstkey(), dba_key_split() and example 2 in the DBA examples

dba_open

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

dba_open -- Open database

Description

resource dba_open ( string path, string mode, string handler [, ...])

dba_open() establishes a database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access. Additional you can set the database lock method with the next char. Use "l" to lock the database with an .lck file or "d" to lock the databasefile itself. It is important that all of your applications do this consistently. If you want to test the access and do not want to wait for the lock you can add "t" as third character. When you are 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".

handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.

dba_open() returns a positive handle or FALSE, in the case the database was opened successfull or fails, respectively.

Nota: There can only be one writer for one database file. When you use dba on a webserver and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the 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.

Nota: Since PHP 4.3.0 it is possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.

Nota: Locking and the mode modifiers "l", "d", "-" and "t" were added in PHP 4.3.0. In PHP versions before PHP 4.3.0 you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.

Nota: Up to PHP 4.3.5 open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existant database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

See also dba_popen(), and dba_close()

dba_optimize

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

dba_optimize -- Optimize database

Description

bool dba_optimize ( resource handle)

dba_optimize() optimizes the underlying database specified by handle.

handle is a database handle returned by dba_open().

dba_optimize() returns TRUE or FALSE, if the optimization succeeds or fails, respectively.

See also: dba_sync()

dba_popen

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

dba_popen -- Open database persistently

Description

resource dba_popen ( string path, string mode, string handler [, ...])

dba_popen() establishes a persistent database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.

handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.

dba_popen() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_open() dba_close()

dba_replace

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

dba_replace -- Replace or insert entry

Description

bool dba_replace ( string key, string value, resource handle)

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_replace() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists(), dba_delete(), dba_fetch(), and dba_insert().

dba_sync

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

dba_sync -- Synchronize database

Description

bool dba_sync ( resource handle)

dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.

handle is a database handle returned by dba_open().

dba_sync() returns TRUE or FALSE, if the synchronization succeeds or fails, respectively.

See also: dba_optimize()

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

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

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

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

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

Nota: Questo modulo ` stato rimosso da PHP 5 ed inserito tra le librerie PECL.


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 )

dblist --  Descrive la libreria DBM-compatibile in uso.

Descrizione

string dblist ( void )

dbmclose

(PHP 3, PHP 4 )

dbmclose -- Chiude un database dbm

Descrizione

bool dbmclose ( int dbm_identifier)

Sblocca e chiude il database specificato.

dbmdelete

(PHP 3, PHP 4 )

dbmdelete --  Cancella il valore per una chiave da un database DBM

Descrizione

bool dbmdelete ( int 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 )

dbmexists --  Dice se esiste un valore per una chiave in un database DBM

Descrizione

bool dbmexists ( int dbm_identifier, string key)

Restituisce TRUE se c'è un valore associato con la key.

dbmfetch

(PHP 3, PHP 4 )

dbmfetch --  Estrae un valore per una chiave da un database DBM

Descrizione

string dbmfetch ( int dbm_identifier, string key)

Restituisce il valore associato con key.

dbmfirstkey

(PHP 3, PHP 4 )

dbmfirstkey --  Recupera la prima chiave da un database DBM

Descrizione

string dbmfirstkey ( int 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 )

dbminsert --  Inserisce un valore per una chiave in un database DBM

Descrizione

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

dbmnextkey --  Recupera la chiave successiva da un database DBM

Descrizione

string dbmnextkey ( int 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

$key = dbmfirstkey ($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch ($dbm_id, $key) . "\n";
    $key = dbmnextkey ($dbm_id, $key);
}

dbmopen

(PHP 3, PHP 4 )

dbmopen -- Apre un database DBM

Descrizione

int 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à filename.dir e filename.pag files. 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 )

dbmreplace --  Sostituisce il valore per una chiave in un database DBM

Descrizione

int dbmreplace ( int 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à.

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


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

NameDefaultChangeable
dbx.colnames_case"unchanged"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Nota: This ini-option is available available from PHP 4.3.0.

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

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_RESULT_UNBUFFERED (integer) (CVS only)

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)

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)

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)

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" (CVS only)

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)

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)

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)

dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

object 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 array 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)

dbx_query -- Send a query and fetch all results (if any)

Description

object 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 (CVS only)

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)

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

XXI. 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 -- ???
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation
dbplus_next -- Get next tuple from relation
dbplus_open -- Open relation file
dbplus_prev -- Get previous tuple from relation
dbplus_rchperm -- Change relation permissions
dbplus_rcreate -- Creates a new DB++ relation
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_resolve -- Resolve host information for relation
dbplus_restorepos -- ???
dbplus_rkeys -- Specify new primary key for a relation
dbplus_ropen -- Open relation file local
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex --  Create a new secondary index for a relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation
dbplus_savepos -- ???
dbplus_setindex -- ???
dbplus_setindexbynumber -- ???
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- ???
dbplus_undoprepare -- ???
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation
dbplus_update -- Update specified tuple in relation
dbplus_xlockrel -- Request exclusive lock on relation
dbplus_xunlockrel -- Free exclusive lock on relation

dbplus_add

(4.1.0 - 4.2.3 only)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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)

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)

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)

dbplus_close -- Close a relation

Description

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

dbplus_curr

(4.1.0 - 4.2.3 only)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

dbplus_info -- ???

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.

Not implemented yet.

dbplus_last

(4.1.0 - 4.2.3 only)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array tuple)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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)

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)

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)

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)

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)

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)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

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

dbplus_rcrtlike

(4.1.0 - 4.2.3 only)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

resource dbplus_rcrtlike ( string name, resource relation, int flag)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_resolve

(4.1.0 - 4.2.3 only)

dbplus_resolve -- Resolve host information for relation

Description

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

dbplus_restorepos -- ???

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.

Not implemented yet.

dbplus_rkeys

(4.1.0 - 4.2.3 only)

dbplus_rkeys -- Specify new primary key for a relation

Description

resource dbplus_rkeys ( resource relation, mixed domlist)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

dbplus_ropen

(4.1.0 - 4.2.3 only)

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)

dbplus_rquery -- Perform local (raw) AQL query

Description

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

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)

dbplus_rsecindex --  Create a new secondary index for a relation

Description

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

dbplus_runlink

(4.1.0 - 4.2.3 only)

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)

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)

dbplus_savepos -- ???

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.

Not implemented yet.

dbplus_setindex

(4.1.0 - 4.2.3 only)

dbplus_setindex -- ???

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.

Not implemented yet.

dbplus_setindexbynumber

(4.1.0 - 4.2.3 only)

dbplus_setindexbynumber -- ???

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.

Not implemented yet.

dbplus_sql

(4.1.0 - 4.2.3 only)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query, string server, string dbpath)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Not implemented yet.

dbplus_tcl

(4.1.0 - 4.2.3 only)

dbplus_tcl -- Execute TCL code on server side

Description

int dbplus_tcl ( int sid, string script)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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)

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)

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

Not implemented yet.

dbplus_undoprepare

(4.1.0 - 4.2.3 only)

dbplus_undoprepare -- ???

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.

Not implemented yet.

dbplus_unlockrel

(4.1.0 - 4.2.3 only)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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)

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)

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)

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)

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

XXII. 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 non è disponibile su piattaforme Windows.


Requisiti

Non sono necessarie librerie esterne per utilizzare questo modulo.


Installazione

Per potere utilizzare queste funzioni, occorre configurare PHP con --enable-dio.


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


Costanti predefinite

Questa estensione non definisce alcuna costante.

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 fd e li restituisce, se n non è specificato, legge un blocco da 1k
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)

dio_close -- Chiude il descrittore di file passato

Descrizione

void dio_close ( resource fd)

La funzione dio_close() chiude il descrittore di file fd.

Vedere anche dio_open().

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5)

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.

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)

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.

dio_open

(PHP 4 >= 4.2.0, PHP 5)

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, oppure FALSE se si verificano problemi. Se flags viene impostato a O_CREAT, nel terzo parametro, opzionale, mode verranno impostati i permessi del file (permessi di creazione). Il parametro flags può avere i seguenti valori:

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

Il parametro flags può includere 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.

Vedere anche: dio_close().

dio_read

(PHP 4 >= 4.2.0, PHP 5)

dio_read --  Legge n bytes da un descrittore fd e li restituisce, se n non è specificato, legge un blocco da 1k

Descrizione

string dio_read ( resource fd [, int n])

La funzione dio_read() legge e restituisce n bytes dal file indicato dal descrittore fd. Se n viene omesso, la funzione dio_read() leggerà e restituirà un blocco da 1k.

Vedere anche: dio_write().

dio_seek

(PHP 4 >= 4.2.0, PHP 5)

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 con descrittore fd. Il parametro whence specifica come debba essere interpretata la posizione indicata da pos:

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

dio_stat

(PHP 4 >= 4.2.0, PHP 5)

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 file con descrittore fd. dio_stat() 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" - dimensione totale in byte

  • "blocksize" - blocksize

  • "blocks" - numero di blocchi allocati

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

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. Attualmente le opzioni disponibili sono:

  • 'baud' - velocità della porta - può essere 38400,19200,9600,4800,2400,1800,1200,600,300,200,150,134,110,75 oppure 50, il valore di default è 9600

  • 'bits' - bit di dati - può essere 8,7,6 oppure 5 il valore di default è 8

  • 'stop' - bit di stop - può essere 1 o 2 il valore di default è 1

  • 'parity' - può essere 0,1 o 2 il valore di default è 0

Esempio 1. Esempio di impostazione della velocità di una porta seriale

<?php

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

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 di zero. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..

dio_write

(PHP 4 >= 4.2.0, PHP 5)

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. Se il parametro len viene omesso, dio_write() scrive tutto il contenuto di data nel file indicato. La funzione dio_write() restituisce il numero di byte scritti in fd.

Vedere anche dio_read().

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

Questo 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

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

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

Vedere anche chdir().

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. Si può sopprimere l'output dell'errore di opendir() anteponendo `@' davanti al nome della funzione.

Esempio 1. esempio opendir()

<?php

if ($dir = @opendir("/tmp")) {
  while (($file = readdir($dir)) !== false) { 
    echo "$file\n";
  }  
  closedir($dir);
}

?>

Vedere anche is_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

// Nota che l'operatore !== non è esistito fino alla versione 4.0.0-RC2
<?php
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().

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

Description

array scandir ( string directory [, int sorting_order [, resource context]])

Returns an array of files and directories from the directory. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then sort order is alphabetical in descending order.

Esempio 1. A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

Outputs something like:

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

?>

Outputs something like:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

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 L per avere la lista dei protocolli URL supportati.

See also opendir(), readdir(), glob(), is_dir(), and sort().

XXIV. DOM Functions

Introduzione

The DOM extension is the replacement for the domxml extension from PHP 4. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API.


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. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is an element
XML_ATTRIBUTE_NODE (integer) 2Node is an attribute
XML_TEXT_NODE (integer) 3Node is a piece of text
XML_CDATA_SECTION_NODE (integer) 4 
XML_ENTITY_REF_NODE (integer) 5 
XML_ENTITY_NODE (integer) 6Node is an entity like &nbsp;
XML_PI_NODE (integer) 7Node is a processing instruction
XML_COMMENT_NODE (integer) 8Node is a comment
XML_DOCUMENT_NODE (integer) 9Node is a document
XML_DOCUMENT_TYPE_NODE (integer) 10 
XML_DOCUMENT_FRAG_NODE (integer) 11 
XML_NOTATION_NODE (integer) 12 
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 2. DOMException constants

ConstantValueDescription
DOM_INDEX_SIZE_ERR (integer) 1 
DOMSTRING_SIZE_ERR (integer) 2 
DOM_HIERARCHY_REQUEST_ERR (integer) 3 
DOM_WRONG_DOCUMENT_ERR (integer) 4 
DOM_INVALID_CHARACTER_ERR (integer) 5 
DOM_NO_DATA_ALLOWED_ERR (integer) 6 
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) 7 
DOM_NOT_FOUND_ERR (integer) 8 
DOM_NOT_SUPPORTED_ERR (integer) 9 
DOM_INUSE_ATTRIBUTE_ERR (integer) 10 
DOM_INVALID_STATE_ERR (integer) 11 
DOM_SYNTAX_ERR (integer) 12 
DOM_INVALID_MODIFICATION_ERR (integer) 13 
DOM_NAMESPACE_ERR (integer) 14 
DOM_INVALID_ACCESS_ERR (integer) 15 
DOM_VALIDATION_ERR (integer) 16 

Classes

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module.

This module defines a number of classes, which are listed - including their method - in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

Tabella 3. List of classes

Class nameParent classes
DOMAttrDOMNode
DOMCDataSectionDOMText : DOMNode
DOMCharacterDataDOMNode
DOMCommentDOMCharacterData : DomNode
DOMDocumentDOMNode
DOMDocumentFragmentDOMNode
DOMDocumentTypeDOMNode
DOMElementDOMNode
DOMEntityDOMNode
DOMEntityReferenceDOMNode
DOMNode 
DOMNotationDOMNode
DOMProcessingInstructionDOMNode
DOMTextDOMCDataSection : DomNode
DOMException 
DOMImplementation 
DOMNamedNodeMap 
DOMNodeList 
DOMXPath 

Sommario
DOMAttr->isId --  Checks if attribute is a defined ID
DOMCharacterData->appendData --  Append the string to the end of the character data of the node.
DOMCharacterData->deleteData --  Remove a range of characters from the node.
DOMCharacterData->insertData --  Insert a string at the specified 16-bit unit offset.
DOMCharacterData->replaceData --  Replace a substring within the DOMCharacterData node.
DOMCharacterData->substringData --  Extracts a range of data from the node.
DOMDocument->createAttribute -- Create new attribute
DOMDocument->createAttributeNS --  Create new attribute node with an associated namespace
DOMDocument->createCDATASection -- Create new cdata node
DOMDocument->createComment -- Create new comment node
DOMDocument->createDocumentFragment -- Create new document fragment
DOMDocument->createElement -- Create new element node
DOMDocument->createElementNS --  Create new element node with an associated namespace
DOMDocument->createEntityReference -- Create new entity reference node
DOMDocument->createProcessingInstruction -- Creates new PI node
DOMDocument->createTextNode -- Create new text node
DOMDocument->getElementById -- Searches for an element with a certain id.
DOMDocument->getElementsByTagName -- Searches for all elements with given tag name.
DOMDocument->getElementsByTagNameNS --  Searches for all elements with given tag name in specified namespace.
DOMDocument->importNode -- Import node into current document.
DOMDocument->load --  Load XML from a file.
DOMDocument->loadHTML --  Load HTML from a string.
DOMDocument->loadHTMLFile --  Load HTML from a file.
DOMDocument->loadXML --  Load XML from a string.
DOMDocument->normalize --  Normalizes document.
DOMDocument->relaxNGValidate --  Performs relaxNG validation on the document.
DOMDocument->relaxNGValidateSource --  Performs relaxNG validation on the document.
DOMDocument->save --  Dumps the internal XML tree back into a file
DOMDocument->saveHTML --  Dumps the internal document into a string using HTML formatting
DOMDocument->saveHTMLFile --  Dumps the internal document back 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 --  Validates the document based on its DTD.
DOMDocument->xinclude --  Substitutes XIncludes in a DOMDocument Object.
DOMElement->getAttribute -- Returns value of attribute
DOMElement->getAttributeNode -- Returns attribute node
DOMElement->getAttributeNodeNS --  Returns attribute node
DOMElement->getAttributeNS -- Returns value of attribute
DOMElement->getElementsByTagName -- Gets elements by tagname
DOMElement->getElementsByTagNameNS -- Get elements by namespaceURI and localName
DOMElement->hasAttribute -- Checks to see if attribute exists
DOMElement->hasAttributeNS --  Checks to see if attribute exists
DOMElement->removeAttribute -- Removes attribute
DOMElement->removeAttributeNode -- Removes attribute
DOMElement->removeAttributeNS -- Removes attribute
DOMElement->setAttribute -- Adds new attribute
DOMElement->setAttributeNode -- Adds new attribute node to element
DOMElement->setAttributeNodeNS -- Adds new attribute node to element
DOMElement->setAttributeNS -- Adds new attribute
DOMImplementation->createDocument --  Creates a DOM Document object of the specified type with its document element.
DOMImplementation->createDocumentType --  Creates an empty DOMDocumentType object.
DOMImplementation->hasFeature --  Test if the DOM implementation implements a specific feature and version.
DOMNamedNodeMap->getNamedItem --  Retrieves a node specified by name.
DOMNamedNodeMap->getNamedItemNS --  Retrieves a node specified by local name and namespace URI.
DOMNamedNodeMap->item -- Retrieves a node specified by index.
DOMNode->appendChild --  Adds new child at the end of the children
DOMNode->cloneNode --  Clones a node
DOMNode->hasAttributes --  Checks if node has attributes
DOMNode->hasChildNodes --  Checks if node has children
DOMNode->insertBefore --  Adds new child at the end of the children
DOMNode->isSameNode --  Indicates if two nodes are the same node.
DOMNode->isSupported --  Checks if feature is supported for specified version.
DOMNode->lookupNamespaceURI --  Returns namespace URI of the node based on the prefix.
DOMNode->lookupPrefix --  Returns name space prefix of the node based on namespaceURI.
DOMNode->normalize --  Normalizes the node.
DOMNode->removeChild --  Removes child from list of children
DOMNode->replaceChild --  Replaces a child
DOMNodelist->item --  Retrieves a node specified by index.
DOMText->isWhitespaceInElementContent --  Indicates whether this text node contains whitespace.
DOMText->splitText --  Breaks this node into two nodes at the specified offset.
DOMXPath->query --  Evaluates the XPath expression in the given string
DOMXPath->registerNamespace --  Registers the namespace with the DOMXpath object.

DOMAttr->isId

(no version information, might be only in CVS)

DOMAttr->isId --  Checks if attribute is a defined ID

Description

bool DOMAttr->isId ( void )

This function checks if the attribute is a defined ID.

DOMCharacterData->appendData

(no version information, might be only in CVS)

DOMCharacterData->appendData --  Append the string to the end of the character data of the node.

Description

void DOMCharacterData->appendData ( string data)

Append the string data to the end of the character data of the node.

DOMCharacterData->deleteData

(no version information, might be only in CVS)

DOMCharacterData->deleteData --  Remove a range of characters from the node.

Description

void DOMCharacterData->deleteData ( int offset, int count)

Deletes count characters starting from position offset. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

Throws DOMExcpetion if offset is negative or greater than the number of characters in data, or if count is negative.

DOMCharacterData->insertData

(no version information, might be only in CVS)

DOMCharacterData->insertData --  Insert a string at the specified 16-bit unit offset.

Description

void DOMCharacterData->insertData ( int offset, string data)

Inserts string data at position offset.

Throws DOMExcpetion if offset is negative or greater than the number of 16-bit units in data.

DOMCharacterData->replaceData

(no version information, might be only in CVS)

DOMCharacterData->replaceData --  Replace a substring within the DOMCharacterData node.

Description

void DOMCharacterData->replaceData ( int offset, int count, string data)

Replace count characters starting from position offset with data. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

Throws DOMExcpetion if offset is negative or greater than the number of characters in data, or if count is negative.

DOMCharacterData->substringData

(no version information, might be only in CVS)

DOMCharacterData->substringData --  Extracts a range of data from the node.

Description

string DOMCharacterData->substringData ( int offset, int count)

Returns the specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

Throws DOMExcpetion if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

DOMDocument->createAttribute

(no version information, might be only in CVS)

DOMDocument->createAttribute -- Create new attribute

Description

object DOMDocument->createAttribute ( string name)

This function returns a new instance of class DOMAttr. The name of the attribute is the value of the first parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMDocument->createElement(), DOMNode->appendChild(), DOMDocument->createTextNode(), DOMDocument->createComment() and DOMDocument->createProcessingInstruction().

DOMDocument->createAttributeNS

(no version information, might be only in CVS)

DOMDocument->createAttributeNS --  Create new attribute node with an associated namespace

Description

object DOMDocument->createAttributeNS ( string namespaceURI, string qualifiedName)

This function returns a new instance of class DOMAttr. The tag name and prefix of the attribute is determined by the value of the passed parameter qualifiedName. The URI of the namespace is the value of namespaceURI. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMDocument->createElementNS(), DOMNode->appendChild(), DOMDocument->createElement(), DOMDocument->createTextNode() and DOMDocument->createAttribute().

DOMDocument->createCDATASection

(no version information, might be only in CVS)

DOMDocument->createCDATASection -- Create new cdata node

Description

object DOMDocument->createCDATASection ( string data)

This function returns a new instance of class DOMCDATASection. The content of the cdata is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMNode->appendChild(), DOMDocument->createElement(), DOMDocument->createTextNode(), DOMDocument->createAttribute(), DOMDocument->createProcessingInstruction().

DOMDocument->createComment

(no version information, might be only in CVS)

DOMDocument->createComment -- Create new comment node

Description

object DOMDocument->createComment ( string data)

This function returns a new instance of class DOMComment. The content of the comment is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMNode->appendChild(), DOMDocument->createElement(), DOMDocument->createTextNode(), DOMDocument->createAttribute(), DOMDocument->createProcessingInstruction().

DOMDocument->createDocumentFragment

(no version information, might be only in CVS)

DOMDocument->createDocumentFragment -- Create new document fragment

Description

object DOMDocument->createDocumentFragment ( void )

This function returns a new instance of class DOMAttr. The name of the attribute is the value of the first parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

DOMDocument->createElement

(no version information, might be only in CVS)

DOMDocument->createElement -- Create new element node

Description

object DOMDocument->createElement ( string name [, string value])

This function returns a new instance of class DOMElement. The tag name of the element is the value of the name parameter. Optionally, a value for the new element may also be passed in. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMDocument->createElementNS(), DOMNode->appendChild(), DOMDocument->createTextNode(), DOMDocument->createComment(), DOMDocument->createAttribute(), DOMDocument->createProcessingInstruction().

DOMDocument->createElementNS

(no version information, might be only in CVS)

DOMDocument->createElementNS --  Create new element node with an associated namespace

Description

object DomDocument->createElementNS ( string namespaceURI, string qualifiedName)

This function returns a new instance of class DOMElement. The tag name and prefix of the element is determined by the value of the passed parameter qualifiedName. The URI of the namespace is the value of the passed parameter namespaceURI. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMNode->appendChild(), DOMDocument->createAttributeNS(), DOMDocument->createElement(), DOMDocument->createAttribute() and DOMDocument->createComment().

DOMDocument->createEntityReference

(no version information, might be only in CVS)

DOMDocument->createEntityReference -- Create new entity reference node

Description

object DOMDocument->createEntityReference ( string name)

This function returns a new instance of class DOMEntityReference. The content of the entity reference is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMNode->appendChild(), DOMDocument->createElement(), DOMDocument->createAttribute() and DOMDocument->createComment().

DOMDocument->createProcessingInstruction

(no version information, might be only in CVS)

DOMDocument->createProcessingInstruction -- Creates new PI node

Description

object DOMDocument->createProcessingInstruction ( string target [, string data])

This function returns a new instance of class DOMProcessingInstruction. The content of the pi is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMNode->appendChild(), DOMDocument->createElement(), DOMDocument->createAttribute() and DOMDocument->createComment().

DOMDocument->createTextNode

(no version information, might be only in CVS)

DOMDocument->createTextNode -- Create new text node

Description

object DOMDocument->createTextNode ( string content)

This function returns a new instance of class DOMText. The content of the text is the value of the passed parameter. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().

The return value is FALSE if an error occurred.

See also DOMNode->appendChild(), DOMDocument->createElement(), DOMDocument->createAttribute() and DOMDocument->createComment().

DOMDocument->getElementById

(no version information, might be only in CVS)

DOMDocument->getElementById -- Searches for an element with a certain id.

Description

object DOMDocument->getElementById ( string elementId)

This function is similar to DOMDocument->getElementsByTagName() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID.

DOMDocument->getElementsByTagName

(no version information, might be only in CVS)

DOMDocument->getElementsByTagName -- Searches for all elements with given tag name.

Description

object DOMDocument->getElementsByTagName ( string name)

This function returns a new instance of class DOMNodeList containing the elements with tagnames matching the name parameter. Use "*" for the name to return all elements within the document.

DOMDocument->getElementsByTagNameNS

(no version information, might be only in CVS)

DOMDocument->getElementsByTagNameNS --  Searches for all elements with given tag name in specified namespace.

Description

object DOMDocument->getElementsByTagNameNS ( string namespaceURI, string localName)

This function returns a new instance of class DOMNodeList containing the elements with tagnames matching the localName parameter and in the namespaceURI namespace. Use "*" for the name to return all elements within the document.

DOMDocument->importNode

(no version information, might be only in CVS)

DOMDocument->importNode -- Import node into current document.

Description

object DOMDocument->importNode ( object importedNode [, bool deep])

This function returns a copy of the node to import and associates it with the current document. DOMExcpetion is thrown if node cannot be imported.

DOMDocument->load

(no version information, might be only in CVS)

DOMDocument->load --  Load XML from a file.

Description

mixed DOMDocument->load ( string filename)

The function parses the XML document in the file named filename. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Esempio 1. Creating a Document

<?php
$doc = DOMDocument::load("filename.xml");
print $doc->saveXML();

$doc = new DOMDocument();
$doc->load("filename");
print $doc->saveXML();
?>

See also DOMDocument->loadXML(), DOMDocument->save() and DOMDocument->saveXML().

DOMDocument->loadHTML

(no version information, might be only in CVS)

DOMDocument->loadHTML --  Load HTML from a string.

Description

mixed DOMDocument->loadHTML ( string source)

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Esempio 1. Creating a Document

<?php
$doc = DOMDocument::loadHTML("<html><body>Test<br></body></html>");
print $doc->saveHTML();

$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
print $doc->saveHTML();
?>

See also DOMDocument->loadHTMLFile(), DOMDocument->saveHTML() and DOMDocument->saveHTMLFile().

DOMDocument->loadHTMLFile

(no version information, might be only in CVS)

DOMDocument->loadHTMLFile --  Load HTML from a file.

Description

mixed DOMDocument->loadHTMLFile ( string filename)

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Esempio 1. Creating a Document

<?php
$doc = DOMDocument::loadHTMLFile("filename.html");
print $doc->saveHTML();

$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
print $doc->saveHTML();
?>

See also DOMDocument->loadHTML(), DOMDocument->saveHTML() and DOMDocument->saveHTMLFile().

DOMDocument->loadXML

(no version information, might be only in CVS)

DOMDocument->loadXML --  Load XML from a string.

Description

mixed DOMDocument->loadXML ( string source)

The function parses the XML contained in the string source. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Esempio 1. Creating a Document

<?php
$doc = DOMDocument::loadXML("<root><node/></root>");
print $doc->saveXML();

$doc = new DOMDocument();
$doc->loadXML("<root><node/></root>");
print $doc->saveXML();
?>

See also DOMDocument->load(), DOMDocument->save() and DOMDocument->saveXML().

DOMDocument->normalize

(no version information, might be only in CVS)

DOMDocument->normalize --  Normalizes document.

Description

void DOMDocument->normalize ( void )

Normalizes document.

DOMDocument->relaxNGValidate

(no version information, might be only in CVS)

DOMDocument->relaxNGValidate --  Performs relaxNG validation on the document.

Description

bool DOMDocument->relaxNGValidate ( string filename)

Performs relaxNG validation on the document based on the file defined by filename.

See also DOMDocument->validate(), DOMDocument->schemaValidate(), DOMDocument->schemaValidateSource() and DOMDocument->relaxNGValidateSource().

DOMDocument->relaxNGValidateSource

(no version information, might be only in CVS)

DOMDocument->relaxNGValidateSource --  Performs relaxNG validation on the document.

Description

bool DOMDocument->relaxNGValidateSource ( string source)

Performs relaxNG validation on the document based on the file defined in string source.

See also DOMDocument->validate(), DOMDocument->schemaValidate(), DOMDocument->schemaValidateSource() and DOMDocument->relaxNGValidate().

DOMDocument->save

(no version information, might be only in CVS)

DOMDocument->save --  Dumps the internal XML tree back into a file

Description

int DOMDocument->save ( string filename)

Creates an XML document from the dom representation. The number of bytes written is returned. This function is usually called after building a new dom document from scratch as in the example below.

Esempio 1. Creating a simple HTML document header

<?php
$doc = new DOMDocument("1.0");
$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);
$doc->save("/tmp/test.xml");
?>

See also DOMDocument->load(), DOMDocument->loadXML() and DOMDocument->saveXML().

DOMDocument->saveHTML

(no version information, might be only in CVS)

DOMDocument->saveHTML --  Dumps the internal document into a string using HTML formatting

Description

string DOMDocument->saveHTML ( void )

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Esempio 1. Creating a simple HTML document header

<?php
$doc = new DOMDocument("1.0");
$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 "<PRE>";
echo $doc->saveHTML();
echo "</PRE>";
?>

See also DOMDocument->loadHTML(), DOMDocument->loadHTMLFile() and DOMDocument->saveHTMLFile().

DOMDocument->saveHTMLFile

(no version information, might be only in CVS)

DOMDocument->saveHTMLFile --  Dumps the internal document back into a file using HTML formatting

Description

string DOMDocument->saveHTMLFile ( string filename)

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Esempio 1. Creating a simple HTML document header

<?php
$doc = new DOMDocument("1.0");
$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);
$doc->saveHTMLFile("/tmp/test.hmtl");
?>

See also DOMDocument->loadHTML(), DOMDocument->loadHTMLFile() and DOMDocument->saveHTML().

DOMDocument->saveXML

(no version information, might be only in CVS)

DOMDocument->saveXML -- Dumps the internal XML tree back into a string

Description

string DOMDocument->saveXML ( [object node])

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. The node is used to output only the node rather than the entire document.

Esempio 1. Creating a simple HTML document header

<?php
$doc = new DOMDocument("1.0");
$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 "<PRE>";
echo htmlentities($doc->saveXML());
echo "</PRE>";
?>

See also DOMDocument->load(), DOMDocument->loadXML() and DOMDocument->save().

DOMDocument->schemaValidate

(no version information, might be only in CVS)

DOMDocument->schemaValidate --  Validates a document based on a schema.

Description

bool DOMDocument->schemaValidate ( string filename)

Validates a document based on a schema defined by filename.

See also DOMDocument->schemaValidateSource(), DOMDocument->relaxNGValidate(), DOMDocument->relaxNGValidateSource() and DOMDocument->validate().

DOMDocument->schemaValidateSource

(no version information, might be only in CVS)

DOMDocument->schemaValidateSource --  Validates a document based on a schema.

Description

bool DOMDocument->schemaValidateSource ( string source)

Validates a document based on a schema defined in string source.

See also DOMDocument->schemaValidate(), DOMDocument->relaxNGValidate(), DOMDocument->relaxNGValidateSource() and DOMDocument->validate(),.

DOMDocument->validate

(no version information, might be only in CVS)

DOMDocument->validate --  Validates the document based on its DTD.

Description

bool DOMDocument->validate ( void )

Validates the document based on its DTD.

See also DOMDocument->schemaValidate(), DOMDocument->schemaValidateSource(), DOMDocument->relaxNGValidate(), DOMDocument->relaxNGValidateSource().

DOMDocument->xinclude

(no version information, might be only in CVS)

DOMDocument->xinclude --  Substitutes XIncludes in a DOMDocument Object.

Description

int DOMDocument->xinclude ( void )

Substitutes XIncludes in a DOMDocument Object.

DOMElement->getAttribute

(no version information, might be only in CVS)

DOMElement->getAttribute -- Returns value of attribute

Description

string DOMElement->getAttribute ( string name)

Returns the value of the attribute with name name for the current node. If no attribute with given name is found, an empty string is returned.

See also DOMElement->setAttribute()

DOMElement->getAttributeNode

(no version information, might be only in CVS)

DOMElement->getAttributeNode -- Returns attribute node

Description

object DOMElement->getAttributeNode ( object name)

Returns the attribute node with name name for the current element.

See also DOMElement->setAttribute()

DOMElement->getAttributeNodeNS

(no version information, might be only in CVS)

DOMElement->getAttributeNodeNS --  Returns attribute node

Description

object DOMElement->getAttributeNodeNS ( string namespaceURI, string localName)

Returns the attribute node in namespace namespaceURI with local name localName for the current node.

See also DOMElement->setAttributeNodeNS()

DOMElement->getAttributeNS

(no version information, might be only in CVS)

DOMElement->getAttributeNS -- Returns value of attribute

Description

string DOMElement->getAttributeNS ( string namespaceURI, string localName)

Returns the value of the attribute in namespace namespaceURI with local name localName for the current node. If no attribute with given name is found, an empty string is returned.

See also DOMElement->setAttributeNS()

DOMElement->getElementsByTagName

(no version information, might be only in CVS)

DOMElement->getElementsByTagName -- Gets elements by tagname

Description

object DOMElement->getElementsByTagName ( string name)

This function returns a new instance of class DOMNodeList containing the elements with tagnames matching the name parameter. Use "*" for the name to return all elements within the document.

DOMElement->getElementsByTagNameNS

(no version information, might be only in CVS)

DOMElement->getElementsByTagNameNS -- Get elements by namespaceURI and localName

Description

object DOMElement->getElementsByTagNameNS ( string namespaceURI, string localName)

This function returns a new instance of class DOMNodeList containing the elements in the namespace namespaceURI having localName. Use "*" for the name to return all elements within the document.

DOMElement->hasAttribute

(no version information, might be only in CVS)

DOMElement->hasAttribute -- Checks to see if attribute exists

Description

bool DOMElement->hasAttribute ( string name)

Indicates wether attribute named name exists as a member of the element.

DOMElement->hasAttributeNS

(no version information, might be only in CVS)

DOMElement->hasAttributeNS --  Checks to see if attribute exists

Description

bool DOMElement->hasAttributeNS ( string namespaceURI, string localName)

Indicates wether attribute in namespace namespaceURI named localName exists as a member of the element.

DOMElement->removeAttribute

(no version information, might be only in CVS)

DOMElement->removeAttribute -- Removes attribute

Description

bool DOMElement->removeAttribute ( string name)

Removes attribute named name from the element.

Throws DOMExcpetion if node cannot be modified.

DOMElement->removeAttributeNode

(no version information, might be only in CVS)

DOMElement->removeAttributeNode -- Removes attribute

Description

bool DOMElement->removeAttributeNode ( object oldnode)

Removes attribute oldnode from the element.

Throws DOMExcpetion if node cannot be modified or attribute is not a member of the element node.

DOMElement->removeAttributeNS

(no version information, might be only in CVS)

DOMElement->removeAttributeNS -- Removes attribute

Description

bool DOMElement->removeAttributeNS ( string namespaceURI, string localName)

Removes attribute is namespace namespaceURI named localName from the element.

Throws DOMExcpetion if node cannot be modified.

DOMElement->setAttribute

(no version information, might be only in CVS)

DOMElement->setAttribute -- Adds new attribute

Description

bool DOMElement->setAttribute ( string name, string value)

Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.

Throws DOMExcpetion if node cannot be modified.

Esempio 1. Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

See also DOMElement->getAttribute()

DOMElement->setAttributeNode

(no version information, might be only in CVS)

DOMElement->setAttributeNode -- Adds new attribute node to element

Description

bool DOMElement->setAttributeNode ( object attr)

Adds new attribute node attr to element. Returns old node if attribute replaced.

Throws DOMExcpetion if node cannot be modified.

DOMElement->setAttributeNodeNS

(no version information, might be only in CVS)

DOMElement->setAttributeNodeNS -- Adds new attribute node to element

Description

bool DOMElement->setAttributeNodeNS ( object attr)

Adds new attribute node attr to element. Returns old node if attribute replaced.

Throws DOMExcpetion if node cannot be modified.

DOMElement->setAttributeNS

(no version information, might be only in CVS)

DOMElement->setAttributeNS -- Adds new attribute

Description

void DOMElement->setAttributeNS ( string namespaceURI, string qualifiedName, string value)

Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.

Throws DOMExcpetion if node cannot be modified.

See also DOMElement->getAttributeNS()

DOMImplementation->createDocument

(no version information, might be only in CVS)

DOMImplementation->createDocument --  Creates a DOM Document object of the specified type with its document element.

Description

object DOMImplementation->createDocument ( [string namespaceURI [, string qualifiedName [, object doctype]]])

Creates a DOMDocument object of the specified type with its document element. If namespaceURI, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Throws DOMExcpetion if there is an error with the namespace, as determined by namespaceURI and qualifiedName, or if doctype is not valid.

See also DOMImplementation->createDocumentType().

DOMImplementation->createDocumentType

(no version information, might be only in CVS)

DOMImplementation->createDocumentType --  Creates an empty DOMDocumentType object.

Description

object DOMImplementation->createDocumentType ( [string qualifiedName [, string publicId [, string systemId]]])

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

Throws DOMExcpetion if there is an error with the namespace, as determined by qualifiedName.

See also DOMImplementation->createDocument().

DOMImplementation->hasFeature

(no version information, might be only in CVS)

DOMImplementation->hasFeature --  Test if the DOM implementation implements a specific feature and version.

Description

bool DOMImplementation->hasFeature ( string feature, string version)

Test if the DOM implementation implements a specific feature and version.

DOMNamedNodeMap->getNamedItem

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItem --  Retrieves a node specified by name.

Description

object DOMNamedNodeMap->getNamedItem ( string name)

Retrieves a node specified by name.

DOMNamedNodeMap->getNamedItemNS

(no version information, might be only in CVS)

DOMNamedNodeMap->getNamedItemNS --  Retrieves a node specified by local name and namespace URI.

Description

object DOMNamedNodeMap->getNamedItemNS ( string namespaceURI, string localName)

Retrieves a node specified by localName and namespaceURI.

DOMNamedNodeMap->item

(no version information, might be only in CVS)

DOMNamedNodeMap->item -- Retrieves a node specified by index.

Description

object DOMNamedNodeMap->item ( int index)

Retrieves a node specified by index within the DOMNamedNodeMap object.

DOMNode->appendChild

(no version information, might be only in CVS)

DOMNode->appendChild --  Adds new child at the end of the children

Description

object DOMNode->appendChild ( object newnode)

This functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument->createElement(), DOMDocument->createTextNode() etc. or simply by using any other node.

Throws DOMException if node cannot be appended.

The following example will add a new element node to a fresh document.

Esempio 1. Adding a child

<?php
$doc = new DOMDocument();
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
print $doc->saveXML();
?>

DOMNode->cloneNode

(no version information, might be only in CVS)

DOMNode->cloneNode --  Clones a node

Description

object DOMNode->cloneNode ( [bool deep])

Creates a copy of the node. The paramter deep indicates wether to copy all descedant nodes. This paramter is defaulted to FALSE.

DOMNode->hasAttributes

(no version information, might be only in CVS)

DOMNode->hasAttributes --  Checks if node has attributes

Description

bool DOMNode->hasAttributes ( void )

This function checks if the node has attributes.

DOMNode->hasChildNodes

(no version information, might be only in CVS)

DOMNode->hasChildNodes --  Checks if node has children

Description

bool DOMNode->hasChildNodes ( void )

This function checks if the node has children.

DOMNode->insertBefore

(no version information, might be only in CVS)

DOMNode->insertBefore --  Adds new child at the end of the children

Description

object DOMNode->insertBefore ( object newnode [, object refnode])

This function inserts the new node newnode right before the node refnode. The return value is the inserted node. If you plan to do further modifications on the appended child you must use the returned node. If refnode is not supplied then newnode is appended to the children.

Throws DOMException if node cannot be inserted.

DOMNode->isSameNode

(no version information, might be only in CVS)

DOMNode->isSameNode --  Indicates if two nodes are the same node.

Description

bool DOMNode->isSameNode ( object node)

This functions indicates if two nodes are the same node. The comparison is NOT based on content

DOMNode->isSupported

(no version information, might be only in CVS)

DOMNode->isSupported --  Checks if feature is supported for specified version.

Description

bool DOMNode->isSupported ( string feature, string version)

Checks if feature is supported for specified version.

DOMNode->lookupNamespaceURI

(no version information, might be only in CVS)

DOMNode->lookupNamespaceURI --  Returns namespace URI of the node based on the prefix.

Description

string DOMNode->lookupNamespaceURI ( string prefix)

Returns namespace URI of the node based on the prefix.

DOMNode->lookupPrefix

(no version information, might be only in CVS)

DOMNode->lookupPrefix --  Returns name space prefix of the node based on namespaceURI.

Description

string DOMNode->lookupPrefix ( string namespaceURI)

Returns name space prefix of the node based on namespaceURI.

DOMNode->normalize

(no version information, might be only in CVS)

DOMNode->normalize --  Normalizes the node.

Description

void DOMNode->normalize ( void )

Normalizes the node.

DOMNode->removeChild

(no version information, might be only in CVS)

DOMNode->removeChild --  Removes child from list of children

Description

object DOMNode->removeChild ( object oldchild)

This functions removes a child from a list of children. If the child could be removed the functions returns the old child.

Throws DOMException if node cannot be removed.

DOMNode->replaceChild

(no version information, might be only in CVS)

DOMNode->replaceChild --  Replaces a child

Description

object DOMNode->replaceChild ( object oldnode, object newnode)

This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time.If the replacement succeeds the old node is returned.

Throws DOMException if node cannot be replaced.

DOMNodelist->item

(no version information, might be only in CVS)

DOMNodelist->item --  Retrieves a node specified by index.

Description

object DOMNodelist->item ( int index)

Retrieves a node specified by index within the DOMNodelist object.

DOMText->isWhitespaceInElementContent

(no version information, might be only in CVS)

DOMText->isWhitespaceInElementContent --  Indicates whether this text node contains whitespace.

Description

bool DOMText->isWhitespaceInElementContent ( void )

Indicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.

DOMText->splitText

(no version information, might be only in CVS)

DOMText->splitText --  Breaks this node into two nodes at the specified offset.

Description

object DOMText->splitText ( int offset)

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings. After being split, this node will contain all the content up to the offset. A new node of the same type, which contains all the content at and after the offset, is returned. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

DOMXPath->query

(no version information, might be only in CVS)

DOMXPath->query --  Evaluates the XPath expression in the given string

Description

object DOMXPath->query ( string expression [, object contextnode])

Returns a DOMNodelist containing all nodes matching expression. Any expression which do not return nodes will return an empty DOMNodelist.

The optional contextnode can be specified for doing relative XPath queries.

DOMXPath->registerNamespace

(no version information, might be only in CVS)

DOMXPath->registerNamespace --  Registers the namespace with the DOMXpath object.

Description

bool DOMXPath->registerNamespace ( string prefix, string namespaceURI)

Registers the namespaceURI and prefix with the DOMXpath object.

XXV. Funzioni DOM XML

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.

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


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

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.

Nota per gli utenti Win32: Per potere abilitare questa estensione sui sistemi Windows, occorre copiare file addizionali dalla directory DLL della dustribuzione PHP/Win32 nella directory SYSTEM32 della macchina Windows (ad esempio: C\WINNT\SYSTEM32 oppure c:\WINDOWS\SYSTEM32). Per le versioni di PHP <= 4.2.0 copiare il file libxml2.dll, per le versioni >= 4.3.0 copiare il file >iconv.dll.


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'>
  &amp;sp;
  <!-- comment -->
  <informaltable ID='findme' language='&amp;sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

Sommario
DomAttribute->name --  Restituisce il nome di un attributo
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 valore di un attributo
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 di un elemento
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
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
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

bool DomAttribute->name ( void )

La funzione restituisce il nome di un attributo.

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

bool DomAttribute->value ( void )

Questa funzione restituisce il valore di un attributo.

Vedere anche domattribute_name().

DomDocument->add_root

(no version information, might be only in CVS)

DomDocument->add_root --  Aggiunge un nodo radice [deprecated]

Descrizione

resource 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

object 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

string 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

object 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

object 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

object 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

object 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

string 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

object 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

object 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

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

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

object 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
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->html_dump_mem());
echo "</PRE>";
?>

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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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.

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.

L'esempio seguente visualizzerà '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.

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

DomElement->get_attribute_node

(no version information, might be only in CVS)

DomElement->get_attribute_node --  Restituisce il valore di un attributo

Descrizione

object DomElement->get_attribute_node ( object attributo)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

bool 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

bool 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 di un elemento

Descrizione

string DomElement->tagname ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

object DomNode->append_child ( object nuovo_nodo)

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.

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)

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)

domxml_open_file -- Crea un oggetto DOM da un file XML

Descrizione

object domxml_open_file ( string nome_file)

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.

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)

domxml_open_mem -- Crea un oggetto DOM da un documento XML

Descrizione

object domxml_open_mem ( string str)

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.

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)

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)

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)

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)

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)

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

xpath_eval_expression

(PHP 4 >= 4.0.4)

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)

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)

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

xptr_eval

(PHP 4 >= 4.0.4)

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)

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.

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

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

ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by '/manual/' you can simply use docref_root=/manual/. Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html. It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash '/'. But see the second example above which does not have nor need it.

Nota: This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

See docref_root.

Nota: The value of docref_ext must begin with a dot '.'.

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog().

warn_plus_overloading boolean

If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).


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 --  Generates a backtrace
debug_print_backtrace --  Prints a 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
set_error_handler --  Configura una funzione di gestione dell'errore 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 --  Generates a backtrace

Description

array debug_backtrace ( void )

debug_backtrace() generates a PHP backtrace and returns this information as an associative array. The possible returned elements are listed in the following table:

Tabella 1. Possible returned elements from debug_backtrace()

NameTypeDescription
functionstring The current function name. See also __FUNCTION__.
lineinteger The current line number. See also __LINE__.
filestring The current file name. See also __FILE__.
classstring The current class name. See also __CLASS__
typestring The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
argsarray If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

The following is a simple example.

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

Results when executing /tmp/b.php:

Hi: friend
array(2) {
  [0]=>
  array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
  }
  [1]=>
  array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] => 
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

See also trigger_error() and debug_print_backtrace().

debug_print_backtrace

(PHP 5)

debug_print_backtrace --  Prints a backtrace

Description

void debug_print_backtrace ( void )

debug_print_backtrace() prints a PHP backtrace.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

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

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

XXVIII. 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 non è disponibile su piattaforme Windows.


Requisiti

This extension uses the functions of the FAM library, devoloped 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)

fam_cancel_monitor -- Terminate monitoring

Description

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

fam_close -- Close FAM connection

Description

void fam_close ( resource fam)

fam_close() closes a connection to the FAM service previously opened using fam_open().

fam_monitor_collection

(PHP 5)

fam_monitor_collection -- Monitor a collection of files in a directory for changes

Description

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)

fam_monitor_directory -- Monitor a directory for changes

Description

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)

fam_monitor_file -- Monitor a regular file for changes

Description

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)

fam_next_event -- Get next pending FAM event

Description

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)

fam_open -- Open connection to FAM daemon

Description

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)

fam_pending -- Check for pending FAM events

Description

bool fam_pending ( resource fam)

fam_pending() returns TRUE if events are available to be fetched using fam_next_event().

See also fam_next_event().

fam_resume_monitor

(PHP 5)

fam_resume_monitor -- Resume suspended monitoring

Description

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)

fam_suspend_monitor -- Temporarily suspend monitoring

Description

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

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

Description

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

Description

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

Description

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.

XXX. Funzioni filePro

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

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.

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.

XXXI. 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 XLII, 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 L.

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 del 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
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
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 un nome di file unico
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 si separazione nei percorsi. 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 iniziare mode con 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
?>

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. 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 si abilita il safe mode, il PHP verifica se i file o le directory su cui si sta operando hanno il medesimo UID (proprietario) dello script. In aggiunta, non si può impostare il SUID, SGID e lo 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
if (!copy($file, $file.'.bak')) {
    echo "Copia di $file non riuscita ...<br>\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.

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.

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

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 timeoute del socket); altrimenti restituisce FALSE.

Avvertimento

La funzione feof() restituirà TRUE soltanto se la connessione aperta da fsockopen() è chiusa. Ciò può portare in timeout lo lo script. Un trucco per evitare ciò consiste nell'utilizzare la funzione stream_set_timeout(), in modo da costringere feof() a restituire FALSE in caso di timeout.

Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen() o 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 se ha successo, FALSE altrimenti.

Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen() o 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).

Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen() o 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]])

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. Il delimitatore di campo è una virgola, a meno che non venga specificato un altro delimitatore usando il terzo parametro opzionale, mentre per il quarto parametro opzionale, enclosure, il default sono i doppi apici. Entrambi i parametri, delimitatore ed enclosure, hanno la dimensione di un carattere. Se si forniscono stringhe di più di un carattere, verrà considerato solo il primo.

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, ",")) {
    $num = count($data);
    echo "<p> $num campi sulla linea $row: <br >\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br>\n";
    }
}
fclose($handle);
?>

Vedere anche explode(), file() e pack().

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.

Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen(), o 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, PHP4B3.

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 L 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]])

Simile alla funzione file(), tranne che file_get_contents() restituisce il file in una stringa. Se si verifica un errore file_get_contents() restituirà FALSE

La funzione file_get_contents() è la via preferenziale per leggere il contenuto di un file in una stringa. La funzione utilizza tecniche di mappatura della memoria, se sono supportate dal sistema operativo, per ottimizzare le prestazioni.

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 L per avere la lista dei protocolli URL supportati.

Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0.

Vedere anche: fgets(), file(), fread(), include() e readfile().

file_put_contents

(PHP 5)

file_put_contents -- Write a string to a file

Description

int file_put_contents ( string filename, string data [, int flags [, resource context]])

Identical to calling fopen(), fwrite(), and fclose() successively. The function returns the amount of bytes that were written to the file.

flags can take FILE_USE_INCLUDE_PATH and/or FILE_APPEND, however the FILE_USE_INCLUDE_PATH option should be used with caution.

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 L per avere la lista dei protocolli URL supportati.

See also fopen(), fwrite(), fclose(), and file_get_contents().

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 L 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 al contesto è stato aggiunto nel PHP 5.0.0

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 L 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 L 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 L 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 L 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 L 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 L 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 del file

Descrizione

int fileperms ( string filename)

Restituisce i permessi sul 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 L per la lista di quali wrappers supportano le funzioni della famiglia stat().

Vedere 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 L 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 L 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à).

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)

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 [, int 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 safe mode, 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 L. 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 CVIII, Stream Functions.

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.

Per motivi di portabilità è fortemente raccomandato l'uso del flag 'b' quando si aprono dei file con fopen().

Inoltre, sempre per la portabilità, è anche fortemente raccomandato di aggiornare il codice che utilizza o che confida nel modalità 't' in modo da utilizzare il corretto terminatore di linea.

A partire dal PHP 4.3.2, per tutte le piattaforme che distinguono tra tra testo e binario, la modalità di default è la binaria. Se si hanno problemi negli script dopo l'aggiornamneto, tentare l'utilizzo del flag 't' per tamponare i problemi fino a quando non si sono resi gli script più portabili come descritto in precedenza.

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

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 L, 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.

Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen() o fsockopen(). You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file. Il file viene chiuso quando fpassthru() viene conclusa la sua lettura (lasciando handle 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()

fputs

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 proc_open(), 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 = "";
do {
    $data = fread($handle, 8192);
    if (strlen($data) == 0) {
        break;
    }
    $contents .= $data;
} while (true);
fclose($handle);
?>

Nota: L'esempio precedente ottiene migliori performance rispetto al tradizionale approccio tramite while(!feof()), poichè si risparmia l'overhead della chiamata per la funzione di iterazione.

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 [, string var1])

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. 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, viene ottenuta aggiungento 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://".

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

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

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.

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

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

is_uploaded_file() is available only in versions of PHP 3 after PHP 3.0.16, and in versions of PHP 4 after 4.0.2. If you are stuck using an earlier version, you can use the following function to help protect yourself:

Nota: The following example will not work in versions of PHP 4 after 4.0.2. It depends on internal functionality of PHP which changed after that version.

<?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 "Possible file upload attack: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

See also move_uploaded_file(), and the section Handling file uploads for a simple usage example.

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 L per la lista di quali wrappers supportano le funzioni della famiglia stat().

Vedere anche is_readable(), file_exists() e fwrite().

is_writeable

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.

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 campo st_dev 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

?>

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 L 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 [, 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().

<?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 L per avere l'elenco dei wrapper supportati da mkdir().

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 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 safe mode 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 safe mode 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
        )

)

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo -- Restituisce informazioni su un percorso di file

Descrizione

array pathinfo ( string path)

pathinfo() restituisce un vettore associativo contenente informazioni riguardo path. Nel vettore vegono riportati i seguenti elementi: dirname, basename e extension.

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

?>

produrra:

/www/htdocs
index.html
html

Nota: Per maggiori dettagli sul recupero del percorso corrente, leggere la sezione variabili predefinite riservate.

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

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 è abilitato il safe mode si possono eseguire solo gli eseguibili presenti nella directoy safe_mode_exec_dir. Per ragioni pratiche, attualmente, non è consentito avere .. nel percorso dell'eseguibile.

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

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

?>

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

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

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

Vedere anche link() per creare hard link, e readlink() con linkinfo().

tempnam

(PHP 3, PHP 4 , PHP 5)

tempnam -- Crea un nome di file unico

Descrizione

string tempnam ( string dir, string prefix)

Crea un nome di file temporaneo univoco nella directory specificata. Se la directory non esiste, tempnam() può generare il nome file nella directory temporanea del sistema.

Prima di PHP 4.0.6, il comportamento della funzione tempnam() dipendeva dal sistema. Su Windows la variabile d'ambiente TMP scavalcherà il parametro dir, su Linux la variabile d'ambiente TMPDIR ha la precedenza, mentre SVR4 userà sempre il tuo parametro dir se la directory cui punta esiste. Consulta la documentazione del tuo sistema sulla funzione tempnam(3) se non sei sicuro.

Nota: Se il PHP non è in grado di creare il file nella directory dir la funzione passa alla directory di default del sistema.

Restituisce il nuovo filename temporaneo, o la stringa NULL se fallisce.

Esempio 1. tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
  	fclose($handle);

// do here something

unlink($tmpfname);
?>

Nota: Il comportamento di questa funzione è cambiata in 4.0.3. Il file temporaneo è anche creato per evitare una condizione di rincorsa dove il file può apparire nel filesystem fra il momento che la stringa viene generato e prima che lo script si occupi di crearlo. Note, that you need to remove the file in case you need it no more, it is not done automatically.

Vedere anche tmpfile() e 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 il modalità di scrittura, 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");
fclose($temp); // this removes the file
?>

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 al valore dato da time. Se non viene passata l'opzione time usa l'ora attuale. Questo 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 todays date and 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 L 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.

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

fdf_get_flags ( void )

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

XXXIII. Funzioni FriBiDi

Sommario
fribidi_log2vis -- Converte una stringa logica in una visuale

fribidi_log2vis

(PHP 4 >= 4.0.4)

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.

XXXIV. 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 in un file aperto
ftp_fput -- Carica da un file aperto al server FTP
ftp_get_option -- Richiama vari comportamenti runtime dello stream FTP attualmente in uso
ftp_get -- Scarica un file dal server FTP
ftp_login -- Loggarsi in una connessione FTP
ftp_mdtm -- Restituisce la data di ultima modifica di un dato file
ftp_mkdir -- Crea una directory
ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)
ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)
ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)
ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)
ftp_nb_put -- Stores a file on the FTP server (non-blocking)
ftp_nlist -- Restituisce l'elenco dei file in una data directory
ftp_pasv -- Abilita o disabilita la modalità passiva
ftp_put -- Carica un file sul server FTP
ftp_pwd -- Restituisce il nome della directory corrente
ftp_quit -- Chiude una connessione FTP
ftp_raw -- Sends an arbitrary command to an FTP server
ftp_rawlist -- Restituisce l'elenco dettagliato dei file in una data directory
ftp_rename -- Rinomina un file sul server FTP
ftp_rmdir -- Elimina una directory
ftp_set_option -- Imposta alcune opzioni runtime generiche dell'FTP
ftp_site -- Invia un comando SITE al server
ftp_size -- Restituisce la dimensione di un dato file
ftp_ssl_connect -- Opens an Secure SSL-FTP connection
ftp_systype -- Restituisce l'identificatore del tipo di sistema del server FTP remoto

ftp_alloc

(PHP 5)

ftp_alloc -- Allocates space for a file to be uploaded.

Description

bool ftp_alloc ( resource ftp_stream, int filesize [, string &result])

Sends an ALLO command to the remote FTP server to allocate filesize bytes of space. Returns TRUE on success, or FALSE on failure.

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.

A textual representation of the servers response will be returned by reference in result is a variable is provided.

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

?>

See also: ftp_put(), and 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

Description

string ftp_chmod ( resource ftp_stream, int mode, string filename)

Sets the permissions on the remote file specified by filename to mode given as an octal value.

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)) {
 echo "$file chmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

Returns the new file permissions on success or FALSE on error.

See also 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 in un file aperto

Descrizione

int ftp_fget ( int ftp_stream, int fp, string remote_file, int mode)

ftp_fget() recupera remote_file dal server FTP, e lo scrive da un dato puntatore del file, fp. Il parametro mode che specifica il tipo di trasferimento deve essere FTP_ASCII oppure FTP_BINARY.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

ftp_fput

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_fput -- Carica da un file aperto al server FTP

Descrizione

int ftp_fput ( int ftp_stream, string remote_file, int fp, int mode)

ftp_fput() carica i dati dal puntatore del file fp fino alla fine del file stesso. I risultati vengono salvati in remote_file sul server FTP. Il parametro mode che spedifica il tipo di trasferimento deve essere FTP_ASCII oppure FTP_BINARY.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_get_option -- Richiama vari comportamenti runtime dello stream FTP attualmente in uso

Descrizione

mixed ftp_get_option ( resource stream, int opzione)

Nota: Questa funzione è disponibile solo nella versione CVS.

Restituisce il valore in caso di successo o FALSE se la data opzione non è supportata. Nel secondo caso viene inoltre generato un messaggio di avviso.

Questa funzione restituisce il valore corrispondente all' opzione richiesta, prendendolo dallo stream specificato. Al momento sono supportate le seguenti opzioni:

Tabella 1. Opzioni runtime FTP supportate

FTP_TIMEOUT_SECRestituisce l'attuale timeout usato per le operazioni relative alla rete.

Esempio 1. Esempio di ftp_get_option()

// Ottiene il timeout del dato stream FTP
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);

ftp_get

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_get -- Scarica un file dal server FTP

Descrizione

int ftp_get ( int ftp_stream, string file_in_locale, string file_remoto, int mode)

ftp_get() recupera file_remoto dal server FTP, e lo salva come file_in_locale localmente. La modalità di trasferimento indicata dal parametro mode deve essere specificata come FTP_ASCII oppure FTP_BINARY.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

Vedere anche ftp_fget().

ftp_login

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_login -- Loggarsi in una connessione FTP

Descrizione

int ftp_login ( int ftp_stream, string nome_utente, string password)

Esegue il login in un dato stream FTP.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

ftp_mdtm

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_mdtm -- Restituisce la data di ultima modifica di un dato file

Descrizione

int ftp_mdtm ( int ftp_stream, string remote_file)

ftp_mdtm() Controlla la data di ultima modifica di un file, e la restituisce in formato UNIX timestamp. Se si verifica un errore, oppure il file non esiste, viene restituito -1. Da notare che non tutti i server supportano questa caratteristica.

Restituisce uno UNIX timestamp se a buon fine, oppure -1 in caso di errore.

Nota: ftp_mdtm() non funziona con le cartelle.

ftp_mkdir

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_mkdir -- Crea una directory

Descrizione

string ftp_mkdir ( int ftp_stream, string directory)

Crea la directory specificata.

Restituisce il nome della directory appena creata se a buon fine, FALSE in caso di errore.

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)

Description

int ftp_nb_continue ( resource ftp_stream)

Continues retrieving/sending a file non-blocking.

Esempio 1. ftp_nb_continue() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

ftp_nb_fget

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Description

int ftp_nb_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos])

ftp_nb_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, handle. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Esempio 1. ftp_nb_fget() example

<?php

// open some file for reading
$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);

// Initate the download
$ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

// close filepointer
fclose($fp);
?>

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

See also ftp_nb_get(), ftp_nb_continue(), ftp_fget(), and ftp_get().

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)

Description

int ftp_nb_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos])

ftp_nb_fput() uploads the data from the file pointer handle until it reaches the end of the file. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Esempio 1. ftp_nb_fput() example

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

// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue upload...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

fclose($fp);
?>

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

See also ftp_nb_put(), ftp_nb_continue(), ftp_put() and ftp_fput().

ftp_nb_get

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Description

int ftp_nb_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_nb_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

Esempio 1. ftp_nb_get() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Esempio 2. Resuming a download with ftp_nb_get()

<?php

// Initate 
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY, 
                      filesize("test"));
// OR: $ret = ftp_nb_get($my_connection, "test", "README", 
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Esempio 3. Resuming a download at position 100 to a new file with ftp_nb_get()

<?php

// Disable Autoseek
ftp_set_option($my_connection, FTP_AUTOSEEK, false);

// Initiate
$ret = ftp_nb_get($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   /* ... */
   
   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
?>

In the example above, "newfile" is 100 bytes smaller than "README" on the FTP server because we started reading at offset 100. If we have not have disabled FTP_AUTOSEEK, the first 100 bytes of "newfile" will be '\0'.

See also ftp_nb_fget(), ftp_nb_continue(), ftp_get(), and ftp_fget().

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_put -- Stores a file on the FTP server (non-blocking)

Description

int ftp_nb_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

ftp_nb_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_put() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.

Esempio 1. ftp_nb_put() example

<?php

// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

Esempio 2. Resuming an upload with ftp_nb_put()

<?php

// Initiate
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", 
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_nb_put($my_connection, "test.remote", "test.local", 
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

See also ftp_nb_fput(), ftp_nb_continue(), ftp_put(), and ftp_fput().

ftp_nlist

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_nlist -- Restituisce l'elenco dei file in una data directory

Descrizione

array ftp_nlist ( int ftp_stream, string directory)

Restituisce una array di nomi di file se a buon fine, FALSE in caso di errore.

ftp_pasv

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_pasv -- Abilita o disabilita la modalità passiva

Descrizione

int ftp_pasv ( int ftp_stream, int pasv)

ftp_pasv()Abilita la modalità passiva se il parametro pasv risulta TRUE (disabilita la modalità passiva se pasv risulta FALSE.) In modalità passiva la connessione viene iniziata dal client, piuttosto che dal server.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

ftp_put

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_put -- Carica un file sul server FTP

Descrizione

int ftp_put ( int ftp_stream, string remote_file, string local_file, int mode)

ftp_put() salva local_file sul server FTP, come remote_file. Il parametro mode che spedifica il tipo di trasferimento deve essere FTP_ASCII oppure FTP_BINARY.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

Esempio 1. Esempio di ftp_put()

$upload = ftp_put ($conn_id, $destination_file, $source_file, FTP_ASCII);

ftp_pwd

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_pwd -- Restituisce il nome della directory corrente

Descrizione

string ftp_pwd ( int ftp_stream)

Restituisce il nome della directory corrente, oppure FALSE in caso di errore.

ftp_quit

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_quit -- Chiude una connessione FTP

Descrizione

int ftp_quit ( int ftp_stream)

ftp_quit() chiude ftp_stream.

ftp_raw

(PHP 5)

ftp_raw -- Sends an arbitrary command to an FTP server

Description

array ftp_raw ( resource ftp_stream, string command)

Sends an arbitrary command to the FTP server. Returns the server's response as an array of strings. No parsing is performed on the response string, nor does ftp_raw() determine if the command succeeded.

Esempio 1. Using ftp_raw() to login to an FTP server manually.

<?php
$fp = ftp_connect("ftp.example.com");

/* This is the same as: 
   ftp_login($fp, "joeblow", "secret"); */
ftp_raw($fp, "USER joeblow");
ftp_raw($fp, "PASS secret");
?>

See Also: ftp_exec()

ftp_rawlist

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_rawlist -- Restituisce l'elenco dettagliato dei file in una data directory

Descrizione

array ftp_rawlist ( int ftp_stream, string directory)

ftp_rawlist() esegue il comando FTP LIST e restituisce il risultato come un array. Ogni elemento dell'array corrisponde ad una linea di testo. L'output non viene in alcun modo interpretato. L'identificatore del tipo di sistema restituito da ftp_systype() può essere usato per determinare l'interpretazione del risultato.

ftp_rename

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_rename -- Rinomina un file sul server FTP

Descrizione

boolean ftp_rename ( resource ftp_stream, string da, string a)

ftp_rename() rinomina il file o la cartella che ha come nome corrente da con il nome a, sul flusso FTP ftp_stream.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

ftp_rmdir

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_rmdir -- Elimina una directory

Descrizione

int ftp_rmdir ( int ftp_stream, string directory)

Elimina la directory specificata.

Restituisce TRUE in caso di successo, FALSE in caso di errore.

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_set_option -- Imposta alcune opzioni runtime generiche dell'FTP

Descrizione

bool ftp_set_option ( resource stream, int opzione, mixed valore)

Nota: Questa funzione è disponibile solo nella versione CVS.

Restituisce TRUE se l'opzione può essere impostata; FALSE altrimenti. Un messaggio di avviso verrà generato se opzione non è supportata o se valore non corrisponde al valore atteso per quella data opzione.

Questa funzione controlla diverse opzioni runtime per lo stream FTP specificato. Il parametro valore dipende da quale parametro opzione si sceglie di alterare. Attualmente, sono supportate le seguenti opzioni:

Tabella 1. Opzioni runtime FTP supportate

FTP_TIMEOUT_SECCambia il timeout in secondi usato per tutte le funzioni orientate alla rete. Il parametro valore deve essere di tipo int e deve essere maggiore di 0. Il valore predefinito di timeout è 90 secondi.

Esempio 1. Esempio di ftp_set_option()

// Imposta il timeout di rete a 10 secondi
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);

ftp_site

(PHP 3>= 3.0.15, PHP 4 , PHP 5)

ftp_site -- Invia un comando SITE al server

Descrizione

int ftp_site ( int ftp_stream, string cmd)

ftp_site() Invia il comando specificato da cmd al server FTP. I comandi SITE non sono standardizzati e cambiano da server a server. Sono utili per gestire i permessi di accesso e di appartenenza ai gruppi dei file.

Restituisce TRUE se a buon fine, FALSE in caso di errore.

ftp_size

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_size -- Restituisce la dimensione di un dato file

Descrizione

int ftp_size ( int ftp_stream, string remote_file)

ftp_size() restituisce la dimensione di un file. Se si verifica un errore, oppure se il file non esiste, viene restituito -1. Non tutti i server supportano questa caratteristica.

Restituisce la dimensione del file se a buon fine, oppure -1 in caso di errore.

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5)

ftp_ssl_connect -- Opens an Secure SSL-FTP connection

Description

resource ftp_ssl_connect ( string host [, int port [, int timeout]])

Returns a SSL-FTP stream on success or FALSE on error.

ftp_ssl_connect() opens a SSL-FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it's omitted or set to zero then the default FTP port 21 will be used.

The timeout parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Esempio 1. ftp_ssl_connect() example

<?php

// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

Why this function may not exist: ftp_ssl_connect() is only available if OpenSSL support is enabled into your version of PHP. If it's undefined and you've compiled FTP support then this is why. For Windows you must compile your own PHP binaries to support this function.

See also ftp_connect().

ftp_systype

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

ftp_systype -- Restituisce l'identificatore del tipo di sistema del server FTP remoto

Descrizione

string ftp_systype ( int ftp_stream)

Restituisce il tipo di sistema remoto, oppure FALSE in caso di errore.

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

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

See also: is_callable(), and call_user_func_array()

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) 
{
    for ($f=0; $f < count($farr); $f++) {
        echo $farr[$f]($var1, $var2) . "\n";
    }
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . " , ".crc32(b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

and when you run the code above, the output will be:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

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.

If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.

<?php
function foo() 
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br />\n";
     if ($numargs >= 2) {
     echo "Second argument is: " . func_get_arg(1) . "<br />\n";
     }
} 

foo (1, 2, 3);
?>

func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

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 the corresponding member of the current user-defined function's argument list. func_get_args() will generate a warning if called from outside of a function definition.

<?php
function foo() 
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
} 

foo(1, 2, 3);
?>

func_get_args() may be used in conjunction with func_num_args() and func_get_arg() to allow user-defined functions to accept variable-length argument lists.

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.

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

Registers the function named by function to be executed when script processing is complete.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

The registered shutdown functions are called after the request has been completed (including sending any output buffers), so it is not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents().

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.

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

void register_tick_function ( callback function [, mixed arg])

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

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.

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

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy gnu_gettext.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). Starting with PHP 4.2.3 the name changed to libintl-1.dll, this requires also iconv.dll to be copied.


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

Description

string textdomain ( string text_domain)

This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with NULL as parameter to get the current setting without changing it.

XXXVII. Funzioni GMP

Queste funzioni permettono di lavorare con numeri interi di lunghezza arbitraria usando le librerie GNU MP. In pratica per poter usufruire di queste funzioni, bisogna installare il supporto GMP usando la seguente opzione --with-gmp.

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.

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.

Esempio 1. Funzione fattoriale usando GMP

<?php
function fact ($x) {
    if ($x <= 1) 
        return 1;
    else
        return gmp_mul ($x, fact ($x-1));
}

print gmp_strval (fact (1000)) . "\n";
?>

Questo calcolerà il fattoriale di 1000 (numero abbastanza grande) molto velocemente.

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

(no version information, might be only in CVS)

gmp_sqrtrm -- Radice quadrata con resto

Descrizione

array gmp_sqrtrm ( 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.

XXXVIII. Funzioni HTTP

Queste funzioni permettono di modificare l'output inviato verso un browser attraverso manipolazioni a livello di protocollo HTTP.

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(29) "X-Powered-By: PHP/5.0.0"
  [1]=>
  string(19) "Set-Cookie: foo=bar"
  [2]=>
  string(18) "X-Sample-Test: foo"
  [3]=>
  string(24) "Content-type: text/plain"
}

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://www.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 [, int 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.

XXXIX. 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: An unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.

  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.

  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.

  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.


Requisiti

This extension needs a Hyperwave server downloadable from http://www.hyperwave.com/.


Installazione

To enable Hyperwave support compile PHP --with-hyperwave.


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with

RewriteEngine on

You will need scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Hyperwave configuration options

NameDefaultChangeable
hyperwave.allow_persistent"0"PHP_INI_SYSTEM
hyperwave.default_port"418"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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 )

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 )

hw_changeobject --  Changes attributes of an object (obsolete)

Description

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

hw_Children -- object ids of children

Description

array hw_children ( int connection, int objectID)

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_ChildrenObj

(PHP 3>= 3.0.3, PHP 4 )

hw_ChildrenObj -- object records of children

Description

array hw_childrenobj ( int connection, int objectID)

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Close

(PHP 3>= 3.0.3, PHP 4 )

hw_Close -- closes the Hyperwave connection

Description

int hw_close ( int connection)

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

hw_Connect

(PHP 3>= 3.0.3, PHP 4 )

hw_Connect -- opens a connection

Description

int hw_connect ( string host, int port, string username, string password)

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

hw_connection_info

(PHP 3>= 3.0.3, PHP 4 )

hw_connection_info --  Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_cp

(PHP 3>= 3.0.3, PHP 4 )

hw_cp -- Copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination_id)

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

hw_Deleteobject

(PHP 3>= 3.0.3, PHP 4 )

hw_Deleteobject -- deletes object

Description

int hw_deleteobject ( int connection, int object_to_delete)

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

hw_DocByAnchor

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchor -- object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID)

Returns an th object id of the document to which anchorID belongs.

hw_DocByAnchorObj

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchorObj -- object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID)

Returns an th object record of the document to which anchorID belongs.

hw_Document_Attributes

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Attributes -- object record of hw_document

Description

string hw_document_attributes ( int hw_document)

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

hw_Document_BodyTag

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_BodyTag -- body tag of hw_document

Description

string hw_document_bodytag ( int hw_document)

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

hw_Document_Content

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Content -- returns content of hw_document

Description

string hw_document_content ( int hw_document)

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().

hw_Document_SetContent

(PHP 4 )

hw_Document_SetContent -- sets/replaces content of hw_document

Description

string hw_document_setcontent ( int hw_document, string content)

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

See also hw_document_attributes(), hw_document_size(), and hw_document_content().

hw_Document_Size

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Size -- size of hw_document

Description

int hw_document_size ( int hw_document)

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

hw_dummy

(PHP 3>= 3.0.3, PHP 4 )

hw_dummy --  Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_EditText

(PHP 3>= 3.0.3, PHP 4 )

hw_EditText -- retrieve text document

Description

int hw_edittext ( int connection, int hw_document)

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), and hw_gettext().

hw_Error

(PHP 3>= 3.0.3, PHP 4 )

hw_Error -- error number

Description

int hw_error ( int connection)

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

hw_ErrorMsg

(PHP 3>= 3.0.3, PHP 4 )

hw_ErrorMsg -- returns error message

Description

string hw_errormsg ( int connection)

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

hw_Free_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Free_Document -- frees hw_document

Description

int hw_free_document ( int hw_document)

Frees the memory occupied by the Hyperwave document.

hw_GetAnchors

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchors -- object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID)

Returns an array of object ids with anchors of the document with object ID objectID.

hw_GetAnchorsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchorsObj -- object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID)

Returns an array of object records with anchors of the document with object ID objectID.

hw_GetAndLock

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAndLock -- return 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 )

hw_GetChildColl -- object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID)

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

hw_GetChildCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildCollObj -- object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID)

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

hw_GetChildDocColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocColl -- object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID)

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

hw_GetChildDocCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocCollObj -- object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID)

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

hw_GetObject

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObject -- object record

Description

array hw_getobject ( int connection, 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 )

hw_GetObjectByQuery -- search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

hw_GetObjectByQueryColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryColl -- search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

hw_GetObjectByQueryCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryCollObj -- search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

hw_GetObjectByQueryObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryObj -- search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

hw_GetParents

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParents -- object ids of parents

Description

array hw_getparents ( int connection, int objectID)

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetParentsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParentsObj -- object records of parents

Description

array hw_getparentsobj ( int connection, int objectID)

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

hw_getrellink

(PHP 3>= 3.0.3, PHP 4 )

hw_getrellink --  Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_GetRemote

(PHP 3>= 3.0.3, PHP 4 )

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID)

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources 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 )

hw_getremotechildren -- Gets children of remote document

Description

int hw_getremotechildren ( int connection, string object_record)

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How 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 )

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID)

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

hw_GetText

(PHP 3>= 3.0.3, PHP 4 )

hw_GetText -- retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix])

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document 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 )

hw_getusername -- name of currently logged in user

Description

string hw_getusername ( int connection)

Returns the username of the connection.

hw_Identify

(PHP 3>= 3.0.3, PHP 4 )

hw_Identify -- identifies as user

Description

int hw_identify ( string username, string password)

Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

See also hw_connect().

hw_InCollections

(PHP 3>= 3.0.3, PHP 4 )

hw_InCollections -- check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections)

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

hw_Info

(PHP 3>= 3.0.3, PHP 4 )

hw_Info -- info about connection

Description

string hw_info ( int connection)

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InsColl

(PHP 3>= 3.0.3, PHP 4 )

hw_InsColl -- insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array)

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

hw_InsDoc

(PHP 3>= 3.0.3, PHP 4 )

hw_InsDoc -- insert document

Description

int hw_insdoc ( int connection, int parentID, string object_record, string text)

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors --  Inserts only anchors into text

Description

string hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_InsertDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertDocument -- upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document)

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

hw_InsertObject

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertObject -- inserts an object record

Description

int hw_insertobject ( int connection, string object_rec, string parameter)

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no 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 )

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server_id, int object_id)

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

hw_Modifyobject

(PHP 3>= 3.0.7, PHP 4 )

hw_Modifyobject -- modifies object record

Description

int hw_modifyobject ( int connection, int object_to_change, array remove, array add, int mode)

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means 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 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 )

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 )

hw_New_Document -- create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size)

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().

hw_objrec2array

(PHP 3>= 3.0.3, PHP 4 )

hw_objrec2array -- Convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format])

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.

See also hw_array2objrec().

hw_Output_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Output_Document -- prints hw_document

Description

int hw_output_document ( int hw_document)

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

hw_pConnect

(PHP 3>= 3.0.3, PHP 4 )

hw_pConnect -- make a persistent database connection

Description

int hw_pconnect ( string host, int port, string username, string password)

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

hw_PipeDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_PipeDocument -- retrieve any document

Description

int hw_pipedocument ( int connection, int objectID)

Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be 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 )

hw_Root -- root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

hw_setlinkroot

(PHP 3>= 3.0.3, PHP 4 )

hw_setlinkroot --  Set the id to which links are calculated

Description

void hw_setlinkroot ( int link, int rootid)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

hw_stat

(PHP 3>= 3.0.3, PHP 4 )

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 )

hw_Unlock -- unlock object

Description

int hw_unlock ( int connection, int objectID)

Unlocks a document, so other users regain access.

See also hw_getandlock().

hw_Who

(PHP 3>= 3.0.3, PHP 4 )

hw_Who -- List of currently logged in users

Description

int hw_who ( int connection)

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.

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

NameDefaultChangeable
hwapi.allow_persistent"0"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


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

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->dstofsrcanchors -- Returns destination of a source anchor
hw_api_error->count -- Returns number of reasons
hw_api_error->reason -- Returns reason of error
hw_api->find -- Search for objects
hw_api->ftstat -- Returns statistics about fulltext server
hwapi_hgcsp -- Returns object of class hw_api
hw_api->hwstat -- Returns statistics about Hyperwave server
hw_api->identify -- Log into Hyperwave Server
hw_api->info -- Returns information about server configuration
hw_api->insert -- Inserts a new object
hw_api->insertanchor -- Inserts a new object of type anchor
hw_api->insertcollection -- Inserts a new object of type collection
hw_api->insertdocument -- Inserts a new object of type document
hw_api->link -- Creates a link to an object
hw_api->lock -- Locks an object
hw_api->move -- Moves object between collections
hw_api_content -- Create new instance of class hw_api_content
hw_api_object->assign -- Clones object
hw_api_object->attreditable -- Checks whether an attribute is editable
hw_api_object->count -- Returns number of attributes
hw_api_object->insert -- Inserts new attribute
hw_api_object -- Creates a new instance of class hw_api_object
hw_api_object->remove -- Removes attribute
hw_api_object->title -- Returns the title attribute
hw_api_object->value -- Returns value of attribute
hw_api->object -- Retrieve attribute information
hw_api->objectbyanchor -- Returns the object an anchor belongs to
hw_api->parents -- Returns parents of an object
hw_api_reason->description -- Returns description of reason
hw_api_reason->type -- Returns type of reason
hw_api->remove -- Delete an object
hw_api->replace -- Replaces an object
hw_api->setcommitedversion -- Commits version other than last version
hw_api->srcanchors -- Returns a list of all source anchors
hw_api->srcsofdst -- Returns source of a destination object
hw_api->unlock -- Unlocks a locked object
hw_api->user -- Returns the own user object
hw_api->userlist -- Returns a list of all logged in users

hw_api_attribute->key

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

string key ( void )

Returns the name of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

string langdepvalue ( string language)

Returns the value in the given language of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

string value ( void )

Returns the value of the attribute.

See also hwapi_attribute_key(), hwapi_attribute_values().

hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

array values ( void )

Returns all values of the attribute as an array of strings.

See also hwapi_attribute_value().

hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

object attribute ( [string name [, string value]])

Creates a new instance of hw_api_attribute with the given name and value.

hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

object checkin ( array parameter)

This function checks in an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks in and commits the object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.

HW_API_CHECKIN_FORCE_VERSION_CONTROL

Checks in an object even if it is not under version control.

HW_API_CHECKIN_REVERT_IF_NOT_CHANGED

Check if the new version is different from the last version. Unless this is the case the object will be checked in.

HW_API_CHECKIN_KEEP_TIME_MODIFIED

Keeps the time modified from the most recent object.

HW_API_CHECKIN_NO_AUTO_COMMIT

The object is not automatically 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

object checkout ( array parameter)

This function checks out an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks out an object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

See also hwapi_checkin().

hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

array children ( array parameter)

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_parents().

hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

string mimetype ( void )

Returns the mimetype of the content.

hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

string read ( string buffer, integer len)

Reads len bytes from the content into the given buffer.

hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

object content ( array parameter)

This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

object copy ( array parameter)

This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

See also hwapi_move(), hwapi_link().

hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

object dbstat ( array parameter)

See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().

hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

object dcstat ( array parameter)

See also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

object dstanchors ( array parameter)

Retrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_srcanchors().

hw_api->dstofsrcanchors

(no version information, might be only in CVS)

hw_api->dstofsrcanchors -- Returns destination of a source anchor

Description

object dstofsrcanchors ( array parameter)

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_srcanchors(), hwapi_dstanchors(), hwapi_objectbyanchor().

hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

int count ( void )

Returns the number of error reasons.

See also hwapi_error_reason().

hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

object reason ( void )

Returns the first error reason.

See also hwapi_error_count().

hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

array find ( array parameter)

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', '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

object ftstat ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().

hwapi_hgcsp

(no version information, might be only in CVS)

hwapi_hgcsp -- Returns object of class hw_api

Description

object hwapi_hgcsp ( string hostname [, int port])

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP. If you do not pass a port number, 418 is used.

See also hwapi_hwtp().

hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

object hwstat ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

object identify ( array parameter)

Logs into the Hyperwave Server. The parameter array must contain the elements 'username' 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

object info ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().

hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

object insert ( array parameter)

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set. The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding 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

object insertanchor ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

See also hwapi_insertdocument(), hwapi_insertcollection(), hwapi_insert().

hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

object insertcollection ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insertdocument(), hwapi_insertanchor(), hwapi_insert().

hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

object insertdocument ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insert() hwapi_insertanchor(), hwapi_insertcollection().

hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

object link ( array parameter)

Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

The function returns TRUE on success or an error object.

See also hwapi_copy().

hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

object lock ( array parameter)

Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the 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

object move ( array parameter)

See also hw_objrec2array().

hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

string content ( string content, string mimetype)

Creates a new content object from the string content. The mimetype is set to mimetype.

hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

object assign ( array parameter)

Clones the attributes of an object.

hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

bool attreditable ( array parameter)

hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

int count ( array parameter)

hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

bool insert ( object attribute)

Adds an attribute to the object. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_remove().

hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

object hw_api_object ( array parameter)

See also hwapi_lock().

hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

bool remove ( string name)

Removes the attribute with the given name. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_insert().

hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

string title ( array parameter)

hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

string value ( string name)

Returns the value of the attribute with the given name or FALSE if an error occurred.

hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

object hw_api->object ( array parameter)

This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error 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

object objectbyanchor ( array parameter)

This function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_dstofsrcanchor(), hwapi_srcanchors(), hwapi_dstanchors().

hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

array parents ( array parameter)

Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_children().

hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

string description ( void )

Returns the description of a reason

hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

object type ( void )

Returns the type of a reason.

hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

object remove ( array parameter)

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

object replace ( array parameter)

Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL

The object on the server is replace with the object passed.

HW_API_REPLACE_FORCE_VERSION_CONTROL

HW_API_REPLACE_AUTOMATIC_CHECKOUT

HW_API_REPLACE_AUTOMATIC_CHECKIN

HW_API_REPLACE_PLAIN

HW_API_REPLACE_REVERT_IF_NOT_CHANGED

HW_API_REPLACE_KEEP_TIME_MODIFIED

See also hwapi_insert().

hw_api->setcommitedversion

(no version information, might be only in CVS)

hw_api->setcommitedversion -- Commits version other than last version

Description

object setcommitedversion ( array parameter)

Commits a version of a 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

object srcanchors ( array parameter)

Retrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_dstanchors().

hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

object srcsofdst ( array parameter)

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

See also hwapi_dstofsrcanchor().

hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

object unlock ( array parameter)

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Returns TRUE on success or an object of class HW_API_Error.

See also hwapi_lock().

hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

object user ( array parameter)

See also hwapi_userlist().

hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

object userlist ( array parameter)

See also hwapi_user().

XLI. funzioni iconv

Qesto moudlo contiene un'interfaccia con le funzioni della libreria iconv. Per essere abilitati ad usare queste funzioni definite in questo modulo si deve compilare l'interprete PHP usando l'opzione --with-iconv. Per fare così, devi avere la funzione iconv() nella libreria standard di C o libriconv installata sul tuo sistema. La libreria libiconv è reperebile presso l'indirizzo http://www.gnu.org/software/libiconv/.

La libreria iconv converte i file tra vari set di caratteri. I set di caratteri supportati dipendono dall'implementazione di iconv() sul tuo sistema. Nota che la funzione iconv() non è utilizzabile come ti aspetti su alcuni sistemi. In questo caso, dovresti installare la libreria libiconv.

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

The output of this script should look like:

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

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

XLII. 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
exif_imagetype -- Determina il tipo di un'immagine
exif_read_data -- Reads the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.
exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image
gd_info -- Retrieve information about the currently installed GD library
getimagesize -- Get the size of an image
image_type_to_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
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 Filter an image using a custom angle
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
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
read_exif_data -- Alias of exif_read_data()

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype -- Determina il tipo di un'immagine

Descrizione

int|false exif_imagetype ( string filename)

exif_imagetype() legge i primi byte di un'immagine e controlla la relativa signature. Se la funzione riesce e trovare una signature corretta, verrà restituita una costante, altrimenti verrà restituito il valore FALSE. Il valore restituito è lo stesso che restituisce la funzione getimagesize() come secondo indice, ma la prima funzione è più rapida.

Sono definite le seguenti costanti: 1 = IMAGETYPE_GIF, 2 = IMAGETYPE_JPG, 3 = IMAGETYPE_PNG, 4 = IMAGETYPE_SWF, 5 = IMAGETYPE_PSD, 6 = IMAGETYPE_BMP, 7 = IMAGETYPE_TIFF_II (intel byte order), 8 = IMAGETYPE_TIFF_MM (motorola byte order), 9 = IMAGETYPE_JPC, 10 = IMAGETYPE_JP2, 11 = IMAGETYPE_JPX.

Questa funzione può essere usata per evitare di invocare altre funzioni exif con tipi di immagine non supportati o in unione a $_SERVER['HTTP_ACCEPT'] per controllare se il visitatore è in grado o meno di visualizzare un determinato tipo di immagine col suo browser.

Nota: Questa funzione è disponibile solo con PHP 4 compilato utilizzando l'opzione --enable-exif.

Questa funzione non richiede le librerie GD.

Vedi anche getimagesize().

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data -- Reads the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.

Description

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]])

The exif_read_data() function reads the EXIF headers from a JPEG or TIFF image file. It returns an associative array where the indexes are the header names and the values are the values associated with those headers. If no data can be returned the result is FALSE.

filename is the name of the file to read. This cannot be a URL.

sections 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
COMPUTEDhtml, Width, Height, IsColor and some more if available.
ANY_TAGAny information that has a Tag e.g. IFD0, EXIF, ...
IFD0All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAILA 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.
EXIFThe 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 allways become arrays as they may contain values whose names are conflict with other sections.

thumbnail whether or not to read the thumbnail itself and not only its tagged data.

Nota: Exif headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

Windows ME/XP both can wipe the Exif headers when connecting to a camera. More information available at http://www.canon-asia.com/products/digital_cameras/winxp_problems.html.

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

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

The first call fails because the image has no header information.
test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

Nota: If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. This was added in PHP 4.3.

When an Exif header contains a Copyright note this itself can contain two values. As the solution is 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 contain also an entry Copyright Which is either the original copyright string or it is a comma separated list of photo and editor copyright.

Nota: The tag UserComment has the same problem as the Copyright tag. It can store two values first the encoding used and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.

If the user comment uses Unicode or JIS encoding and the module mbstring is available this encoding will automatically changed according to the exif ini settings in the php.ini. This was added in PHP 4.3.

Nota: Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also html is a height/width text string to be used inside normal HTML.

Nota: Starting from PHP 4.3 the function can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in THUMBNAIL subarray and the function exif_read_data() can return thumbnails in TIFF format. Last but not least there is no longer a maximum length for returned values (not until memory limit is reached).

Nota: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2. Earlier versions are very unstable.

Since PHP 4.3 user comment can automatically change encoding if PHP 4 was compiled using --enable-mbstring.

This function does not require the GD image library.

See also exif_thumbnail() and getimagesize().

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]])

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image. If the image contains no thumbnail FALSE will be returned.

The parameters width, height and imagetype are available since PHP 4.3.0 and return the size of the thumbnail as well as its type. 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.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function. The following example demonstrates this:

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

Starting from version PHP 4.3.0, the function exif_thumbnail() can return thumbnails in TIFF format.

Nota: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2.0

Nota: This function does not require the GD image library.

See also exif_read_data() and image_type_to_mime_type().

gd_info

(PHP 4 >= 4.3.0, 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)

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.

See also imagecreatetruecolor().

imagearc

(PHP 3, PHP 4 , PHP 5)

imagearc -- Draw a partial ellipse

Description

int 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 = imagecreate(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

int 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 = imagecreate(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

int 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 = imagecreate(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 imagecreate() function. red, green and blue are the values of the red, green and blue component of the requested color respectively. These parameters are integers between 0 and 255 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

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

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

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

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.

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

bool imagecolorset ( resource image, int index, int red, int green, int blue)

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in 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 imagecreate() and color is a color identifier returned by imagecolorallocate().

Nota: The transparent color is a property of the image, transparency is not a property of the color. Once you have a set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

The identifier of the new (or current, if none is specified) transparent color is returned.

imagecopy

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

imagecopy -- Copy part of an image

Description

int imagecopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5)

imagecopymerge -- Copy and merge part of an image

Description

int imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

Nota: This function was added in PHP 4.0.6

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5)

imagecopymergegray -- Copy and merge part of an image with gray scale

Description

int imagecopymergegray ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

This function is identical to imagecopymerge() except that when merging it 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_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

Nota: This function requires GD 2.0.1 or later.

See also imagecopyresized().

imagecopyresized

(PHP 3, PHP 4 , PHP 5)

imagecopyresized -- Copy and resize part of an image

Description

int imagecopyresized ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

imagecopyresized() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

See also imagecopyresampled().

imagecreate

(PHP 3, PHP 4 , 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(50, 100)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
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.

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

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 L 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 L 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 (courtesy vic at zymsys dot com)

<?php
function LoadGif ($imgname) 
{
    $im = @imagecreatefromgif ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

Nota: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

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 L 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 (courtesy vic at zymsys dot com )

<?php
function LoadJpeg($imgname) 
{
    $im = @imagecreatefromjpeg($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate(150, 30); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

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 L 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 (courtesy vic at zymsys dot com)

<?php
function LoadPNG($imgname) 
{
    $im = @imagecreatefrompng($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate(150, 30); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

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

Description

resource imagecreatefromstring ( string image)

imagecreatefromstring() returns an image identifier representing the image obtained from the given string.

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 (courtesy vic at zymsys dot com)

<?php
function LoadWBMP($imgname) 
{
    $im = @imagecreatefromwbmp($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (20, 20); /* Create a blank image */
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}
?>

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

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

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

int 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 the imagecreate() function.

imageellipse

(PHP 4 >= 4.0.6, PHP 5)

imageellipse -- Draw an ellipse

Description

int 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 = imagecreate(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

int 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

// this example is provided by poxy at klam dot is

// create image
$image = imagecreate(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.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

Esempio 1. imagefilledellipse() example

<?php

// create a blank image
$image = imagecreate(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

int imagefilledpolygon ( resource image, array points, int num_points, int color)

imagefilledpolygon() creates a filled polygon in image image. 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 vertices.

Esempio 1. imagefilledpolygon() example

<?php

// this example is provided by ecofarm at mullum dot com dot au

// set up array of points for polygon
$values = array(
  0  => 40,    // x1
  1  => 50,    // y1
  2  => 20,    // x2
  3  => 240,   // y2
  4  => 60,    // x3
  5  => 60,    // y3
  6  => 240,   // x4
  7  => 20,    // y4
  8  => 50,    // x5
  9  => 40,    // y5
  10 => 10,    // x6
  11 => 10,    // y6
);

// create image
$im = imagecreate(250, 250);

// some colors
$bg   = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 0, 0, 255);

// draw a polygon
imagefilledpolygon($im, $values, 6, $blue );

// flush image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

?>

imagefilledrectangle

(PHP 3, PHP 4 , PHP 5)

imagefilledrectangle -- Draw a filled rectangle

Description

int 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

int 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 Filter an image using a custom angle

Description

bool imagefilter ( resource src_im, int filtertype [, int args])

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.

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.

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.

imagegammacorrect

(PHP 3>= 3.0.13, PHP 4 , PHP 5)

imagegammacorrect -- Apply a gamma correction to a GD image

Description

int imagegammacorrect ( resource image, float inputgamma, float outputgamma)

The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.

imagegd2

(PHP 4 >= 4.1.0, PHP 5)

imagegd2 -- Output GD2 image

Description

bool imagegd2 ( resource image [, string filename [, int chunk_size [, int type]]])

imagegd2() outputs GD2 image to browser or file.

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.

imagegd

(PHP 4 >= 4.1.0, PHP 5)

imagegd -- Output GD image to browser or file

Description

bool imagegd ( resource image [, string filename])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.

Nota: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library. 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 imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.

Nota: JPEG support is only available if PHP was compiled against GD-1.8 or later.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See also imagepng(), imagegif(), imagewbmp(), imageinterlace() and imagetypes().

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

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

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.

See also imagefontwidth() and imagefontheight().

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5)

imagepalettecopy -- Copy the palette from one image to another

Description

int imagepalettecopy ( resource destination, resource source)

imagepalettecopy() copies the palette from the source image to the destination image.

imagepng

(PHP 3>= 3.0.13, PHP 4 , 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

int 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 = imagecreate(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 --enable-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 ( int 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 --enable-t1lib.

See also imagepsloadfont().

imagepsencodefont

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

imagepsencodefont -- Change the character encoding vector of a font

Description

int imagepsencodefont ( int 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 --enable-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 --enable-t1lib.

imagepsfreefont

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

imagepsfreefont -- Free memory used by a PostScript Type 1 font

Description

void imagepsfreefont ( int fontindex)

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.

See also imagepsloadfont().

imagepsloadfont

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

imagepsloadfont -- Load a PostScript Type 1 font from file

Description

int imagepsloadfont ( string filename)

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.

Esempio 1. imagepsloadfont() example

<?php
header("Content-type: image/jpeg");
$im = imagecreate(350, 45);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$font = imagepsloadfont("bchbi.pfb"); // or locate your .pfb files on your machine
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);
imagejpeg($im, "", 100); //for best quality...your mileage may vary
imagedestroy($im);
?>

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.

See also imagepsfreefont().

imagepsslantfont

(PHP 3>= 3.0.9, PHP 4 , PHP 5)

imagepsslantfont -- Slant a font

Description

bool imagepsslantfont ( int font_index, float slant)

Slant a font given by the font_index parameter with a slant of the value of the slant parameter.

Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-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, int 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 --enable-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

int imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col)

imagerectangle() creates a rectangle of color col in image image starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.

imagerotate

(PHP 4 >= 4.3.0, PHP 5)

imagerotate -- Rotate an image with a given angle

Description

resource imagerotate ( resource src_im, float angle, int bgd_color)

Rotates the src_im image using a given angle in degree. bgd_color specifies the color of the uncovered zone after the rotation.

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

int imagesetbrush ( resource image, resource brush)

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Nota: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

Nota: This function was added in PHP 4.0.6

imagesetpixel

(PHP 3, PHP 4 , PHP 5)

imagesetpixel -- Set a single pixel

Description

int 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 imagecreate() 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  = imagecreate(100, 100);
$w   = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red);
imagesetstyle($im, $style);

$brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg($im);
imagedestroy($im);
?>

See also imagesetbrush(), imageline().

Nota: This function was added in PHP 4.0.6

imagesetthickness

(PHP 4 >= 4.0.6, 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

int imagesettile ( resource image, resource tile)

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Nota: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

imagestring

(PHP 3, PHP 4 , PHP 5)

imagestring -- Draw a string horizontally

Description

int imagestring ( resource image, int font, int x, int y, string s, int col)

imagestring() draws the string s in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

Esempio 1. imagestring() example

<?php

  // create a 100*30 image
  $im = imagecreate(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/jpg");
  imagejpeg($im);
?>

See also imageloadfont().

imagestringup

(PHP 3, PHP 4 , PHP 5)

imagestringup -- Draw a string vertically

Description

int imagestringup ( resource image, int font, int x, int y, string s, int col)

imagestringup() draws the string s vertically in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

imagesx

(PHP 3, PHP 4 , 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 = imagecreate(300, 200);

echo imagesx($img); // 300

?>

See also imagecreate(), 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 = imagecreate(300, 200);

echo imagesy($img); // 200

?>

See also imagecreate(), getimagesize() and imagesx().

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5)

imagetruecolortopalette -- Convert a true color image to a palette image

Description

void imagetruecolortopalette ( resource image, bool dither, int ncolors)

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors sets the maximum number of colors that should be retained in the palette.

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

text

The string to be measured.

size

The font size in pixels.

fontfile

The name of the TrueType font file. (Can also 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.

angle

Angle in degrees in which text will be measured.

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

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)

imagettftext() draws the string text in the image identified by image, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color color, using the TrueType font file identified by fontfile. Depending on which version of the GD library that PHP is using, when fontfile does not begin with a leading '/', '.ttf' will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

The coordinates given by x, y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character.

angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).

fontfile is the path to the TrueType font you wish to use.

text is the text string which may include UTF-8 character sequences (of the form: &#123;) to access characters in a font beyond the first 255.

color is the color index. Using the negative of a color index has the effect of turning off antialiasing.

imagettftext() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally.

This example script will produce a black JPEG 400x30 pixels, with the words "Testing..." in white in the font Arial.

Esempio 1. imagettftext() example

<?php
  header("Content-type: image/jpeg");
  $im = imagecreate(400, 30);
  $white = imagecolorallocate($im, 255, 255, 255);
  $black = imagecolorallocate($im, 0, 0, 0);
  
  // Replace path by your own font path
  imagettftext($im, 20, 0, 10, 20, $black, "/path/arial.ttf",
  "Testing... Omega: &amp;#937;");
  imagejpeg($im);
  imagedestroy($im);
?>

This function requires both the GD library and the FreeType library.

See also imagettfbbox().

imagetypes

(PHP 3 CVS only, PHP 4 >= 4.0.2, 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 imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Using the optional foreground parameter, you can set the foreground color. Use an identifier obtained from imagecolorallocate(). The default foreground color is black.

See also image2wbmp(), imagepng(), imagegif(), imagejpeg(), imagetypes().

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

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

read_exif_data

read_exif_data -- Alias of exif_read_data()

Description

This function is an alias of exif_read_data().

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


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

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 o YAZ. 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 of 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 of imap_list()
imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_listsubscribed -- Alias of 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 of 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 --  Return threaded by REFERENCES tree
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, int 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

  • date - when was it sent

  • message_id - Message-ID

  • references - is a reference to this message id

  • size - size in bytes

  • uid - UID the message has in the mailbox

  • msgno - message sequence number in the maibox

  • recent - this message is flagged as recent

  • flagged - this message is flagged

  • answered - this message is flagged as answered

  • deleted - this message is flagged for deletion

  • seen - this message is flagged as already read

  • draft - this message is flagged as being a draft

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)) {
        reset($overview);
        while (list($key, $val) = each($overview)) {
                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 [, flags options])

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

The options for imap_fetchbody() is a bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, 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 originial 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.

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)) {
  reset($list);
  while (list($key, $val) = each($list)) {
    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

imap_header -- Alias of imap_headerinfo()

Description

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)) {
  reset($list);
  while (list($key, $val) = each($list)) {
    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

imap_listmailbox -- Alias of imap_list()

Description

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

imap_listsubscribed -- Alias of imap_lsub()

Description

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

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

To connect to an IMAP server running on port 143 on the local machine, do the following:

<?php
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");
?>

To connect to a POP3 server on port 110 on the local server, use:

<?php
$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:

<?php
$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:

<?php
$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:

<?php
$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 1. 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 {
    while (list ($key, $val) = each($folders)) {
        echo $val . "<br />\n";
    }
}

echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    while (list ($key, $val) = each ($headers)) {
        echo $val . "<br />\n";
    }
}

imap_close($mbox);
?>

imap_ping

(PHP 3, PHP 4 , 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() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout. (As PHP scripts do not tend to run that long, I can hardly imagine that this function will be useful to anyone.)

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

imap_scanmailbox -- Alias of imap_listscan()

Description

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)

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.

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

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

Returns an array of message numbers sorted by the given parameters.

Reverse is 1 for reverse-sorting.

Criteria can be one (and only one) of the following:

  • SORTDATE - message Date

  • SORTARRIVAL - arrival date

  • SORTFROM - mailbox in first From address

  • SORTSUBJECT - message subject

  • SORTTO - mailbox in first To address

  • SORTCC - mailbox in first cc address

  • SORTSIZE - size of message in octets

The flags are a bitmask of one or more of the following:

  • SE_UID - Return UIDs instead of sequence numbers

  • SE_NOPREFETCH - Don't prefetch searched messages

imap_status

(PHP 3>= 3.0.4, PHP 4 , 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 --  Return threaded by REFERENCES tree

Description

array imap_thread ( resource stream_id [, int options])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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 an unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().

Nota: This is not supported by POP3 mailboxes.

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)

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.

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

NameDefaultChangeable
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
For further details and definition of the PHP_INI_* constants see ini_set().

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 safe mode.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().


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 ... */
}
for ($i = 0; $i < count($properties); $i++) {
    $fname = key ($properties);
    printf ("%s:\t type =  %s\n", $fname, $properties[$fname]);
    next ($properties);
}
?>

ifx_fieldtypes

(PHP 3>= 3.0.3, PHP 4 , 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 ... */
}
for ($i = 0; $i < count($types); $i++) {
    $fname = key($types);
    printf("%s :\t type =  %s\n", $fname, $types[$fname]);
    next($types);
}
?>

ifx_free_blob

(PHP 3>= 3.0.4, PHP 4 , 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 ( long bid, int mode)

Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.

ifxus_read_slob

(PHP 3>= 3.0.4, PHP 4 , PHP 5)

ifxus_read_slob -- Reads nbytes of the slob object

Description

int ifxus_read_slob ( long bid, long nbytes)

Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.

ifxus_seek_slob

(PHP 3>= 3.0.4, PHP 4 , PHP 5)

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( long bid, int mode, long offset)

Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.

ifxus_tell_slob

(PHP 3>= 3.0.4, PHP 4 , PHP 5)

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( long bid)

Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.

ifxus_write_slob

(PHP 3>= 3.0.4, PHP 4 , PHP 5)

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( long bid, string content)

Writes a string into the slob object. bid is an existing slob id and content the content to write. Return FALSE on error otherwise bytes written.

XLV. Funzioni InterBase

InterBase è un famoso database prodotto da Borland/Inprise. Maggiori informazioni riguardo InterBase sono disponibili a http://www.interbase.com/. Oh, a proposito, InterBase è da poco entrato nel movimento open source!

Nota: Il supporto completo per InterBase 6 è stato aggiunto in PHP 4.0.

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

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 ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

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 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_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 ( string server, string dba_user_name, string dba_user_password, string user_name)

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

int ibase_gen_id ( [resource link_identifier [, string generator [, int increment]]])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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 ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

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_connect ( 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_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 ( [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.

<?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 , PHP 5)

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

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


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, downloadthe 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 (integer)

ID3_V2 is used if you are working with ID3 V2.x tags. These tags are quite flexible and are currently not supported by the id3 extension.

Sommario
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_genre_id

(no version information, might be only in CVS)

id3_get_genre_id -- Get the id for a genre.

Description

int id3_get_genre_name ( 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

Nota: Instead of a filename you may also pass a valid stream resource.

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

(no version information, might be only in CVS)

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.

Nota: Instead of a filename you may also pass a valid stream resource.

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

(no version information, might be only in CVS)

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.

Nota: Instead of a filename you may also pass a valid stream resource.

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

(no version information, might be only in CVS)

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
)

Nota: Currently id3_get_tag() only supports version 1.0 and 1.1.

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.

See also id3_set_tag(), id3_remove_tag() and id3_get_version().

id3_get_version

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

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

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

To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.


Installazione

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 II configuration options

NameDefaultChangeable
ingres.allow_persistent"1"PHP_INI_SYSTEM
ingres.max_persistent"-1"PHP_INI_SYSTEM
ingres.max_links"-1"PHP_INI_SYSTEM
ingres.default_databaseNULLPHP_INI_ALL
ingres.default_userNULLPHP_INI_ALL
ingres.default_passwordNULLPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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)

INGRES_NUM (integer)

INGRES_BOTH (integer)

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

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_connect --  Open a connection to an Ingres II database

Description

resource ingres_connect ( [string database [, string username [, string password]]])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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_fetch_array

(PHP 4 >= 4.0.2, PHP 5)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_fetch_object -- Fetch a row of result into an object.

Description

object ingres_fetch_object ( [int result_type [, resource link]])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_fetch_row --  Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_field_name -- Get the name of a field in a query result.

Description

string ingres_field_name ( int index [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_field_type --  Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_num_fields --  Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

ingres_num_rows --  Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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)

ingres_pconnect --  Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

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


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

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)

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_fetch_error_msg

(PHP 4 >= 4.1.0, PHP 5)

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)

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)

ircg_html_encode --  Encodes HTML preserving output

Description

bool ircg_html_encode ( string html_string)

Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.

ircg_ignore_add

(PHP 4 >= 4.0.5, PHP 5)

ircg_ignore_add --  Add a user to your ignore list on a server

Description

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

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)

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)

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)

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)

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)

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)

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)

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)

ircg_msg --  Send message to channel or user on server

Description

bool ircg_msg ( resource connection, string recipient, string message [, boolean suppress])

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.

ircg_nick

(PHP 4 >= 4.0.5, PHP 5)

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)

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)

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)

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)

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)

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)

ircg_pconnect --  Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings]]]]])

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

Nota: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.

You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.

If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.

You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.

See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().

ircg_register_format_messages

(PHP 4 >= 4.0.5, PHP 5)

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)

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)

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)

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)

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)

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)

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.

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

To include Java support in your PHP build you must add the option --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared dl. More build instructions for this extension can be found in php-src/ext/java/README.

Note to Win32 Users: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must copy jvm.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). For PHP > 4.0.6 you do not need any additional dll file.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Java configuration options

NameDefaultChangeable
java.class.pathNULLPHP_INI_ALL
java.homeNULLPHP_INI_ALL
java.library.pathNULLPHP_INI_ALL
java.libraryJAVALIBPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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 advanatage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

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)

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)

java_last_exception_get -- Get last Java exception

Description

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

L. 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 the University of Michigan ldap-3.3 package, Netscape Directory SDK 3.0 or OpenLDAP 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.

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.


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. LDAP configuration options

NameDefaultChangeable
ldap.max_links"-1"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


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 -- Close link to LDAP server
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str --  Convert LDAP error number into string error message
ldap_errno --  Return the LDAP error number of the last LDAP command
ldap_error --  Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_first_reference --  Return first reference
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values_len -- Get all binary values from a result entry
ldap_get_values -- Get all values from a result entry
ldap_list -- Single-level search
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_modify -- Modify an LDAP entry
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_next_reference --  Get next reference
ldap_parse_reference --  Extract information from reference entry
ldap_parse_result --  Extract information from result
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_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.


    entry["attribute1"] = value
    entry["attribute2"][0] = value1
    entry["attribute2"][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"; 
}
?>

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 -- Close link to LDAP server

Description

bool ldap_close ( resource link_identifier)

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.

This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use this in preference to ldap_close().

Nota: This function is an alias of ldap_unbind().

ldap_compare

(PHP 4 >= 4.0.2, PHP 5)

ldap_compare -- Compare value of attribute found in entry specified with DN

Description

bool ldap_compare ( resource link_identifier, string dn, string attribute, string value)

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

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.

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

?>

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.

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.

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

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)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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, string 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.

LI. LZF Functions

Introduzione

LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. It can be optimized for speed or space at the time of compilation.


Installazione

LZF is currently available through PECL http://pecl.php.net/package/lzf.

If PEAR is available on your *nix-like system you can use the pear installer to install the LZF extension, by the following command: pear -v install lzf.

You can always download the tar.gz package and install LZF by hand:

Esempio 1. LZF install by hand

gunzip lzf-xxx.tgz
tar -xvf lzf-xxx.tar
cd lzf-xxx
phpize
./configure && make && make install

You can pass --enable-lzf-better-compression to optimize LZF for space rather then speed.

Windows users can download the extension dll php_lzf.dll from http://snaps.php.net/win32/PECL_STABLE/.

Sommario
lzf_compress --  LZF compression.
lzf_decompress --  LZF decompression.
lzf_optimized_for --  Determines what LZF extension was optimized for.

lzf_compress

(no version information, might be only in CVS)

lzf_compress --  LZF compression.

Description

string lzf_compress ( string arg)

lzf_compress() compresses data in arg parameter.

Returns compressed data or FALSE if an error occured.

See also lzf_decompress().

lzf_decompress

(no version information, might be only in CVS)

lzf_decompress --  LZF decompression.

Description

string lzf_decompress ( string arg)

lzf_decompress() decompresses data from parameter arg.

Returns decompressed data or FALSE if an error occured.

See also lzf_compress().

lzf_optimized_for

(no version information, might be only in CVS)

lzf_optimized_for --  Determines what LZF extension was optimized for.

Description

int lzf_optimized_for ( void )

Returns 1 if LZF was optimized for speed, 0 for compression.

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


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

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

This extension has been moved from PHP as of PHP 4.2.0 and now mailparse lives in PECL.


Installazione

These functions are only available if PHP was configured with --enable-mailparse.

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. If callbackfunc is not specified, the contents will be sent to "stdout"
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. Returns an array listing filename information

mailparse_determine_best_xfer_encoding

(4.1.0 - 4.1.2 only)

mailparse_determine_best_xfer_encoding --  Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able

Description

int mailparse_determine_best_xfer_encoding ( resource fp)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

mailparse_msg_create -- Returns a handle that can be used to parse a message

Description

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

mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding

Description

string mailparse_msg_extract_part_file ( resource rfc2045, string filename [, string callbackfunc])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

mailparse_msg_extract_part --  Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"

Description

void mailparse_msg_extract_part ( resource rfc2045, string msgbody [, string callbackfunc])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_free

(4.1.0 - 4.1.2 only)

mailparse_msg_free -- Frees a handle allocated by mailparse_msg_create()

Description

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

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)

mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage

Description

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

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)

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)

mailparse_msg_parse -- Incrementally parse data into buffer

Description

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

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)

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

(no version information, might be only in CVS)

mailparse_uudecode_all --  Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename information

Description

array mailparse_uudecode_all ( resource fp)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LIV. 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 arg, 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

See also 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. base_convert()

<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);
?>

Visualizza:

101000110111001100110100

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() and 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() sostituisce ogni carattere non esadecimale che incontra con 0. In questo modo, tutti gli zeri a sinistra sono ignorati, ma gli zeri a destra sono valutati.

Esempio 1. esempio di hexdec()

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// entrambi stampano "int(238)"

var_dump(hexdec("that"));
var_dump(hexdec("a0"));
// entrambi stampano "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 è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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 assicura numeri casuali che potrebbero essere utilizzati per scopi crittografici e (vedere la homepage per i dettagli) e che è mediamente quattro volte più veloce 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.

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

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

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

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 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.04
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 solo nel 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.

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

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

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

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

NameDefaultChangeable
mbstring.language"neutral"PHP_INI_SYSTEM | PHP_INI_PERDIR
mbstring.detect_orderNULLPHP_INI_ALL
mbstring.http_input"pass"PHP_INI_ALL
mbstring.http_output"pass"PHP_INI_ALL
mbstring.internal_encodingNULLPHP_INI_ALL
mbstring.script_encodingNULLPHP_INI_ALL
mbstring.substitute_characterNULLPHP_INI_ALL
mbstring.func_overload"0"PHP_INI_SYSTEM | PHP_INI_PERDIR
mbstring.encoding_translation"0"PHP_INI_SYSTEM | PHP_INI_PERDIR
For the definition of the PHP_INI_* constants, please refer to ini_set().

Breve descrizione dei parametri di configurazione.

  • mbstring.language is 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 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 defines the default internal character encoding.

  • mbstring.http_input defines the default HTTP input character encoding.

  • mbstring.http_output defines the default HTTP output character encoding.

  • mbstring.detect_order defines default character code detection order. See also mb_detect_order().

  • mbstring.substitute_character defines character to substitute for invalid character encoding.

  • mbstring.func_overload overloads a set of single byte functions by the mbstring counterparts. See Funtion 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() and strtoupper().

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 [, mixed encoding])

mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.

option is conversion option. Default value is "KV".

encoding is character encoding. If it is omitted, internal character encoding is used.

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)

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

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

array mb_detect_order ( [mixed encoding-list])

mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE for failure.

encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding-list is omitted, it returns current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

Nota: mbstring currently implements following encoding detection filters. If there is 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])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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 [, array option])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

array mb_ereg_search_getpos ( 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.

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 )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

array mb_ereg_search_init ( string string [, string pattern [, string option]])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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(). It it is not specified, the previous one will be used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

array mb_ereg_search_setpos ( 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.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

string mb_get_info ( [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.

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

string mb_http_input ( [string type])

mb_http_input() returns result of HTTP input character encoding detection.

type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input type processed.

Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.

See also mb_internal_encoding(), mb_http_output(), mb_detect_order().

mb_http_output

(PHP 4 >= 4.0.6, PHP 5)

mb_http_output -- Set/Get HTTP output character encoding

Description

string mb_http_output ( [string encoding])

If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.

If encoding is omitted, mb_http_output() returns current HTTP output character encoding.

See also mb_internal_encoding(), mb_http_input(), mb_detect_order().

mb_internal_encoding

(PHP 4 >= 4.0.6, 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

string mb_language ( [string language])

mb_language() sets language. If language is omitted, it returns current language as string.

language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.

See also mb_send_mail().

mb_list_encodings

(PHP 5)

mb_list_encodings --  Returns an array of all supported encodings

Description

array mb_list_encodings ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

string mb_regex_encoding ( [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.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

string mb_strlen ( string str [, string encoding])

mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

encoding is character encoding for str. If encoding is omitted, internal character encoding is used.

See also mb_internal_encoding(), strlen().

mb_strpos

(PHP 4 >= 4.0.6, 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_strpos(), 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().

LVI. 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 rimosso da PHP 5 ed inserito tra le librerie PECL.

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 )

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 )

mcal_close -- Close an MCAL stream

Description

int mcal_close ( int mcal_stream, int flags)

Closes the given mcal stream.

mcal_create_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_create_calendar -- Create a new MCAL calendar

Description

bool mcal_create_calendar ( int stream, string calendar)

Creates a new calendar named calendar.

mcal_date_compare

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_compare -- Compares two dates

Description

int mcal_date_compare ( int a_year, int a_month, int a_day, int b_year, int b_month, int b_day)

mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.

mcal_date_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_valid --  Returns TRUE if the given year, month, day is a valid date

Description

int mcal_date_valid ( int year, int month, int day)

mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.

mcal_day_of_week

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_week --  Returns the day of the week of the given date

Description

int mcal_day_of_week ( int year, int month, int day)

mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.

mcal_day_of_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_year --  Returns the day of the year of the given date

Description

int mcal_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 )

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 )

mcal_delete_calendar -- Delete an MCAL calendar

Description

string mcal_delete_calendar ( int stream, string calendar)

Deletes the calendar named calendar.

mcal_delete_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_event -- Delete an event from an MCAL calendar

Description

int mcal_delete_event ( int mcal_stream [, int event_id])

mcal_delete_event() deletes the calendar event specified by the event_id.

Returns TRUE.

mcal_event_add_attribute

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure

Description

void mcal_event_add_attribute ( int stream, string attribute, string value)

mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".

mcal_event_init

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_init --  Initializes a streams global event structure

Description

int mcal_event_init ( int stream)

mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.

Returns TRUE.

mcal_event_set_alarm

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_alarm --  Sets the alarm of the streams global event structure

Description

int mcal_event_set_alarm ( int stream, int alarm)

mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.

Returns TRUE.

mcal_event_set_category

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_category --  Sets the category of the streams global event structure

Description

int mcal_event_set_category ( int stream, string category)

mcal_event_set_category() sets the streams global event structure's category to the given string.

Returns TRUE.

mcal_event_set_class

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_class --  Sets the class of the streams global event structure

Description

int mcal_event_set_class ( int stream, int class)

mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.

Returns TRUE.

mcal_event_set_description

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_description --  Sets the description of the streams global event structure

Description

int mcal_event_set_description ( int stream, string description)

mcal_event_set_description() sets the streams global event structure's description to the given string.

Returns TRUE.

mcal_event_set_end

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_end --  Sets the end date and time of the streams global event structure

Description

int mcal_event_set_end ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_end() sets the streams global event structure's end date and time to the given values.

Returns TRUE.

mcal_event_set_recur_daily

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_daily ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccurring on a daily basis, ending at the given date.

mcal_event_set_recur_monthly_mday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_mday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be 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 )

mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_wday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by week basis, ending at the given date.

mcal_event_set_recur_none

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_none ( int stream)

mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).

mcal_event_set_recur_weekly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_weekly ( int stream, int year, int month, int day, int interval, int weekdays)

mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccurring on a weekly basis, ending at the given date.

mcal_event_set_recur_yearly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_yearly ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccurring on a yearly basis,ending at the given date.

mcal_event_set_start

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_start --  Sets the start date and time of the streams global event structure

Description

int mcal_event_set_start ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_start() sets the streams global event structure's start date and time to the given values.

Returns TRUE.

mcal_event_set_title

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_title --  Sets the title of the streams global event structure

Description

int mcal_event_set_title ( int stream, string title)

mcal_event_set_title() sets the streams global event structure's title to the given string.

Returns TRUE.

mcal_expunge

(no version information, might be only in CVS)

mcal_expunge --  Deletes all events marked for being expunged.

Description

int mcal_expunge ( int stream)

mcal_expunge() deletes all events which have been previously marked for deletion.

mcal_fetch_current_stream_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure

Description

object mcal_fetch_current_stream_event ( int stream)

mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

mcal_fetch_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_event --  Fetches an event from the calendar stream

Description

object mcal_fetch_event ( int mcal_stream, int event_id [, int options])

mcal_fetch_event() fetches an event from the calendar stream specified by id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

The possible values for recur_type are:

  • 0 - Indicates that this event does not recur

  • 1 - This event recurs daily

  • 2 - This event recurs on a weekly basis

  • 3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)

  • 4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)

  • 5 - This event recurs on an annual basis

mcal_is_leap_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_is_leap_year --  Returns if the given year is a leap year or not

Description

int mcal_is_leap_year ( int year)

mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.

mcal_list_alarms

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime

Description

array mcal_list_alarms ( int mcal_stream [, int begin_year [, int begin_month [, int begin_day [, int end_year [, int end_month [, int end_day]]]]]])

Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_list_events

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_events --  Return a list of IDs for a date or a range of dates

Description

array mcal_list_events ( int mcal_stream, object begin_date [, object end_date])

Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_next_recurrence

(PHP 3>= 3.0.13, PHP 4 )

mcal_next_recurrence -- Returns the next recurrence of the event

Description

int mcal_next_recurrence ( int stream, int weekstart, array next)

mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.

mcal_open

(PHP 3>= 3.0.13, PHP 4 )

mcal_open -- Opens up an MCAL connection

Description

int mcal_open ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_popen

(PHP 3>= 3.0.13, PHP 4 )

mcal_popen -- Opens up a persistent MCAL connection

Description

int mcal_popen ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_rename_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_rename_calendar -- Rename an MCAL calendar

Description

string mcal_rename_calendar ( int stream, string old_name, string new_name)

Renames the calendar old_name to new_name.

mcal_reopen

(PHP 3>= 3.0.13, PHP 4 )

mcal_reopen -- Reopens an MCAL connection

Description

int mcal_reopen ( string calendar [, int options])

Reopens an MCAL stream to a new calendar.

mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

mcal_snooze

(PHP 3>= 3.0.13, PHP 4 )

mcal_snooze -- Turn off an alarm for an event

Description

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 )

mcal_store_event -- Modify an existing event in an MCAL calendar

Description

int mcal_store_event ( int mcal_stream)

mcal_store_event() stores the modifications to the current global event for the given stream.

Returns the event id of the modified event on success and FALSE on error.

mcal_time_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_time_valid --  Returns TRUE if the given hour, minutes and seconds is a valid time

Description

int mcal_time_valid ( int hour, int minutes, int seconds)

mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.

mcal_week_of_year

(PHP 4 )

mcal_week_of_year --  Returns the week number of the given date

Description

int mcal_week_of_year ( int day, int month, int year)

mcal_week_of_year() returns the week number of the given date.

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

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

NameDefaultChangeable
mcrypt.algorithms_dirNULLPHP_INI_ALL
mcrypt.modes_dirNULLPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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.

mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies the source of the IV.

The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). If you use MCRYPT_RAND, make sure to call srand() before to initialize the random number generator. MCRYPT_RAND is the only one supported on Windows because Windows (of course) doesn't have /dev/random or /dev/urandom.

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 loosing security.

More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.

mcrypt_decrypt

(PHP 4 >= 4.0.2, 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";
?>

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

bool mcrypt_enc_self_test ( resource td)

This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_encrypt

(PHP 4 >= 4.0.2, 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";
?>

The above example will print out:
42
64

See also mcrypt_module_open() for a more advanced API and an example.

mcrypt_generic_deinit

(PHP 4 >= 4.1.1, 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.

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

The above example will produce:
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));
?>

The above example will output:

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

LVIII. 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 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, long 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, long 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, long 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, long 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 ( long 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.

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

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 memcache extension.


Installazione

Memcache is currently available through PECL http://pecl.php.net/package/memcache.

Also you can use the pear installer to install the memcache extension, using the following command: pear -v install memcache.

You can always download the tar.gz package and install memcache by hand:

Esempio 1. Memcache installation

gunzip memcache-xxx.tgz
tar -xvf memcache-xxx.tar
cd memcache-xxx
phpize
./configure && make && make install

Windows users can download the extension dll php_memcache.dll here: http://snaps.php.net/win32/PECL_STABLE/.


Tipi di risorse

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.


Costanti predefinite

MEMCACHE_COMPRESSED (integer)

Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().


Esempi

Esempio 2. 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, 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::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_debug -- Turn debug output on/off

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, 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::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);

?>

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

mixed Memcache::get ( string key)

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

?>

Memcache::get() returns FALSE on failure.

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

memcache_debug

(no version information, might be only in CVS)

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.

LX. 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_MD5

  • MHASH_SHA1

  • MHASH_HAVAL256

  • MHASH_HAVAL192

  • MHASH_HAVAL160

  • MHASH_HAVAL128

  • MHASH_RIPEMD160

  • MHASH_GOST

  • MHASH_TIGER

  • MHASH_CRC32

  • MHASH_CRC32B


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

The above example will print out:

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.

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

NameDefaultChangeable
mime_magic.magicfile"/usr/share/misc/magic.mime"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


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

The above example will output:

image/gif
text/plain

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

NomeDefaultModificabile
mssql.allow_persistent"1"PHP_INI_SYSTEM
mssql.max_persistent"-1"PHP_INI_SYSTEM
mssql.max_links"-1"PHP_INI_SYSTEM
mssql.min_error_severity"10"PHP_INI_ALL
mssql.min_message_severity"10"PHP_INI_ALL
mssql.compatability_mode"0"PHP_INI_ALL
mssql.connect_timeout"5"PHP_INI_ALL
mssql.timeout"60"PHP_INI_ALL
mssql.textsize"-1"PHP_INI_ALL
mssql.textlimit"-1"PHP_INI_ALL
mssql.batchsize"0"PHP_INI_ALL
mssql.datetimeconvert"1"PHP_INI_ALL
mssql.secure_connection"0"PHP_INI_SYSTEM
mssql.max_procs"25"PHP_INI_ALL
Per maggiori dettagli sulle 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.

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

int mssql_connect ( [string nome_server [, string nome_utente [, string password]]])

Restituisce: un identificativo di connessione su l'operazione riesce, oppure falso 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.

Vedere anche mssql_data_seek().

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.

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

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.

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

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

new 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

int 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

int 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

new swfbitmap ( string filename [, int alphafilename])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 named filename. alphafilename indicates a MSK file to be used as an alpha mask for a Jpeg image.

Nota: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

Esempio 1. Import PNG files

<?php
  $s = new SWFShape();
  $f = $s->addFill(new SWFBitmap("png.dbl"));
  $s->setRightFill($f);

  $s->drawLine(32, 0);
  $s->drawLine(0, 32);
  $s->drawLine(-32, 0);
  $s->drawLine(0, -32);

  $m = new SWFMovie();
  $m->setDimension(32, 32);
  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

And you can put an alpha mask on a jpeg fill.

Esempio 2. swfbitmap() example

<?php

  $s = new SWFShape();

  // .msk file generated with "gif2mask" utility
  $f = $s->addFill(new SWFBitmap("alphafill.jpg", "alphafill.msk"));
  $s->setRightFill($f);

  $s->drawLine(640, 0);
  $s->drawLine(0, 480);
  $s->drawLine(-640, 0);
  $s->drawLine(0, -480);

  $c = new SWFShape();
  $c->setRightFill($c->addFill(0x99, 0x99, 0x99));
  $c->drawLine(40, 0);
  $c->drawLine(0, 40);
  $c->drawLine(-40, 0);
  $c->drawLine(0, -40);

  $m = new SWFMovie();
  $m->setDimension(640, 480);
  $m->setBackground(0xcc, 0xcc, 0xcc);

  // draw checkerboard background
  for ($y=0; $y<480; $y+=40) {
    for ($x=0; $x<640; $x+=80) {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }

    $y+=40;

    for ($x=40; $x<640; $x+=80) {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }
  }

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

swfbutton_keypress

(PHP 4 >= 4.0.5)

swfbutton_keypress --  Returns the action flag for keyPress(char)

Description

int swfbutton_keypress ( string str)

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

new 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 atmospher to Halloween (use a landscape or bright picture).

Esempio 1. swfdisplayitem->multcolor() example

<?php

  $b = new SWFBitmap("backyard.jpg");
  // note use your own picture :-)
  $s = new SWFShape();
  $s->setRightFill($s->addFill($b));
  $s->drawLine($b->getWidth(), 0);
  $s->drawLine(0, $b->getHeight());
  $s->drawLine(-$b->getWidth(), 0);
  $s->drawLine(0, -$b->getHeight());

  $m = new SWFMovie();
  $m->setDimension($b->getWidth(), $b->getHeight());

  $i = $m->add($s);

  for ($n=0; $n<=20; ++$n) {
    $i->multColor(1.0-$n/10, 1.0, 1.0);
    $i->addColor(0xff*$n/20, 0, 0);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->remove

(no version information, might be only in CVS)

SWFDisplayItem->remove -- Removes the object from the movie

Description

void swfdisplayitem->remove ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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->rotate() 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

new 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

new 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

int 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

new 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

new 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

new 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 ( string mp3FileName)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 mp3FileName. Not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it). Like swfshape->addjpegfill(), this isn't a stable function- we'll probably need to make a separate SWFSound object to contain sound types.

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Yes, now you can use ming to put that rock and roll devil worship music into your SWF files. Just don't tell the RIAA.

Esempio 1. swfmovie->streammp3() example

<?php
  $m = new SWFMovie();
  $m->setRate(12.0);
  $m->streamMp3("distortobass.mp3");
  // use your own MP3

  // 11.85 seconds at 12.0 fps = 142 frames
  $m->setFrames(142);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMovie

(PHP 4 >= 4.0.5)

SWFMovie -- Creates a new movie object, representing an SWF version 4 movie.

Description

new swfmovie ( void )

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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

void swfshape->addfill ( 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.

void swfshape->addfill ( SWFbitmap bitmap [, 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.

void 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 or SWFFILL_TILED_BITMAP. Default is SWFFILL_TILED_BITMAP. I think.

The gradient argument is an swfgradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

swfshape->addfill() returns an swffill() object for use with the swfshape->setleftfill() and swfshape->setrightfill() functions described below.

See also swfshape->setleftfill() and swfshape->setrightfill().

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

Esempio 1. swfshape->addfill() example

<?php

  $p = new SWFMorph();

  $b = new SWFBitmap("alphafill.jpg");
  // use your own bitmap
  $width = $b->getWidth();
  $height = $b->getHeight();

  $s = $p->getShape1();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);
  $f->moveTo(-$width/2, -$height/4);
  $f->scaleTo(1.0, 0.5);
  $s->setLeftFill($f);
  $s->movePenTo(-$width/2, -$height/4);
  $s->drawLine($width, 0);
  $s->drawLine(0, $height/2);
  $s->drawLine(-$width, 0);
  $s->drawLine(0, -$height/2);

  $s = $p->getShape2();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);

  // these two have no effect!
  $f->moveTo(-$width/4, -$height/2);
  $f->scaleTo(0.5, 1.0);

  $s->setLeftFill($f);
  $s->movePenTo(-$width/4, -$height/2);
  $s->drawLine($width/2, 0);
  $s->drawLine(0, $height);
  $s->drawLine(-$width/2, 0);
  $s->drawLine(0, -$height);

  $m = new SWFMovie();
  $m->setDimension($width, $height);
  $i = $m->add($p);
  $i->moveTo($width/2, $height/2);

  for ($n=0; $n<1.001; $n+=0.03) {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFShape->drawCurve

(no version information, might be only in CVS)

SWFShape->drawCurve -- Draws a curve (relative).

Description

void swfshape->drawcurve ( int controldx, int controldy, int anchordx, int anchordy)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().

SWFShape->drawCurveTo

(no version information, might be only in CVS)

SWFShape->drawCurveTo -- Draws a curve.

Description

void swfshape->drawcurveto ( int controlx, int controly, int anchorx, int anchory)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.

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

swfshape->setline() accepts 1, 4 or 5 arguments (not 3 or 2).

You must declare all line styles before you use them (see example).

This simple example will draw a big "!#%*@", in funny colors and gracious style.

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

new 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

new 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

void 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

new 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

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

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

NameDefaultChangeable
ignore_user_abort"0"PHP_INI_ALL
highlight.string#DD0000PHP_INI_ALL
highlight.comment#FF9900PHP_INI_ALL
highlight.keyword#007700PHP_INI_ALL
highlight.bg#FFFFFFPHP_INI_ALL
highlight.default#0000BBPHP_INI_ALL
highlight.html#000000PHP_INI_ALL
browscapNULLPHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

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)

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
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 syntax of the specified file
php_strip_whitespace --  Return source with stripped comments and whitespace
show_source -- Alias of highlight_file()
sleep -- Delay execution
time_nanosleep --  Delay for a number of seconds and nano seconds
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.

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.

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

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. In PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. 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";
?>

The above example will show:

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

object get_browser ( [string user_agent])

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 $_SERVER["HTTP_USER_AGENT"] 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().

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.

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.

The following example shows how one might list all available information retrieved about the user's browser.

Esempio 1. get_browser() example

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "<hr />\n";

$browser = get_browser();

foreach ($browser as $name => $value) {
    echo "<b>$name</b> $value <br />\n";
}

?>

The output of the above script would look something like this:

Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr />
<b>browser_name_pattern:</b> Mozilla/4\.5.*<br />
<b>parent:</b> Netscape 4.0<br />
<b>platform:</b> Linux<br />
<b>majorver:</b> 4<br />
<b>minorver:</b> 5<br />
<b>browser:</b> Netscape<br />
<b>version:</b> 4<br />
<b>frames:</b> 1<br />
<b>tables:</b> 1<br />
<b>cookies:</b> 1<br />
<b>backgroundsounds:</b> <br />
<b>vbscript:</b> <br />
<b>javascript:</b> 1<br />
<b>javaapplets:</b> 1<br />
<b>activexcontrols:</b> <br />
<b>beta:</b> <br />
<b>crawler:</b> <br />
<b>authenticodeupdate:</b> <br />
<b>msn:</b> <br />

In order for this to work, your browscap configuration 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 browscap.ini file here. By default, the browscap directive is commented out.

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: On versions older than PHP 4.0.6, you will have to pass the user agent in via the optional user_agent parameter if the PHP directive register_globals is off. In this case, you will pass in $HTTP_SERVER_VARS['HTTP_USER_AGENT'].

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

Attenzione

Care should be taken when using the show_source() and highlight_file() functions 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.

Nota: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.

To setup a URL that can code hightlight any script that you pass to it, we will make use of the "ForceType" directive in Apache to generate a nice URL pattern, and use the function highlight_file() to show a nice looking code list.

In your httpd.conf you can add the following:

Esempio 1. Creating a source highlighting URL

<Location /source>
    ForceType application/x-httpd-php
</Location>

And then make a file named source and put it in your web root directory.

<html>
<head>
<title>Source Display</title>
</head>
<body bgcolor="white">
<?php
    $script = getenv("PATH_TRANSLATED");
    if (!$script) {
        echo "<br /><b>ERROR: Script Name needed</b><br />";
    } else {
        if (ereg("(\\.php|\\.inc)$", $script)) {
            echo "<h1>Source of: " . getenv("PATH_INFO") . "</h1>\n<hr />\n";
            highlight_file($script);
        } else {
            echo "<h1>ERROR: Only PHP or include script names are allowed</h1>"; 
        }
    }
    echo "<hr />Processed: " . date("Y/M/d H:i:s", time());
?>
</BODY>
</HTML>

Then you can use a URL like the one below to display a colorized version of a script located in "/path/to/script.php" in your web site.

http://www.example.com/source/path/to/script.php

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

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)

php_check_syntax --  Check the syntax of the specified file

Description

bool php_check_syntax ( string file_name [, string error_message])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

php_strip_whitespace

(PHP 5)

php_strip_whitespace --  Return source with stripped comments and whitespace

Description

string php_strip_whitespace ( string file_name)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

show_source

show_source -- Alias of highlight_file()

Description

This function is an alias of highlight_file().

sleep

(PHP 3, PHP 4 , PHP 5)

sleep -- Delay execution

Description

void 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 nano seconds

Description

mixed time_nanosleep ( int seconds, int nanoseconds)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

uniqid

(PHP 3, PHP 4 , PHP 5)

uniqid -- Generate a unique ID

Description

string uniqid ( string prefix [, bool lcg])

uniqid() returns a prefixed unique identifier based on the current time in microseconds. The prefix can be useful for instance if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Prefix can be up to 114 characters long.

If the optional lcg parameter is TRUE, uniqid() will add additional "combined LCG" entropy 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 lcg is TRUE, it will be 23 characters.

Nota: The lcg parameter is only available in PHP 4 and PHP 3.0.13 and later.

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

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

Nota: Questo modulo non è disponibile su piattaforme Windows.


Requisiti

Download mnoGosearch from http://www.mnogosearch.ru/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.


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)

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)

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)

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)

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)

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)

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)

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, PHP 5)

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)

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, PHP 5)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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, PHP 5)

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)

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.

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

NameDefaultChangeable
msql.allow_persistent"On"PHP_INI_SYSTEM
msql.max_persistent"-1"PHP_INI_SYSTEM
msql.max_links"-1"PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

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')
    or die('Could not select database', $link);

/* 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 of msql_create_db()
msql_data_seek -- Move internal row pointer
msql -- Send mSQL query
msql_dbname -- Alias of 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 field name
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

Description

int msql_affected_rows ( resource query_identifier)

Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).

See also: msql_query().

msql_close

(PHP 3, PHP 4 , PHP 5)

msql_close -- Close mSQL connection

Description

int msql_close ( [resource link_identifier])

msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

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.

msql_close() will not close persistent links generated by msql_pconnect().

See also: msql_connect() and msql_pconnect().

msql_connect

(PHP 3, PHP 4 , PHP 5)

msql_connect -- Open mSQL connection

Description

int msql_connect ( [string hostname [, string username [, string password]]])

msql_connect() establishes a connection to a mSQL server. The hostname parameter can also include a port number. e.g. "hostname:port". It defaults to 'localhost'.

Returns a positive mSQL link identifier on success, or FALSE on error.

In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().

See also msql_pconnect() and msql_close().

msql_create_db

(PHP 3, PHP 4 , PHP 5)

msql_create_db -- Create mSQL database

Description

bool msql_create_db ( string database_name [, resource link_identifier])

msql_create_db() attempts to create a new database on the server associated with the specified link_identifier.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also msql_drop_db().

msql_createdb

msql_createdb -- Alias of msql_create_db()

Description

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

Description

bool msql_data_seek ( resource query_identifier, 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.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also msql_fetch_row().

msql

(PHP 3, PHP 4 , PHP 5)

msql -- Send mSQL query

Description

resouce msql_db_query ( string database, string query [, resource link_identifier])

Returns a positive mSQL query identifier to the query result, or FALSE on error.

msql_db_query() selects a database and executes a query on it. If the optional link_identifier is not specified, the function will try to find an open link to the mSQL server; if no such link is found it will try to create one as if msql_connect() was called with no arguments.

See also msql_connect().

msql_dbname

msql_dbname -- Alias of msql_result()

Description

This function is an alias of msql_result().

msql_drop_db

(PHP 3, PHP 4 , PHP 5)

msql_drop_db -- Drop (delete) mSQL database

Description

int msql_drop_db ( string database_name [, resource link_identifier])

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

See also: msql_create_db().

msql_error

(PHP 3, PHP 4 , PHP 5)

msql_error -- Returns error message of last msql call

Description

string msql_error ( [resource link_identifier])

msql_error() returns the last issued error by the mSQL server or an empty string if no error was issued. If no link is explicitly passed, the last successful open link will be used to retrieve the error message. Note that only the last error message is accessible with msql_error().

msql_fetch_array

(PHP 3, PHP 4 , PHP 5)

msql_fetch_array -- Fetch row as array

Description

int msql_fetch_array ( int query_identifier [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

The second optional argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.

Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of 0 (or an empty string, or NULL).

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

See also msql_fetch_row() and msql_fetch_object().

msql_fetch_field

(PHP 3, PHP 4 , PHP 5)

msql_fetch_field -- Get field information

Description

object msql_fetch_field ( resource query_identifier, int field_offset)

Returns an object containing field information

msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • not_null - 1 if the column cannot be NULL

  • primary_key - 1 if the column is a primary key

  • unique - 1 if the column is a unique key

  • type - the type of the column

See also msql_field_seek().

msql_fetch_object

(PHP 3, PHP 4 , PHP 5)

msql_fetch_object -- Fetch row as object

Description

int msql_fetch_object ( int query_identifier)

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

See also: msql_fetch_array() and msql_fetch_row().

msql_fetch_row

(PHP 3, PHP 4 , PHP 5)

msql_fetch_row -- Get row as enumerated array

Description

array msql_fetch_row ( resource query_identifier)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().

msql_field_flags

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

msql_field_flags -- Get field flags

Description

string msql_field_flags ( resource query_identifier, int field_offset)

msql_field_flags() returns the field flags of the specified field. Currently this is either, "not NULL", "primary key", a combination of the two or "" (an empty string).

msql_field_len

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

msql_field_len -- Get field length

Description

int msql_field_len ( resource query_identifier, int field_offset)

msql_field_len() 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 field name

Description

string msql_field_name ( resource query_identifier, int field)

msql_field_name() returns the name of the specified field from the result resource query_identifier. msql_field_name($result, 2); will return the name of the second field in the result set associated with the result identifier.

msql_field_seek

(PHP 3, PHP 4 , PHP 5)

msql_field_seek -- Set field offset

Description

int msql_field_seek ( int query_identifier, int field_offset)

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

This function returns FALSE on failure.

See also: msql_fetch_field().

msql_field_table

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

msql_field_table -- Get table name for field

Description

int msql_field_table ( int query_identifier, int field)

Returns the name of the table field was fetched from.

This function returns FALSE on failure.

msql_field_type

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

msql_field_type -- Get field type

Description

string msql_field_type ( resource query_identifier, int field_offset)

msql_field_type() is similar to the msql_field_name() function. The arguments are identical, but the field type is returned. This will be one of "int", "char" or "real".

This function returns FALSE on failure.

msql_fieldflags

msql_fieldflags -- Alias of msql_field_flags()

Description

This function is an alias of msql_field_flags().

msql_fieldlen

msql_fieldlen -- Alias of msql_field_len()

Description

This function is an alias of msql_field_len().

msql_fieldname

msql_fieldname -- Alias of msql_field_name()

Description

This function is an alias of msql_field_name().

msql_fieldtable

msql_fieldtable -- Alias of msql_field_table()

Description

This function is an alias of msql_field_table().

msql_fieldtype

msql_fieldtype -- Alias of msql_field_type()

Description

This function is an alias of msql_field_type().

msql_free_result

(PHP 3, PHP 4 , PHP 5)

msql_free_result -- Free result memory

Description

int msql_free_result ( resource query_identifier)

msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

For downward compatibility, the alias named msql_freeresult() may be used. This, however, is deprecated and not recommended.

msql_list_dbs

(PHP 3, PHP 4 , PHP 5)

msql_list_dbs -- List mSQL databases on server

Description

resource msql_list_dbs ( [resource link_identifier])

msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_result() function to traverse this result pointer.

For downward compatibility, the alias named msql_listtables() may be used. This, however, is deprecated and not recommended.

msql_list_fields

(PHP 3, PHP 4 , PHP 5)

msql_list_fields -- List result fields

Description

resource msql_list_fields ( string database, string tablename [, resource link_identifier])

msql_list_fields() retrieves information about the given tablename. The returned result set can be traversed with any function that fetches result sets, such as msql_fetch_array().

This function returns FALSE on failure.

For downward compatibility, the alias named msql_listfields() may be used. This, however, is deprecated and not recommended.

msql_list_tables

(PHP 3, PHP 4 , PHP 5)

msql_list_tables -- List tables in an mSQL database

Description

resource msql_list_tables ( string database [, resource link_identifier])

msql_list_tables() lists the tables on the specified database. It returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array().

This function returns FALSE on failure.

For downward compatibility, the alias named msql_listtables() may be used. This, however, is deprecated and not recommended.

msql_num_fields

(PHP 3, PHP 4 , PHP 5)

msql_num_fields -- Get number of fields in result

Description

int msql_num_fields ( resource query_identifier)

msql_num_fields() returns the number of fields in a result set.

For downwards compatability, the alias named msql_numfields() may be used. This, however, is deprecated and not recommended.

See also: msql_query(), msql_fetch_field(), and msql_num_rows().

msql_num_rows

(PHP 3, PHP 4 , PHP 5)

msql_num_rows -- Get number of rows in result

Description

int msql_num_rows ( resource query_identifier)

msql_num_rows() returns the number of rows in a result set.

For downwards compatability, the alias named msql_numrows() may be used. This, however is deprecated and not recommended.

See also: msql_db_query() and msql_query().

msql_numfields

msql_numfields -- Alias of msql_num_fields()

Description

This function is an alias of msql_num_fields().

msql_numrows

msql_numrows -- Alias of msql_num_rows()

Description

This function is an alias of msql_num_rows().

msql_pconnect

(PHP 3, PHP 4 , PHP 5)

msql_pconnect -- Open persistent mSQL connection

Description

int msql_pconnect ( [string server [, string username [, string password]]])

msql_pconnect() acts very much like msql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).

Returns a positive mSQL persistent link identifier on success, or FALSE on error.

msql_query

(PHP 3, PHP 4 , PHP 5)

msql_query -- Send mSQL query

Description

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. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if msql_connect() was called, and use it.

Returns a positive mSQL query identifier on success, or FALSE on error.

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

See also msql_db_query(), msql_select_db(), and msql_connect().

msql_regcase

msql_regcase -- Alias of sql_regcase()

Description

This function is an alias of sql_regcase().

msql_result

(PHP 3, PHP 4 , PHP 5)

msql_result -- Get result data

Description

string msql_result ( resource query_identifier, int row [, mixed field])

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they are often much quicker than msql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().

For downward compatibility, the aliases named msql(), msql_tablename(), and msql_dbname() may be used. This, however, is deprecated and not recommended.

msql_select_db

(PHP 3, PHP 4 , PHP 5)

msql_select_db -- Select mSQL database

Description

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. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if msql_connect() was called, and use it.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Subsequent calls to msql_query() will be made on the active database.

For downward compatibility, the alias named msql_selectdb() may be used. This, however, is deprecated and not recommended.

See also msql_connect(), msql_pconnect(), and msql_query().

msql_tablename

msql_tablename -- Alias of msql_result()

Description

This function is an alias of msql_result().

msql

msql -- Alias of msql_db_query()

Description

This function is an alias of msql_db_query().

LXVII. 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. Se si usa questa opzione senza specificare il percorso a MySQL, PHP userà le librerie client MySQL interne. Con PHP 4, il supporto a MySQL è sempre abilitato; se non si specifica l'opzione di configurazione, vengono usate le librerie incluse. Gli utenti che eseguono altre applicazioni che usano MySQL (ad esempio, usando PHP 3 e PHP 4 come moduli concorrenti di Apache oppure auth-mysql) dovrebbere specificare sempre il percorso a MySQL: --with-mysql=/percorso/a/mysql. Questo forzerà PHP ad usare le librerie client installate da MySQL evitando ogni conflitto.

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.

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.


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

Qui c'è una breve spiegazione delle direttive 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");
    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");

    /* Stampa dei risultati in HTML */
    print "<table>\n";
    while ($linea = mysql_fetch_array($risultato, MYSQL_ASSOC)) {
        print "\t<tr>\n";
        foreach ($linea as $valore_colonna) {
            print "\t\t<td>$valore_colonna</td>\n";
        }
        print "\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 errore_mysql ( [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().

LXVIII. Improved MySQL 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.2 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

NameDefaultChangeable
mysqli.max_links"-1"PHP_INI_SYSTEM
mysqli.default_portNULLPHP_INI_ALL
mysqli.default_socketNULLPHP_INI_ALL
mysqli.default_hostNULLPHP_INI_ALL
mysqli.default_userNULLPHP_INI_ALL
mysqli.default_pwNULLPHP_INI_ALL

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

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

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

  • 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

  • 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

  • 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


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à


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

Examples

All Examples in the MySQLI documentation use the world database from MySQL AB. The world database can be found at http://www.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 -- 
mysqli_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 -- 
mysqli_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 an object 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 -- 
mysqli_rpl_probe -- 
mysqli_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 -- 
mysqli_server_end -- 
mysqli_server_init -- Initialize embedded server.
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:

mixed mysqli_affected_rows ( object link)

Object oriented style (property):

class mysqli {

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

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

Example

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

The above examples would produce the following output:

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->auto_commit -- Turns on or off auto-commiting database modifications

Description

Procedural style:

bool mysqli_autocommit ( object link, bool mode)

Object oriented style (method)

class mysqli {

bool auto_commit ( 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'.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

Autocommit is 1

mysqli_bind_param

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.

mysqli_bind_result

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

Return Values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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

Return values

The default character set for the current connection

Example

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

The above examples would be produce the following output:

Current character set is latin1_swedish_ci

mysqli_client_encoding

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

See also

mysqli_client_encoding(). mysqli_real_escape_string().

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

Return values

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

Object oriented style (method)

class mysqli {

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.

Examples

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.

Return values

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Example

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.

Return values

A string that describes the error. An empty string if no error occurred.

Example

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

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

Return values

Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.

Example

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

The above examples would produce the following output:

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 ( object result, int offset)

Object oriented style (method):

class 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 unbuffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

City: Benin City  Countrycode: NGA

mysqli_debug

(PHP 5)

mysqli_debug -- Performs debugging operations

Description

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

Return values

mysqli_debug() doesn't return any value.

Example

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

Description

void mysqli_disable_reads_from_master ( resource link)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

mysqli_disable_rpl_parse

(PHP 5)

mysqli_disable_rpl_parse -- 

Description

void mysqli_disable_rpl_parse ( object link)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

This function is designed to be executed by an user with the SUPER privlege and is used to dump debugging information into the log for the MySQL Server relating to the connection specified by the link parameter.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also

mysqli_debug().

mysqli_embedded_connect

(PHP 5)

mysqli_embedded_connect -- Open a connection to an embedded mysql server.

Description

object mysqli_embedded_connect ( 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.

mysqli_enable_reads_from_master

(PHP 5)

mysqli_enable_reads_from_master -- 

Description

void mysqli_enable_reads_from_master ( object link)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

mysqli_enable_rpl_parse

(PHP 5)

mysqli_enable_rpl_parse -- 

Description

void mysqli_enable_rpl_parse ( object link)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

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

The above examples would produce the following output:

Errorcode: 1193

mysqli_error

(PHP 5)

mysqli_error -- Returns a string description of the last error

Description

Procedural style:

string mysqli_error ( object 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.

Return values

A string that describes the error. An empty string if no error occurred.

Example

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

The above examples would produce the following output:

Errormessage: Unknown system variable 'a'

mysqli_escape_string

mysqli_escape_string -- Alias of mysqli_real_escape_string()

Description

This function is an alias of mysqli_real_escape_string().

mysqli_execute

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.

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 ( object result [, int resulttype])

Object oriend 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.

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.

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.

Return values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Example

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

The above examples would produce the following output:

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

Object oriend 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 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.

Return values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Example

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

The above examples would produce the following output:

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:

mixed mysqli_fetch_field_direct ( object result, int fieldnr)

Object oriented style (method):

class result {

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

Return values

Returns an object 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
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)

Example

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

The above examples would produce the following output:

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:

mixed mysqli_fetch_field ( object result)

Object oriented style (method):

class result {

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

Return values

Returns an object which contains field definition informations 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)

Example

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

The above examples would produce the following output:

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:

mixed mysqli_fetch_fields ( object result)

Object oriented style (method):

class result {

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

Return values

Returns an array of objects which contains field definition informations 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)

Example

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

    for ($i=0; $i < count($finfo); $i++) { 
        printf("Name:     %s\n", $finfo[$i]->name);
        printf("Table:    %s\n", $finfo[$i]->table);
        printf("max. Len: %d\n", $finfo[$i]->max_length);
        printf("Flags:    %d\n", $finfo[$i]->flags);
        printf("Type:     %d\n\n", $finfo[$i]->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);
 
    for ($i=0; $i < count($finfo); $i++) { 
        printf("Name:     %s\n", $finfo[$i]->name);
        printf("Table:    %s\n", $finfo[$i]->table);
        printf("max. Len: %d\n", $finfo[$i]->max_length);
        printf("Flags:    %d\n", $finfo[$i]->flags);
        printf("Type:     %d\n\n", $finfo[$i]->type);
    }    
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples would produce the following output:

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:

mixed mysqli_fetch_lengths ( object result)

Object oriented style (property):

class result {

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

Return values

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.

Example

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 */
    for ($i=0; $i < count($result->lengths); $i++) {
        printf("Field %2d has Length %2d\n", $i+1, $result->lengths[$i]);
    }
    $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 */
    $lengths = mysqli_fetch_lengths($result);
    for ($i=0; $i < count($lengths); $i++) {
        printf("Field %2d has Length %2d\n", $i+1, $lengths[$i]);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples would produce the following output:

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

Object oriented style (method):

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

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.

Example

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

The above examples would produce the following output:

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

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.

Return values

mysqli_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Example

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

The above examples would produce the following output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

mysqli_fetch

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.

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

Object oriented style (method):

class mysql {

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.

Return values

An integer representing the number of fields in a result set

Example

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:

int mysqli_field_seek ( object result, int fieldnr)

Object oriented style (method):

class result {

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

Return values

mysqli_field_seek() returns previuos value of field cursor.

Example

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

The above examples would produce the following output:

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

Object oriented style (property):

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

Example

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

The above examples would produce the following output:

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

Object oriented style (method):

class 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

Example

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.

Return values

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.

Example

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

Example

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

The above examples would produce the following output:

Host info: Localhost via UNIX socket

mysqli_get_metadata

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

Example

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

The above examples would produce the following output:

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

Example

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

The above examples would produce the following output:

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

Example

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

The above examples would produce the following output:

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

Example

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

The above examples would produce the following output:

Records: 150  Duplicates: 0  Warnings: 0

mysqli_init

(PHP 5)

mysqli_init --  Initializes MySQLi and returns an object for use with mysqli_real_connect

Description

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

mixed mysqli_insert_id ( object link)

Object oriented style (property):

class mysqli {

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

Example

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

The above examples would produce the following output:

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

Example

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

The above examples would produce the following output:

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 ( object link, string query)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

mysqli_more_results() indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Return values

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

See mysqli_multi_query().

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

Object oriented style (property):

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

Example

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

The above examples would produce the following output:

Result set has 5 fields.

mysqli_num_rows

(PHP 5)

mysqli_num_rows --  Gets the number of rows in a result

Description

Procedural style:

mixed mysqli_num_rows ( object result)

Object oriented style (property):

class mysqli {

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

Example

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

The above examples would produce the following output:

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 ( object 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_COMPRESSuse compression protocol
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

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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:

mixed mysqli_prepare ( object link, string query)

Object oriented style (method)

class stmt {

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

Example

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

The above examples would produce the following output:

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 ( object link, string query [, int resultmode])

Object oriented style (method):

class mysqli {

mixed query ( string query)

}

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

Example

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

The above examples would produce the following output:

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

Example

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

The above examples would produce the following output:

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 ( object link, string escapestr)

Object oriented style (method):

class mysqli {

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 NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return values

Returns an escaped string.

Example

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

The above examples would produce the following output:

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

Return values

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)

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

class mysqli {

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

The above examples would produce the following output:

0 rows in table myCity.
50 rows in table myCity (after rollback).

mysqli_rpl_parse_enabled

(PHP 5)

mysqli_rpl_parse_enabled -- 

Description

int mysqli_rpl_parse_enabled ( object link)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

mysqli_rpl_probe

(PHP 5)

mysqli_rpl_probe -- 

Description

bool mysqli_rpl_probe ( object link)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

mysqli_rpl_query_type

(PHP 5)

mysqli_rpl_query_type -- 

Description

int mysqli_rpl_query_type ( string query)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

Default database is test.
Default database is world.

mysqli_send_long_data

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

Description

bool mysqli_send_query ( resource link, string query)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

mysqli_server_end

(PHP 5)

mysqli_server_end -- 

Description

void mysqli_server_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.

mysqli_server_init

(PHP 5)

mysqli_server_init -- Initialize embedded server.

Description

bool mysqli_server_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.

mysqli_set_opt

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 ( object 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-returns.html.

Nota: Note that not all MySQL 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
$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);
?>

The above examples would produce the following output:

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

Return values

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:

mixed mysqli_stat ( object link)

Object oriented style (method):

class mysqli {

mixed mysqli->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.

Return values

A string describing the server status. FALSE if an error occurred.

Example

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

The above examples would produce the following output:

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 :

mixed mysqli_stmt_affected_rows ( object stmt)

Object oriented style (property):

class stmt {

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

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.

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.

Example

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

The above examples would produce the following output:

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 ( object stmt, string types, mixed var1 [, mixed var2, ...])

Object oriented style (method):

class stmt {

bool bind_param ( array types, mixed var1 [, mixed var2, ...])

}

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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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_stnt_bind_result ( object stmt, mixed var1 [, mixed var2, ...])

Object oriented style (method):

class stmt {

bool bind_result ( mixed var1 [, mixed var2, ...])

}

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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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

Object oriented style (method):

class mysqli_stmt {

bool mysqli_stmt->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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also

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:

bool mysqli_stmt_data_seek ( object statement, int offset)

Object oriented style (method):

class stmt {

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

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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

Object oriented style (property):

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

Return values

An error code value. Zero means no error occurred.

Example

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

The above examples would produce the following output:

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

Object oriented style (property):

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

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 */
$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);
?>

The above examples would produce the following output:

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

Object oriented style (method):

class 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_fetch() function is used.

Nota: When using mysqli_stmt_execute(), the mysqli_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
$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); 
?>

The above examples would produce the following output:

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:

mixed mysqli_stmt_fetch ( object stmt)

Object oriented style (method):

class stmt {

mixed fetch ( void )

}

mysqli_stmt_fetch() returns row data using the variables bound by mysqli_stmt_bind_result().

Nota: Note that all columns must be bound by the application before calling mysqli_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
$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);
?>

The above examples would produce the following output:

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

Object oriented style (method):

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

object mysqli_stmt_init ( object link)

Object oriented style (property):

class mysqli {

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

mixed mysqli_stmt_num_rows ( object stmt)

Object oriented style (property):

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

Return values

An integer representing the number of rows in result set.

Example

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

The above examples would produce the following output:

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

Object oriented style (property):

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

Example

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

The above examples would produce the following output:

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 ( object stmt, string query)

Object oriented style (method)

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

Example

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

The above examples would produce the following output:

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

Object oriented style (method):

class 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 reprepare a statement with an other query use function mysqli_stmt_prepare().

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysqli_stmt_result_metadata

(PHP 5)

mysqli_stmt_result_metadata -- returns result set metadata from a prepared statement

Description

Procedural style:

mixed mysqli_stmt_result_metadata ( object stmt)

Object oriented style (method):

class stmt {

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

Valori restituiti

mysqli_stmt_result_metadata() returns a result object or FALSE if an error occured.

Example

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 ( object 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), 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 ( object 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-returns.html.

Nota: Note that not all MySQL 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 */
$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);
?>

The above examples would produce the following output:

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 ( object 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_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.

Return values

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example

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

The above examples would produce the following output:

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:

object mysqli_store_result ( object link)

Object oriented style (method):

class mysqli {

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

Return values

Returns a buffered result object or FALSE if an error occured.

Example

See mysqli_multi_query().

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

Return values

mysqli_thread_id() returns the Thread ID for the current connection.

See also

mysqli_kill()

Example

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

The above examples would produce the following output:

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.

Return values

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:

mixed mysqli_use_result ( object link)

Object oriented style (method):

class mysqli {

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

Return values

Returns an unbuffered result object or FALSE if an error occured.

Example

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

The above examples would produce the following output:

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 ( object 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].

Return values

Number of warnings or zero if there are no warnings.

Example

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

The above examples would produce the following output:

Warning (1264): Data truncated for column 'Name' at row 1

LXIX. 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 value
msession_get_array -- Get array of ... ?
msession_get -- Get value from session
msession_getdata -- Get data ... ?
msession_inc -- Increment value in session
msession_list -- List ... ?
msession_listvar -- List sessions with variable
msession_lock -- Lock a session
msession_plugin -- Call an escape function within the msession personality plugin
msession_randstr -- Get random string
msession_set_array -- Set array of ...
msession_set -- Set value in session
msession_setdata -- Set data ... ?
msession_timeout -- Set/get session timeout
msession_uniq -- Get uniq id
msession_unlock -- Unlock a session

msession_connect

(PHP 4 >= 4.2.0, 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 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 ... ?

Description

array msession_get_array ( 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_getdata

(no version information, might be only in CVS)

msession_getdata -- Get data ... ?

Description

string msession_getdata ( string session)

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

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 array of ...

Description

bool msession_set_array ( string session, array tuples)

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_setdata

(no version information, might be only in CVS)

msession_setdata -- Set data ... ?

Description

bool msession_setdata ( string session, 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 uniq 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.

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

muscat_close -- Shuts down the muscat session and releases any memory back to PHP.

Description

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

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)

muscat_give -- Sends string to the core muscat API

Description

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

muscat_setup_net -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup_net ( string muscat_host, 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.

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)

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.

LXXI. Funzioni di rete

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
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 --  Restituisce informazioni su una risorsa socket esistente
socket_set_blocking -- Imposta un socket in modalità blocking/non-blocking
socket_set_timeout -- Imposta il tempo di timeout per un socket
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

int dns_check_record ( string host [, string type])

Check DNS records corresponding to a given Internet host name or IP address

dns_get_mx

(PHP 5)

dns_get_mx -- Synonym for getmxrr()

Description

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

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

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 --  Restituisce informazioni su una risorsa socket esistente

Descrizione

array socket_get_status ( resource socket_get_status)

Restituisce informazioni su una risorsa socket esistente. Attualmente restituisce quattro campi nell'array risultante:

  • timed_out (bool) - Il socket è andato in time out aspettando i dati

  • blocked (bool) - Il socket è bloccato

  • eof (bool) - Indica l'evento EOF

  • unread_bytes (int) - Numero di byte rimasti nel buffer del socket

Vedere anche: socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_strerror() e la Socket extension.

socket_set_blocking

(PHP 4 , PHP 5)

socket_set_blocking -- Imposta un socket in modalità blocking/non-blocking

Descrizione

int socket_set_blocking ( int descrittore del socket, int modo)

Se modo è FALSE, il dato descrittore del socket verrà cambiato in modalità non-blocking e se TRUE, verrà cambiato in modalità blocking. Questo ha effetti su chiamate tipo quelle di fgets() che leggono dirttamente dal socket. In modo non-blocking una chiamata a fgets() restituirà sempre subito i dati, mentre in modalità blocking, essa attenderà che i dati siano disponibili nel socket.

Questa funzione era precedentemente chiamata set_socket_blocking(), ma questo uso è deprecato.

socket_set_timeout

(PHP 4 , PHP 5)

socket_set_timeout -- Imposta il tempo di timeout per un socket

Descrizione

bool socket_set_timeout ( int descrittore socket, int secondi, int microsecondi)

Imposta il valore di timeout per un descrittore socket, espresso come la somma di secondi e microsecondi.

Esempio 1. Esempio di socket_set_timeout()

<?php
$fp = fsockopen("www.php.net", 80);
if(!$fp) {
    echo "Impossibile aprire\n";
} else {
    fputs($fp,"GET / HTTP/1.0\n\n");
    $start = time();
    socket_set_timeout($fp, 2);
    $res = fread($fp, 2000);
    var_dump(socket_get_status($fp));
    fclose($fp);
    print $res;
}
?>

Questa funzione era precedentemente chiamata set_socket_timeout(), ma questo uso è deprecato.

Vedere anche: fsockopen() e fopen().

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

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

NameDefaultChangeable
ncurses.value"42"PHP_INI_ALL
ncurses.string"foobar"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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 -- 
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. If panel is null, returns the bottom panel in the stack
ncurses_panel_below --  Returns the panel below panel. If panel is null, returns the top panel in the stack
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 -- 
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 -- 
ncurses_slk_attron -- 
ncurses_slk_attrset -- 
ncurses_slk_clear -- Clears soft labels from screen
ncurses_slk_color -- Sets color for soft label keys
ncurses_slk_init -- Initializes soft label key functions
ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen
ncurses_slk_refresh -- Copies soft label keys to screen
ncurses_slk_restore -- Restores soft label keys
ncurses_slk_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 -- 
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

int 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

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

Description

int 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

int 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

bool 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

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

int 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. If panel is null, returns the bottom panel in the stack

Description

int ncurses_panel_above ( resource panel)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_below --  Returns the panel below panel. If panel is null, returns the top panel in the stack

Description

int ncurses_panel_below ( resource panel)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5)

ncurses_panel_window --  Returns the window associated with panel

Description

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

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

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

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

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

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

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

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

LXXIII. 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 rimosso da PHP 5 ed inserito tra le librerie PECL.

Sommario
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_copy_db -- Create a note using form form_name
notes_create_db -- Create a Lotus Notes database
notes_create_note -- Create a note using form form_name
notes_drop_db -- Drop a Lotus Notes database
notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_list_msgs -- Returns the notes from a selected database_name
notes_mark_read -- Mark a note_id as read for the User user_name
notes_mark_unread -- Mark a note_id as unread for the User user_name
notes_nav_create -- Create a navigator name, in database_name
notes_search -- Find notes that match keywords in database_name
notes_unread -- Returns the unread note id's for the current User user_name
notes_version -- Get the version Lotus Notes

notes_body

(PHP 4 >= 4.0.5)

notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string server, string mailbox, int msg_number)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

notes_copy_db -- Create a note using form form_name

Description

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

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)

notes_create_note -- Create a note using form form_name

Description

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

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)

notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla

Description

bool notes_find_note ( string database_name, string name [, string type])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

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)

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)

notes_mark_read -- Mark a note_id as read for the User user_name

Description

string notes_mark_read ( string database_name, string user_name, string note_id)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

notes_mark_unread -- Mark a note_id as unread for the User user_name

Description

string notes_mark_unread ( string database_name, string user_name, string note_id)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

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)

notes_search -- Find notes that match keywords in database_name

Description

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

notes_unread -- Returns the unread note id's for the current User user_name

Description

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

notes_version -- Get the version Lotus Notes

Description

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

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

NameDefaultChangeableFunction
nsapi.read_timeout60PHP_INI_ALLsets 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

Description

array nsapi_request_headers ( void )

nsapi_request_headers() returns an associative array of all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.

Esempio 1. nsapi_request_headers() example

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

Nota: Prior to PHP 4.3.3, getallheaders() was only available for the Apache servers. After PHP 4.3.3, getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.

Nota: You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.

nsapi_response_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_response_headers --  Fetch all HTTP response headers

Description

array nsapi_response_headers ( void )

Returns an array of all NSAPI response headers. This functionality is only available in PHP 4.3.3 and greater.

See also nsapi_request_headers() and headers_sent().

nsapi_virtual

(PHP 4 >= 4.3.3, PHP 5)

nsapi_virtual -- Perform an NSAPI sub-request

Description

int 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 install section if you experience this problem.

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

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

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.

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. La funzione ritorna un identificatore di risultato contenenti le informazioni.
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 --  Restituisce una riga in un array associativo
odbc_fetch_into -- Scarica una riga del risultato della query in un array
odbc_fetch_object --  Restituisce una riga di risultato come un 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. La funzione ritorna un identificatore di risultato che punta alle informazioni reperite.
odbc_result_all -- Visualizza il risultato in una tabella HTML
odbc_result -- Restituisce il contenuto dei campi
odbc_rollback -- Annulla una transazione
odbc_setoption --  Settaggio dei parametri ODBC. Restituisce FALSE se si verifica un errore, altrimenti TRUE.
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. Restituisce l'identificatore di risultato in cui vi sono le informazioni.

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

int 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

int 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. La funzione ritorna un identificatore di risultato contenenti le informazioni.

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

resource odbc_data_source ( resource connection_id, constant fetch_type)

La funzione restituisce FALSE se si verifica un errore, oppure un array se ha successo.

Questa funzione restituisce informazioni sulla connessione attiva ricavando i dati dal DSN. 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.

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.

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)

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 safe mode 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 --  Restituisce una riga in un array associativo

Descrizione

array odbc_fetch_array ( resource resultato [, int numero_riga])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

bool odbc_fetch_into ( resource id_risultato [, int numero_riga, array array_dati])

resource odbc_fetch_into ( resource id_risultato, array array_dati [, int numero_riga])

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 --  Restituisce una riga di risultato come un oggetto

Descrizione

object odbc_fetch_object ( resource risultato [, int NumeroRiga])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

string 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

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

int 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

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

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. La funzione ritorna un identificatore di risultato che punta alle informazioni reperite.

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

int 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 --  Settaggio dei parametri ODBC. Restituisce FALSE se si verifica un errore, altrimenti TRUE.

Descrizione

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

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 il set di colonne ottimali, attraverso cui, ottenendo i valori da dette colonne, è possibile identificare in modo univoco ciascun record della tabella indicata.

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

int 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. Restituisce l'identificatore di risultato in cui vi sono le informazioni.

Descrizione

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

LXXVI. 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 = $_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 proccess of aggregation is cummulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

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 of 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 paramater exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp --  Selective class methods aggregation to an object using a regular expression

Description

void aggregate_methods_by_regexp ( object object, string class_name, string regexp [, bool exclude])

Aggregates methods from a class to an existing object using a regular expresion to match method names. The optional paramater exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods --  Dynamic class and object aggregation of methods

Description

void aggregate_methods ( object object, string class_name)

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_info(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list --  Selective dynamic class properties aggregation to an object

Description

void aggregate_properties_by_list ( object object, string class_name, array properties_list [, bool exclude])

Aggregates properties from a class to an existing object using a list of property names. The optional paramater exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp --  Selective class properties aggregation to an object using a regular expression

Description

void aggregate_properties_by_regexp ( object object, string class_name, string regexp [, bool exclude])

Aggregates properties from a class to an existing object using a regular expresion to match their names. The optional paramater exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_info(), deaggregate()

aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties --  Dynamic aggregation of class properties to an object

Description

void aggregate_properties ( object object, string class_name)

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate

(PHP 4 >= 4.2.0)

aggregate --  Dynamic class and object aggregation of methods and properties

Description

void aggregate ( object object, string class_name)

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

See also aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregation_info

aggregation_info -- Alias of aggregate_info()

Description

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

LXXVII. 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_bind_by_name --  Lega una variabile PHP ad un segnaposto Oracle
oci_cancel -- Interrompe la lettura del cursore
oci_close -- Closes Oracle connection
collection->append -- Appends an object to the collection
collection->assign -- Assigns a value to the collection from another existing collection
collection->assignElem -- Assigns a value to the element of the collection
collection->getElem -- Returns value of the element
collection->max -- Gets the maximum number of elements in the collection
collection->size -- Returns size of the collection
collection->trim -- Trims elements from the end of the collection
oci_commit -- Commits outstanding statements
oci_connect -- Establishes a connection to 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
collection->free -- Frees resources associated with collection object
descriptor->free -- Frees resources associated with descriptor
oci_free_statement --  Frees all resources associated with statement or cursor
oci_internal_debug -- Enables or disables internal debug output
lob->append -- Appends data from the large object to another large object
lob->close -- Closes LOB descriptor
oci_lob_copy -- Copies large object
lob->eof -- Tests for end-of-file on a large object's descriptor
lob->erase -- Erases a specified portion of the internal LOB data
lob->export -- Exports LOB's contents to a file
lob->flush -- Flushes/writes buffer of the LOB to the server
lob->import -- Imports file data to the LOB
oci_lob_is_equal -- Compares two LOB/FILE locators for equality
lob->load -- Returns large object's contents
lob->read -- Reads part of large object
lob->rewind -- Moves the internal pointer to the beginning of the large object
lob->save -- Saves data to the large object
lob->seek -- Sets the internal pointer of the large object
lob->size -- Returns size of large object
lob->tell -- Returns current position of internal pointer of large object
lob->truncate -- Truncates large object
lob->writeTemporary -- Writes temporary large object
lob->write -- Writes data to the large object
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 --  Bind a PHP variable to an Oracle Placeholder
ocicancel -- Interrompe la lettura del cursore
ocicloselob -- Closes lob descriptor
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
lob->getBuffering -- Returns current state of buffering for large object
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
lob->setBuffering -- Changes current state of buffering for large object
ocisetprefetch -- Imposta il numero di tuple da precaricare
ocistatementtype -- Restituisce il tipo di un'istruzione OCI
ociwritelobtofile -- Coming soon
ociwritetemporarylob -- Writes temporary blob

oci_bind_by_name

(PHP 5)

oci_bind_by_name --  Lega una variabile PHP ad un segnaposto Oracle

Descrizione

bool oci_bind_byname ( 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: As non-persistent links are closed automatically at the end of script execution, calling this function is not required. Because of this and the method the extension uses to handle connection resources, oci_close() currently provides no actual functionality.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: In PHP versions before 5.0.0 you must use ociclose() 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.

collection->append

(no version information, might be only in CVS)

collection->append -- Appends an object to the collection

Description

bool collection->append ( mixed value)

Appends an object 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.

collection->assign

(no version information, might be only in CVS)

collection->assign -- Assigns a value to the collection from another existing collection

Description

bool collection->assign ( object 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.

collection->assignElem

(no version information, might be only in CVS)

collection->assignElem -- Assigns a value to the element of the collection

Description

bool collection->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.

collection->getElem

(no version information, might be only in CVS)

collection->getElem -- Returns value of the element

Description

mixed collection->getElem ( int index)

Method collection->getElem() returns value of the element with index index (1-based).

collection->getElem() will return 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.

collection->getElem() will return FALSE in case of error.

collection->max

(no version information, might be only in CVS)

collection->max -- Gets the maximum number of elements in the collection

Description

int collection->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. collection->max() returns FALSE in case of error.

See also oci_collection_size().

collection->size

(no version information, might be only in CVS)

collection->size -- Returns size of the collection

Description

int collection->size ( void )

Returns the number of elements in the collection.

See also oci_collection_max().

collection->trim

(no version information, might be only in CVS)

collection->trim -- Trims elements from the end of the collection

Description

bool collection->trim ( int num)

Trims num of elements from the end of the collection.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also oci_collection_size().

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: 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 Oracle server

Description

resource oci_connect ( string username, string password [, string db [, string charset]])

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.

Nota: oci_connect() does not reestablish the connection, if a connection with such parameters was established before. In this case, oci_connect() will return identifier of previously opened connection. This means, that you cannot use this function to separate transactions. To establish a distinctly new connection, use oci_new_connect().

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 alias of oci_connect() for downwards compatability. This, however, is deprecated and not recommended.

See also oci_pconnect() and oci_new_connect().

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. Be careful that Oracle uses ALL-UPPERCASE column names, whereby in your select you can also write 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 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 ocierror ( [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_parse($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.

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

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";
   while (list($key, $val) = each($results)) {
      echo "<th>$key</th>\n";
   }
   echo "</tr>\n";
   
   for ($i = 0; $i < $nrows; $i++) {
      reset($results);
      echo "<tr>\n";
      while ($column = each($results)) {   
         $data = $column['value'];
         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);
?>

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 is no more rows in the result.

oci_fetch_array() returns an array with both associative and numeric indices.

Optional second paramater 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: Don't forget, that 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
}
?>

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

Subsequent call to oci_fetch_assoc() will return next row or FALSE if there is no more rows.

Nota: Don't forget, that Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.

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.

Subsequent calls to oci_fetch_object() will return the next row from the result or FALSE if there is no more rows.

Nota: Don't forget, that Oracle returns all field names in uppercase and attributes' names in the result object will be in uppercase as well.

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.

Subsequent calls to oci_fetch_row() will return the next row from the result data or FALSE if there is no more rows.

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.

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

collection->free

(no version information, might be only in CVS)

collection->free -- Frees resources associated with collection object

Description

bool collection->free ( void )

Frees resources associated with collection object.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

descriptor->free

(no version information, might be only in CVS)

descriptor->free -- Frees resources associated with descriptor

Description

bool descriptor->free ( void )

descriptor->free() frees resources associated with descriptor, previously allocated with oci_new_descriptor().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

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.

lob->append

(no version information, might be only in CVS)

lob->append -- Appends data from the large object to another large object

Description

bool lob->append ( object lob_from)

Appends data from the large object to the end of another large object.

Writing to the large object with 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.

See also oci_lob_flush(), ocisetbufferinglob() and ocigetbufferinglob().

lob->close

(no version information, might be only in CVS)

lob->close -- Closes LOB descriptor

Description

bool lob->close ( void )

lob->close() closes descriptor of LOB or FILE. This function should be used only with lob->writeTemporary().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: In PHP versions before 5.0.0 you must use ocicloselob() instead. This name still can be used, it was left as alias of oci_lob_close() for downwards compatability. This, however, is deprecated and not recommended.

See also oci_lob_write_temporary().

oci_lob_copy

(PHP 5)

oci_lob_copy -- Copies large object

Description

bool oci_lob_copy ( [int length])

Copies large object or a part of large object to another large object. Parameter length indicates the length of data to be copied. Old data of LOB-recipient will be overwritten.

If you need to copy a particular part of LOB to a particular position of LOB, you can use oci_lob_seek() to move internal pointers of LOBs.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

lob->eof

(no version information, might be only in CVS)

lob->eof -- Tests for end-of-file on a large object's descriptor

Description

bool lob->eof ( void )

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

See also oci_lob_size().

lob->erase

(no version information, might be only in CVS)

lob->erase -- Erases a specified portion of the internal LOB data

Description

int lob->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. 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.

lob->erase() returns the actual number of characters/bytes erased or FALSE in case of error.

lob->export

(no version information, might be only in CVS)

lob->export -- Exports LOB's contents to a file

Description

bool lob->export ( string filename [, int start [, int length]])

Exports LOB's contents to a file, which name is given in parameter filename. Optional parameter start indicates from what position to start export and parameter length - length of data to be exported.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

lob->flush

(no version information, might be only in CVS)

lob->flush -- Flushes/writes buffer of the LOB to the server

Description

bool lob->flush ( [int flag])

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. Tt is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.

lob->flush() returns FALSE if buffering was not enabled or an error occurred.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

lob->import

(no version information, might be only in CVS)

lob->import -- Imports file data to the LOB

Description

bool lob->import ( string filename)

Writes data from filename in to the current position of large object.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: In PHP versions before 5.0.0 you must use ocisavelobfile() instead. This name still can be used, it was left as alias of oci_lob_import() for downwards compatability. This, however, is deprecated and not recommended.

oci_lob_is_equal

(PHP 5)

oci_lob_is_equal -- Compares two LOB/FILE locators for equality

Description

bool oci_lob_is_equal ( object lob1, object lob2)

Compares two LOB/FILE locators. Returns TRUE if these objects are equal and FALSE otherwise.

lob->load

(no version information, might be only in CVS)

lob->load -- Returns large object's contents

Description

string lob->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 lob->load() returns FALSE.

Nota: In PHP versions before 5.0.0 you must use ociloadlob() instead. This name still can be used, it was left as alias of oci_lob_load() for downwards compatability. This, however, is deprecated and not recommended.

lob->read

(no version information, might be only in CVS)

lob->read -- Reads part of large object

Description

string lob->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 large object is reached. Internal pointer of large object will be shifted on the amount of bytes read.

Returns FALSE in case of error.

See also oci_lob_eof(), oci_lob_seek(), oci_lob_tell() and oci_lob_write().

lob->rewind

(no version information, might be only in CVS)

lob->rewind -- Moves the internal pointer to the beginning of the large object

Description

bool lob->rewind ( void )

Sets the internal pointer to the beginning of the large object.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also oci_lob_seek() and oci_lob_tell().

lob->save

(no version information, might be only in CVS)

lob->save -- Saves data to the large object

Description

bool lob->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.

Nota: In PHP versions before 5.0.0 you must use ocisavelob() instead. This name still can be used, it was left as alias of oci_lob_save() for downwards compatability. This, however, is deprecated and not recommended.

See also oci_lob_write() and oci_lob_import().

lob->seek

(no version information, might be only in CVS)

lob->seek -- Sets the internal pointer of the large object

Description

bool lob->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)

See also oci_lob_rewind() and oci_lob_tell().

lob->size

(no version information, might be only in CVS)

lob->size -- Returns size of large object

Description

int lob->size ( void )

Returns length of large object value or FALSE in case of error. Empty objects have zero length.

lob->tell

(no version information, might be only in CVS)

lob->tell -- Returns current position of internal pointer of large object

Description

int lob->tell ( void )

Returns current position of a LOB's internal pointer or FALSE if an error occured.

See also oci_lob_size() and oci_lob_eof().

lob->truncate

(no version information, might be only in CVS)

lob->truncate -- Truncates large object

Description

bool lob->truncate ( [int length])

If parameter length is given, lob->truncate() truncates large object to length bytes. Otherwise, lob->truncate() will purge the LOB completely.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also oci_lob_erase().

lob->writeTemporary

(no version information, might be only in CVS)

lob->writeTemporary -- Writes temporary large object

Description

bool lob->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

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.

Nota: In PHP versions before 5.0.0 you must use ociwritetemporarylob() instead. This name still can be used, it was left as alias of oci_lob_write_temporary() for downwards compatability. This, however, is deprecated and not recommended.

See also oci_lob_close().

lob->write

(no version information, might be only in CVS)

lob->write -- Writes data to the large object

Description

int lob->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.

lob->write() returns the number of bytes written or FALSE in case of error.

See also oci_lob_read().

oci_new_collection

(PHP 5)

oci_new_collection -- Allocates new collection object

Description

object oci_new_collection ( resource connection, string tdo [, string schema])

Allocates new collection object. Parameter tdo should be a valid named type (uppercased). Third, optional parameter schema should point to the scheme, where the named type was created. oci_new_collection() uses name of the current user as 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]])

oci_new_connect() creates a new connection to an Oracle server and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora. 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.

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_new_connect() forces the creation of a new connection. This should be used if you need to isolate a set of transactions. By default, connections are shared and subsequent calls to oci_connect() will return the same connection identifier.

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

object 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_execute($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)

Changes password for user with username. Parameters old_password and new_password should indicate old and new passwords respectively.

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

oci_pconnect() creates a new persistent connection to an Oracle server and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora. 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.

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: Note, that these kind of links only work if you are using a module version of PHP. See the Persistent Database Connections section for more information.

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.

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

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 --  Bind a PHP variable to an Oracle Placeholder

Description

bool ocibindbyname ( resource stmt, string ph_name, mixed &variable [, int maxlength [, int type]])

ocibindbyname() binds the PHP variable variable to the Oracle placeholder ph_name. Whether it will be used for input or output will be determined run-time, and the necessary storage space will be allocated. The length parameter sets the maximum length for the bind. If you set length to -1 ocibindbyname() will use the current length of variable to set the maximum length.

If you need to bind an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using ocinewdescriptor() function. The length is not used for abstract Datatypes and should be set to -1. The type variable tells oracle, what kind of descriptor we want to use. Possible values are: OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID).

Esempio 1. ocibindbyname() example

<?php
/* OCIBindByPos example thies at thieso dot net (980221)
  inserts 3 records into emp, and uses the ROWID for updating the 
  records just after the insert.
*/

$conn = OCILogon("scott", "tiger");

$stmt = OCIParse($conn, "insert into emp (empno, ename) " .
					   "values (:empno,:ename) " .
					   "returning ROWID into :rid");

$data = array(1111 => "Larry", 2222 => "Bill", 3333 => "Jim");

$rowid = OCINewDescriptor($conn, OCI_D_ROWID);

OCIBindByName($stmt, ":empno", $empno, 32);
OCIBindByName($stmt, ":ename", $ename, 32);
OCIBindByName($stmt, ":rid", $rowid, -1, OCI_B_ROWID);

$update = OCIParse($conn, "update emp set sal = :sal where ROWID = :rid");
OCIBindByName($update, ":rid", $rowid, -1, OCI_B_ROWID);
OCIBindByName($update, ":sal", $sal, 32);

$sal = 10000;

while (list($empno, $ename) = each($data)) {
	OCIExecute($stmt);
	OCIExecute($update);
} 

$rowid->free();

OCIFreeStatement($update);
OCIFreeStatement($stmt);

$stmt = OCIParse($conn, "select * from emp where empno in (1111,2222,3333)");
OCIExecute($stmt);
while (OCIFetchInto($stmt, &$arr, OCI_ASSOC)) {
	var_dump($arr);
}
OCIFreeStatement($stmt);

/* delete our "junk" from the emp table.... */
$stmt = OCIParse($conn, "delete from emp where empno in (1111,2222,3333)");
OCIExecute($stmt);
OCIFreeStatement($stmt);

OCILogoff($conn);
?>

Nota: This function was renamed to oci_bind_by_name() after PHP >= 5.0.0. For downward compatibility ocibindbyname() can also be used. This is deprecated, however.

Avvertimento

It is a bad idea to use magic quotes and ocibindbyname() simultaneously as no quoting is needed on quoted variables and any quotes magically applied will be written into your database as ocibindbyname() is not able to distinguish magically added quotings from those added by intention.

ocicancel

(PHP 3>= 3.0.8, PHP 4 , 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 -- Closes lob descriptor

Description

bool ocicloselob ( void )

Nota: This function was renamed to oci_lob_close() after PHP >= 5.0.0. For downward compatibility ocicloselob() can also be used. This is deprecated, however.

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.

lob->getBuffering

(no version information, might be only in CVS)

lob->getBuffering -- Returns current state of buffering for large object

Description

bool lob->getBuffering ( void )

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

See also ocisetbufferinglob().

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

lob->setBuffering

(no version information, might be only in CVS)

lob->setBuffering -- Changes current state of buffering for large object

Description

bool lob->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 perfomance 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.

See also ocigetbufferinglob().

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 -- Writes temporary blob

Description

bool ociwritetemporarylob ( string var [, int lob_type])

Nota: This function was renamed to oci_lob_write_temporary() after PHP >= 5.0.0. For downward compatibility ociwritetemporarylob() can also be used. This is deprecated, however.

LXXVIII. 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 -- Get a private key
openssl_get_publickey -- Extract public key from certificate and prepare it for use
openssl_open -- Open sealed data
openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt -- Encrypt an S/MIME message
openssl_pkcs7_sign -- sign an S/MIME message
openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file
openssl_pkey_export -- Gets an exportable representation of a key into a string
openssl_pkey_get_private -- Get a private key
openssl_pkey_get_public -- Extract public key from certificate and prepare it for use
openssl_pkey_new -- Generates a new private key
openssl_private_decrypt -- Decrypts data with private key
openssl_private_encrypt -- Encrypts data with private key
openssl_public_decrypt -- Decrypts data with public key
openssl_public_encrypt -- Encrypts data with public key
openssl_seal -- Seal (encrypt) data
openssl_sign -- Generate signature
openssl_verify -- Verify signature
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file -- Exports a certificate to file
openssl_x509_export -- Exports a certificate as a string
openssl_x509_free -- Free certificate resource
openssl_x509_parse -- Parse an X509 certificate and return the information as an array
openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, 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

bool openssl_csr_new ( array dn, resource privkey [, array configargs [, array extraattribs]])

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.

privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify 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

mixed openssl_error_string ( void )

Returns an error message string, or FALSE if there are no more error messages to return.

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

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 -- Get a private key

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

This is an alias for openssl_pkey_get_private().

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_publickey -- Extract public key from certificate and prepare it for use

Description

resource openssl_get_publickey ( mixed certificate)

This is an alias for openssl_pkey_get_public().

openssl_open

(PHP 4 >= 4.0.4, 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])

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.

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

bool openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts]]])

openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

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_get_private

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_private -- Get a private key

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_privatekey() parses key and prepares it for use by other functions. key can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  2. A PEM formatted private key.

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

openssl_pkey_get_public

(PHP 4 >= 4.2.0, 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])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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

bool openssl_x509_checkpurpose ( mixed x509cert, int purpose, array cainfo [, string untrustedfile])

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

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.

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

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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.

LXXX. Ovrimos SQL Functions

Introduzione

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

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.

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

NameDefaultChangeable
output_buffering"0"PHP_INI_PERDIR|PHP_INI_SYSTEM
output_handlerNULLPHP_INI_PERDIR|PHP_INI_SYSTEM
implicit_flush"0"PHP_INI_PERDIR|PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

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

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Nota: You cannot use both mb_output_handler() with ob_inconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

See also ob_implicit_flush().


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.

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

The above example will output:

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 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])

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 ini.zlib.output_compression. Also note that using ini.zlib.output_compression is preferred over ob_gzhandler().

See also ob_start() and ob_end_flush().

ob_implicit_flush

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

The above example will output:

Array
(
    [0] => default output handler
)
Array
(
    [0] => ob_gzhandler
)

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

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.

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.

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.

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.
</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() and ob_gzhandler().

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

The above example will output:

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

The above example will output:

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

LXXXII. Proprietà object e method call overloading

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.

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.

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;
print "\$o->a: $o->a\n"; // print: $o->a:
print "\$o->b: $o->b\n"; // print: $o->b: 9
print "\$o->c: $o->c\n"; // print: $o->c: 42
print "\$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);

?>

Avvertimento

Siccome è una estensione sperimentale, non tutto funziona. Non c'è attualmente il supporto per __call(), puoi solo overloadare le operazioni di ricezione e di impostazione per le proprietà. Non puoi invocare l'overloading handlers originale della classe, e __set() funziona solo su un livello di proprietà di accesso.

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

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


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

To get these functions to work, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local. In addition you can specify the jpeg, tiff, and pnglibrary for PDFlib to use, which is optional for PDFlib 4.x. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-png-dir[=DIR] --with-tiff-dir[=DIR].

When using version 3.x of PDFlib, you should configure PDFlib with the option --enable-shared-pdflib.


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

pdf_add_annotation -- Deprecated: Adds annotation

Description

This function is deprecated, use pdf_add_note() instead.

pdf_add_bookmark

(PHP 4 >= 4.0.1, PHP 5)

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.

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, PHP 5)

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, PHP 5)

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, PHP 5)

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.

pdf_add_outline

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 , PHP 5)

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, PHP 5)

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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, PHP 5)

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 , PHP 5)

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, PHP 5)

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, PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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, PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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 , PHP 5)

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, PHP 5)

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, PHP 5)

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

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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.

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, PHP 5)

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

pdf_get_font -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_fontname

pdf_get_fontname -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_parameter() instead.

pdf_get_fontsize

pdf_get_fontsize -- Deprecated: font handling

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_image_height

pdf_get_image_height -- Deprecated: returns height of an image

Description

This function is deprecated, use pdf_get_value() instead.

pdf_get_image_width

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, PHP 5)

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, PHP 5)

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, PHP 5)

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.

pdf_get_pdi_parameter

(PHP 4 >= 4.0.5, PHP 5)

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, PHP 5)

pdf_get_pdi_value -- Gets some PDI numerical parameters

Description

string 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, PHP 5)

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.

pdf_initgraphics

(PHP 4 >= 4.0.5, PHP 5)

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 , PHP 5)

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, PHP 5)

pdf_makespotcolor -- Makes a spotcolor

Description

bool 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 , PHP 5)

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, PHP 5)

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, PHP 5)

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, PHP 5)

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

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 , PHP 5)

pdf_open_image_file -- Reads an image from a file

Description

int pdf_open_image_file ( resource pdfdoc, string imagetype, string filename [, string stringparam [, string intparam]])

Open an image file. Supported types are jpeg, tiff, gif, and png. stringparam is either , mask, masked, or page. intparamis either 0, the image id of the applied mask, or the page.

pdf_open_image

(PHP 4 >= 4.0.5, PHP 5)

pdf_open_image -- Versatile function for images

Description

int pdf_open_image ( resource PDF-document, string imagetype, string source, string data, long length, int width, int height, int components, int bpc, string params)

Use image data from a variety of data sources. Supported types are jpeg, ccitt, raw. Supported sources are memory, fileref, url. len is only used when type is raw, params is only used when type is ccitt.

pdf_open_jpeg

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 , PHP 5)

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, PHP 5)

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, PHP 5)

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

pdf_open_png --  Deprecated: Opens a PNG image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open_tiff

pdf_open_tiff -- Deprecated: Opens a TIFF image

Description

This function is deprecated, use pdf_open_image() instead.

pdf_open

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 , PHP 5)

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, PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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 , PHP 5)

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

pdf_set_char_spacing -- Deprecated: Sets character spacing

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_duration

pdf_set_duration -- Deprecated: Sets duration between pages

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_font

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

pdf_set_horiz_scaling -- Sets horizontal scaling of text [deprecated]

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_info_author

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

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

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

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

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, PHP 5)

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

pdf_set_leading -- Deprecated: Sets distance between text lines

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_parameter

(PHP 4 , PHP 5)

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

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 , PHP 5)

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

pdf_set_text_rendering -- Deprecated: Determines how text is rendered

Description

This function is deprecated, use pdf_set_value() instead.

pdf_set_text_rise

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, PHP 5)

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

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, PHP 5)

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.

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 , PHP 5)

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 , PHP 5)

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, PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

pdf_setlinecap -- Sets linecap parameter

Description

void 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 , PHP 5)

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 , PHP 5)

pdf_setlinewidth -- Sets line width

Description

void 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, PHP 5)

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 , PHP 5)

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

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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.

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 , PHP 5)

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 last font set by pdf_setfont(). If the optional parameters font and size are specified, the width will be calculated using that font and size instead. Please note that font is a font handle returned by pdf_findfont().

Nota: Both the font and size parameters must be used together.

See also pdf_setfont() and pdf_findfont().

pdf_stroke

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

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 , PHP 5)

pdf_translate -- Sets origin of coordinate system

Description

bool pdf_translate ( resource pdfdoc, float tx, float ty)

Translate the origin of the coordinate system.

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


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Verisign Payflow Pro configuration options

NameDefaultChangeable
pfpro.defaulthost/PFPRO_VERSION < 3 "test.signio.com"PHP_INI_ALL
pfpro.defaulthost"test-payflow.verisign.com"PHP_INI_ALL
pfpro.defaultport"443"PHP_INI_ALL
pfpro.defaulttimeout"30"PHP_INI_ALL
pfpro.proxyaddress""PHP_INI_ALL
pfpro.proxyport""PHP_INI_ALL
pfpro.proxylogon""PHP_INI_ALL
pfpro.proxypassword""PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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

void pfpro_cleanup ( void )

pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.

See also pfpro_init().

pfpro_init

(PHP 4 >= 4.0.2, PHP 5)

pfpro_init -- Initialises the Payflow Pro library

Description

void pfpro_init ( void )

pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.

See also pfpro_cleanup().

pfpro_process_raw

(PHP 4 >= 4.0.2, 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.

LXXXV. 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 safe mode. In safe mode, è 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 safe mode. L'unico modo è di disabilitare il safe mode oppure di cambiare il limite di tempo nel php.ini.

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 4.0 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 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.
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 è compilato 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 safe mode 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()).

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

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

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

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)

Restituisce una matrcie associativa con l'accoppiata opzione / valore basata sulle opzioni attese indicate in options, oppure FALSE in caso di errore.

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

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

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

?>

Lo script produrrà:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9

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(). Di seguito saranno elencate le opzioni di PHP (aggiornata a PHP 4.2.0), indicando quali possono essere aggiornate e a che livello.

Tabella 1. Opzioni di configurazione

NomeDefaultModificabile
allow_call_time_pass_reference"1"PHP_INI_PERDIR
allow_url_fopen"1"PHP_INI_SYSTEM
always_populate_raw_post_data"0"PHP_INI_PERDIR
arg_separator.input"&"PHP_INI_PERDIR
arg_separator.output"&"PHP_INI_ALL
asp_tags"0"PHP_INI_PERDIR
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_PERDIR
auto_detect_line_endings"0"PHP_INI_ALL
auto_globals_jit"1"PHP_INI_PERDIR
auto_prepend_fileNULLPHP_INI_PERDIR
bcmath.scale"0"PHP_INI_ALL
browscapNULLPHP_INI_SYSTEM
child_terminate"0"PHP_INI_ALL
com.allow_dcom"0"PHP_INI_SYSTEM
com.autoregister_casesensitive"1"PHP_INI_ALL
com.autoregister_typelib"0"PHP_INI_ALL
com.autoregister_verbose"0"PHP_INI_ALL
com.code_page""PHP_INI_ALL
com.typelib_file""PHP_INI_SYSTEM
date.default_latitude"31.7667"PHP_INI_ALL
date.default_longitude"35.2333"PHP_INI_ALL
date.sunrise_zenith"90.83"PHP_INI_ALL
date.sunset_zenith"90.83"PHP_INI_ALL
dba.default_handler""PHP_INI_ALL
default_charset""PHP_INI_ALL
default_mimetype"text/html"PHP_INI_ALL
default_socket_timeout"60"PHP_INI_ALL
define_syslog_variables"0"PHP_INI_ALL
disable_classes""php.ini only
disable_functions""php.ini only
display_errors"1"PHP_INI_ALL
display_startup_errors"0"PHP_INI_ALL
docref_ext""PHP_INI_ALL
docref_root""PHP_INI_ALL
doc_rootNULLPHP_INI_SYSTEM
enable_dl"1"PHP_INI_SYSTEM
engine"1"PHP_INI_ALL
error_append_stringNULLPHP_INI_ALL
error_logNULLPHP_INI_ALL
error_prepend_stringNULLPHP_INI_ALL
exif.decode_jis_intel"JIS"PHP_INI_ALL
exif.decode_jis_motorola"JIS"PHP_INI_ALL
exif.decode_unicode_intel"UCS-2LE"PHP_INI_ALL
exif.decode_unicode_motorola"UCS-2BE"PHP_INI_ALL
exif.encode_jis""PHP_INI_ALL
exif.encode_unicode"ISO-8859-15"PHP_INI_ALL
expose_php"1"php.ini only
extension_dir"@PREFIX@"PHP_INI_SYSTEM
fbsql.allow_persistent"1"PHP_INI_SYSTEM
fbsql.autocommit"1"PHP_INI_SYSTEM
fbsql.batchSize"1000"PHP_INI_SYSTEM
fbsql.default_database""PHP_INI_SYSTEM
fbsql.default_database_password""PHP_INI_SYSTEM
fbsql.default_hostNULLPHP_INI_SYSTEM
fbsql.default_password""PHP_INI_SYSTEM
fbsql.default_user"_SYSTEM"PHP_INI_SYSTEM
fbsql.generate_warnings"0"PHP_INI_SYSTEM
fbsql.max_connections"128"PHP_INI_SYSTEM
fbsql.max_links"128"PHP_INI_SYSTEM
fbsql.max_persistent"-1"PHP_INI_SYSTEM
fbsql.max_results"128"PHP_INI_SYSTEM
file_uploads"1"PHP_INI_SYSTEM
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_ALL
ibase.allow_persistent"1"PHP_INI_SYSTEM
ibase.dateformat"%Y-%m-%d"PHP_INI_ALL
ibase.default_charsetNULLPHP_INI_ALL
ibase.default_dbNULLPHP_INI_SYSTEM
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
iconv.input_encoding"ISO-8859-1"PHP_INI_ALL
iconv.internal_encoding"ISO-8859-1"PHP_INI_ALL
iconv.output_encoding"ISO-8859-1"PHP_INI_ALL
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_ALL
ignore_repeated_source"0"PHP_INI_ALL
ignore_user_abort"0"PHP_INI_ALL
implicit_flush"0"PHP_INI_ALL
include_path".;@PREFIX@\\pear"PHP_INI_ALL
ingres.allow_persistent"1"PHP_INI_SYSTEM
ingres.default_databaseNULLPHP_INI_ALL
ingres.default_passwordNULLPHP_INI_ALL
ingres.default_userNULLPHP_INI_ALL
ingres.max_links"-1"PHP_INI_SYSTEM
ingres.max_persistent"-1"PHP_INI_SYSTEM
ircg.control_user"nobody"PHP_INI_ALL
ircg.keep_alive_interval"60"PHP_INI_ALL
ircg.max_format_message_sets"12"PHP_INI_ALL
ircg.shared_mem_size"6000000"PHP_INI_ALL
ircg.work_dir"/tmp/ircg"PHP_INI_ALL
last_modified"0"PHP_INI_ALL
ldap.max_links"-1"PHP_INI_SYSTEM
log_errors"0"PHP_INI_ALL
log_errors_max_len"1024"PHP_INI_ALL
magic_quotes_gpc"1"PHP_INI_PERDIR
magic_quotes_runtime"0"PHP_INI_ALL
magic_quotes_sybase"0"PHP_INI_ALL
mail.force_extra_parametersNULLPHP_INI_PERDIR
max_execution_time"30"PHP_INI_ALL
max_input_time"-1"PHP_INI_PERDIR
mbstring.detect_orderNULLPHP_INI_ALL
mbstring.encoding_translation"0"PHP_INI_PERDIR
mbstring.func_overload"0"PHP_INI_PERDIR
mbstring.http_input"pass"PHP_INI_ALL
mbstring.http_output"pass"PHP_INI_ALL
mbstring.internal_encodingNULLPHP_INI_ALL
mbstring.language"neutral"PHP_INI_PERDIR
mbstring.script_encodingNULLPHP_INI_ALL
mbstring.substitute_characterNULLPHP_INI_ALL
mcrypt.algorithms_dirNULLPHP_INI_ALL
mcrypt.modes_dirNULLPHP_INI_ALL
memory_limit"8M"PHP_INI_ALL
mime_magic.debug"0"PHP_INI_SYSTEM
mime_magic.magicfilePHP_PREFIXPHP_INI_SYSTEM
mssql.allow_persistent"1"PHP_INI_SYSTEM
mssql.batchsize"0"PHP_INI_ALL
mssql.compatability_mode"0"PHP_INI_ALL
mssql.connect_timeout"5"PHP_INI_ALL
mssql.datetimeconvert"1"PHP_INI_ALL
mssql.max_links"-1"PHP_INI_SYSTEM
mssql.max_persistent"-1"PHP_INI_SYSTEM
mssql.max_procs"25"PHP_INI_ALL
mssql.min_error_severity"10"PHP_INI_ALL
mssql.min_message_severity"10"PHP_INI_ALL
mssql.secure_connection"0"PHP_INI_SYSTEM
mssql.textlimit"-1"PHP_INI_ALL
mssql.textsize"-1"PHP_INI_ALL
mssql.timeout"60"PHP_INI_ALL
mysql.allow_persistent"1"PHP_INI_SYSTEM
mysql.connect_timeout"60"PHP_INI_ALL
mysql.default_hostNULLPHP_INI_ALL
mysql.default_passwordNULLPHP_INI_ALL
mysql.default_portNULLPHP_INI_ALL
mysql.default_socketNULLPHP_INI_ALL
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_ALL
mysqli.default_hostNULLPHP_INI_ALL
mysqli.default_port"3306"PHP_INI_ALL
mysqli.default_pwNULLPHP_INI_ALL
mysqli.default_socketNULLPHP_INI_ALL
mysqli.default_userNULLPHP_INI_ALL
mysqli.max_links"-1"PHP_INI_SYSTEM
mysqli.reconnect"0"PHP_INI_SYSTEM
nsapi.read_timeout"60"PHP_INI_ALL
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
open_basedirNULLPHP_INI_SYSTEM
output_buffering"0"PHP_INI_PERDIR
output_handlerNULLPHP_INI_PERDIR
pfpro.defaulthost"test-payflow.verisign.com"PHP_INI_ALL
pfpro.defaultport"443"PHP_INI_ALL
pfpro.defaulttimeout"30"PHP_INI_ALL
pfpro.proxyaddress""PHP_INI_ALL
pfpro.proxylogon""PHP_INI_ALL
pfpro.proxypassword""PHP_INI_ALL
pfpro.proxyport""PHP_INI_ALL
pgsql.allow_persistent"1"PHP_INI_SYSTEM
pgsql.auto_reset_persistent"0"PHP_INI_SYSTEM
pgsql.ignore_notice"0"PHP_INI_ALL
pgsql.log_notice"0"PHP_INI_ALL
pgsql.max_links"-1"PHP_INI_SYSTEM
pgsql.max_persistent"-1"PHP_INI_SYSTEM
post_max_size"8M"PHP_INI_PERDIR
precision"14"PHP_INI_ALL
register_argc_argv"1"PHP_INI_PERDIR
register_globals"0"PHP_INI_PERDIR
register_long_arrays"1"PHP_INI_PERDIR
report_memleaks"1"PHP_INI_ALL
report_zend_debug"1"PHP_INI_ALL
safe_mode"0"php.ini only
safe_mode_allowed_env_vars"PHP_"PHP_INI_SYSTEM
safe_mode_exec_dir""PHP_INI_SYSTEM
safe_mode_gid"0"PHP_INI_SYSTEM
safe_mode_include_dirNULLPHP_INI_SYSTEM
safe_mode_protected_env_vars"LD_LIBRARY_PATH"PHP_INI_SYSTEM
sendmail_fromNULLPHP_INI_ALL
sendmail_pathNULLPHP_INI_SYSTEM
serialize_precision"100"PHP_INI_ALL
session.auto_start"0"PHP_INI_ALL
session.bug_compat_42"1"PHP_INI_ALL
session.bug_compat_warn"1"PHP_INI_ALL
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_ALL
session.entropy_file""PHP_INI_ALL
session.entropy_length"0"PHP_INI_ALL
session.gc_divisor"100"PHP_INI_ALL
session.gc_maxlifetime"1440"PHP_INI_ALL
session.gc_probability"1"PHP_INI_ALL
session.hash_bits_per_character"4"PHP_INI_ALL
session.hash_function"0"PHP_INI_ALL
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_ALL
session.use_trans_sid"0"PHP_INI_ALL
short_open_tag"1"PHP_INI_PERDIR
SMTP"localhost"PHP_INI_ALL
smtp_port"25"PHP_INI_ALL
soap.wsdl_cache_dir"/tmp"PHP_INI_ALL
soap.wsdl_cache_enabled"1"PHP_INI_ALL
soap.wsdl_cache_ttl"86400"PHP_INI_ALL
sql.safe_mode"0"PHP_INI_SYSTEM
sqlite.assoc_case"0"PHP_INI_ALL
sybct.allow_persistent"1"PHP_INI_SYSTEM
sybct.deadlock_retry_count"-1"PHP_INI_ALL
sybct.hostnameNULLPHP_INI_ALL
sybct.login_timeout"-1"PHP_INI_ALL
sybct.max_links"-1"PHP_INI_SYSTEM
sybct.max_persistent"-1"PHP_INI_SYSTEM
sybct.min_client_severity"10"PHP_INI_ALL
sybct.min_server_severity"10"PHP_INI_ALL
tidy.clean_output"0"PHP_INI_PERDIR
tidy.default_config""PHP_INI_SYSTEM
track_errors"0"PHP_INI_ALL
unserialize_callback_funcNULLPHP_INI_ALL
upload_max_filesize"2M"PHP_INI_PERDIR
upload_tmp_dirNULLPHP_INI_SYSTEM
url_rewriter.tags"a=href,area=href,frame=src,form=,fieldset="PHP_INI_ALL
user_agentNULLPHP_INI_ALL
user_dirNULLPHP_INI_SYSTEM
variables_order"EGPCS"PHP_INI_ALL
xbithack"0"PHP_INI_ALL
xmlrpc_errors"0"PHP_INI_SYSTEM
xmlrpc_error_number"0"PHP_INI_ALL
y2k_compliance"1"PHP_INI_ALL
zlib.output_compression"0"PHP_INI_ALL
zlib.output_compression_level"-1"PHP_INI_ALL
zlib.output_handler""PHP_INI_ALL

Tabella 2. Definizione delle costanti PHP_INI_*

CostanteValoreSignificato
PHP_INI_USER1Entry can be set in user scripts
PHP_INI_PERDIR2 L'opzione può essere impostata in php.ini, .htaccess o httpd.conf
PHP_INI_SYSTEM4 L'opzione può essere impostata in php.ini o httpd.conf
PHP_INI_ALL7L'opzione può essere impostata ovunque

Vedere anche: get_cfg_var(), ini_get(), ini_get_all() e ini_restore()

main

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();
if ($sapi_type == "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 è compilato il PHP

Descrizione

string php_uname ( void )

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.

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_modules().
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_modules() 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 safe mode. 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().

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


Vedere anche

Potrebbe essere interessante anche la sezione Funzioni per il controllo dei processi.

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

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.

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

NameDefaultChangeable
pgsql.allow_persistent"1"PHP_INI_SYSTEM
pgsql.max_persistent"-1"PHP_INI_SYSTEM
pgsql.max_links"-1"PHP_INI_SYSTEM
pgsql.auto_reset_persistent"0"PHP_INI_SYSTEM
pgsql.ignore_notice"0"PHP_INI_ALL
pgsql.log_notice"0"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

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)

PGSQL_NUM (integer)

PGSQL_BOTH (integer)

PGSQL_CONNECTION_BAD (integer)

PGSQL_CONNECTION_OK (integer)

PGSQL_SEEK_SET (integer)

PGSQL_SEEK_CUR (integer)

PGSQL_SEEK_END (integer)

PGSQL_ESCAPE_STRING (integer)

PGSQL_ESCAPE_BYTEA (integer)

PGSQL_EMPTY_QUERY (integer)

PGSQL_COMMAND_OK (integer)

PGSQL_TUPLES_OK (integer)

PGSQL_COPY_OUT (integer)

PGSQL_COPY_IN (integer)

PGSQL_BAD_RESPONSE (integer)

PGSQL_NONFATAL_ERROR (integer)

PGSQL_FATAL_ERROR (integer)


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_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_fieldisnull -- 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 --  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 --  Returns the value of a server parameter
pg_pconnect -- Open a persistent PostgreSQL connection
pg_ping -- Ping database connection
pg_port --  Restituisce il numero di porta associato alla connessione
pg_put_line -- Invia una stringa terminata da NULL al backend PostgreSQL
pg_query -- Esegue una query
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_query --  Invia una query in modo asincrono
pg_set_client_encoding --  Imposta la codifica del client
pg_trace -- iAbilita il tracciamento di una connessione PostgreSQL
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_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_fieldisnull

(PHP 3, PHP 4 , PHP 5)

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

(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_metadata ( 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 --  Returns the value of a server parameter

Description

string|false pg_parameter_status ( [resource connection [, string param_name]])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

(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

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

Restituisce TRUE se percorsofile è stato aperto inscrittura per il log, altrimenti FALSE.

Vedere anche fopen() e pg_untrace().

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)

Description

array pg_version ( [resource connection])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

LXXXVIII. 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");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while (1) {

    // do something interesting here

}

function sig_handler($signo) 
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?>

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

bool 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
} 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])

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.

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

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.

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

int pcntl_wifexited ( int status)

Returns TRUE if the child status code represents a successful exit.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wexitstatus().

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifsignaled --  Returns TRUE if status code represents a termination due to a signal

Description

int pcntl_wifsignaled ( int status)

Returns TRUE if the child process exited because of a signal which was not caught.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_signal().

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifstopped --  Returns TRUE if child process is currently stopped

Description

int pcntl_wifstopped ( int status)

Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid().

pcntl_wstopsig

(PHP 4 >= 4.1.0, 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().

LXXXIX. Funzioni per l'esecuzione di programmi

Queste funzioni permettono l'esecuzione di comandi sul sistema stesso, e rendono sicuri tali comandi. Queste funzioni sono anche strettamente correlate al operatore backtick.

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

system("ls ".escapeshellarg($dir));

Vedere anche 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:

$e = escapeshellcmd($userinput);
system("echo $e"); // qui non ci preoccupiamo se $e contiene spazi
$f = escapeshellcmd($filename);
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); // e qui invece lo facciamo, usando le virgolette

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 [, string array [, 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 array è presente, allora tale vettore specificato verrà riempito con ogni linea del output del comando. 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 array, allora lo stato del comando eseguito verrà scritto in questa variabile.

Avvertimento

Si osservi che se si intende allocare dati che giungono dall'utente per passarli a questa funzione, si dovrebbe usare escapeshellarg() o escapeshellcmd() per assicurarsi che l'utente non forzi il sistema ad eseguire comandi arbitrari.

Nota: Notare anche che se si esegue un programma usando questa funzione e lo si vuole lasciare in esecuzione in background, ci si deve assicurare che l'output del programa venga rediretto ad un file o a qualche altro flusso di output, altrimenti PHP rimarrà bloccato in attesa fino alla fine dell'esecuzione del programma.

Vedere anche system(), passthru(), popen(), escapeshellcmd() 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 intende permettere ai dati provenienti dall'input dell'utente di essere passati a questa funzione, allora si dovrebbe usare escapeshellarg() o escapeshellcmd(), questo al fine di assicurarsi che gli utenti non possano maliziosamente indurrethe il sistema ad eseguire comandi arbitrari.

Nota: Nota che se avvii un programma usando questa funzione e intendi lasciarlo girare in background, devi accertarti che l'output del programma sia rediretto in un file o a qualche altro flusso di output o PHP attenderà fino alla fine dell'esecuzione del programma.

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.

Description

int proc_close ( resource process)

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns 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.

proc_get_status

(PHP 5)

proc_get_status --  Get information about a process opened by proc_open()

Description

array proc_get_status ( resource process)

proc_get_status() fetches data about a process opened using proc_open(). The collected information is returned in an array containing the following elements:

elementtypedescription
commandstringThe 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)

See also proc_open().

proc_nice

(PHP 5)

proc_nice --  Change the priority of the current process

Description

bool proc_nice ( int priority)

proc_nice() changes the priority of the current process. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is generated and FALSE is returned. Otherwise, TRUE is returned.

Nota: 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_nice() is not related to proc_open() and its associated functions in any way.

proc_open

(PHP 4 >= 4.3.0, PHP 5)

proc_open --  Execute a command and open file pointers for input/output

Description

resource proc_open ( string cmd, array descriptorspec, array pipes)

proc_open() is similar to popen() but provides a much greater degree of control over the program execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created. The return value is a resource representing the process; you should free it using proc_close() when you are finished with it.

<?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
);
$process = proc_open("php", $descriptorspec, $pipes);
if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], "<?php echo \"Hello World!\"; ?>");
    fclose($pipes[0]);

    while (!feof($pipes[1])) {
        echo fgets($pipes[1], 1024);
    }
    fclose($pipes[1]);
    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

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

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

The file descriptor numbers in descriptorspec are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.

Nota: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Nota: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

See also stream_select(), exec(), system(), passthru(), popen(), escapeshellcmd(), and the backtick operator.

proc_terminate

(PHP 5)

proc_terminate --  kills a process opened by proc_open

Description

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.

See also proc_open(), proc_close(), and proc_get_status().

shell_exec

(PHP 4 , PHP 5)

shell_exec -- Esegue un comando attraverso la shell e restituisce l'output come stringa

Descrizione

string shell_exec ( string cmd)

Questa funzione è identica all'operatore backtick.

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

Nota che se intendi permettere che i dati in ingresso dall'utente vengano passati a questa funzione, dovresti utilizzare la funzione escapeshellarg() o escapeshellcmd() per assicurarti che l'utente non possa forzare il sistema ad eseguire comandi arbitrari.

Nota: Nota che se avvii un programma usando questa funzione e intendi lasciarlo girare in background, devi accertarti che l'output del programma sia rediretto in un file o a qualche altro flusso di output o PHP attenderà fino alla fine dell'esecuzione del programma.

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

Vedere anche exec(), passthru(), popen(), escapeshellcmd() e l'operatore backtick.

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

Aggiungere la linea extension=php_printer.dll al file php.ini .


Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. Parametri di configurazione per il modulo stampante

NomeDefaultModificabile
printer.default_printer""PHP_INI_ALL
Per maggiori dettagli sulle costanti PHP_INI_* vedere ini_set().

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

printer_draw_bmp -- Disegna una bitmap

Descrizione

void printer_draw_bmp ( resource handle, string nomefile, int x, int y)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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

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

int pspell_add_to_personal ( int dictionary_link, string word)

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

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

int pspell_add_to_session ( int dictionary_link, string word)

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

pspell_check

(PHP 4 >= 4.0.2, 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

int pspell_clear_session ( int dictionary_link)

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

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

int pspell_config_ignore ( int dictionary_link, int n)

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spellchecker. Words less then n characters will be skipped.

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

int pspell_config_mode ( int dictionary_link, int mode)

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

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

int pspell_config_personal ( int dictionary_link, string file)

pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

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

int pspell_config_repl ( int dictionary_link, string file)

pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

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

int pspell_config_runtogether ( int dictionary_link, bool flag)

pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, 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

int pspell_config_save_repl ( int dictionary_link, bool flag)

pspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new_config

(PHP 4 >= 4.0.2, 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 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

int pspell_save_wordlist ( int dictionary_link)

pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

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

int pspell_store_replacement ( int dictionary_link, string misspelled, string correct)

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

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

XCII. 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 meant using PHP from the 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 this 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 this functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR]. In order you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR].


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_clear_history -- Clears the history
readline_completion_function -- Registers a completion function
readline_info -- Gets/sets various internal readline variables
readline_list_history -- Lists the history
readline_read_history -- Reads the history
readline_write_history -- Writes the history
readline -- Reads a line

readline_add_history

(PHP 4 , PHP 5)

readline_add_history -- Adds a line to the history

Description

void readline_add_history ( string line)

This function adds a line to the command line history.

readline_clear_history

(PHP 4 , 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 ( string line)

This function registers a completion function. You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

readline_info

(PHP 4 , 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_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_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());
?>

XCIII. 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://www.gnu.org/directory/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 o YAZ. 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 of 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

recode -- Alias of recode_string()

Description

This function is an alias of recode_string().

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

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) posta all'interno dell'espressione regolare.

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

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

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

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

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

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)

qdom_tree -- Crea un tree di una stringa xml

Descrizione

object qdom_tree ( 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.

XCVI. 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 funzioni che supportano le espressioni regolari sono:

Tutte queste funzioni usano una espressione regolare come loro primo argomento. 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

bool 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 TRUE se le ricerche previste da espressione_regolare sono riscontrate in stringa. Viene restituito FALSE se non si hanno riscontri, oppure si verificano degli errori.

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

bool 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
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 espressione_regolare, string stringa [, int limite])

Questa funzione ha un comportamento identico a split() tranne che per il fatto di non distinguere tra lettere maiuscole e minuscole.

Vedere anche preg_spliti(), 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");
?>

visualizza:

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

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

NomeDefaultModificabile
sysvmsg.value"42"PHP_INI_ALL
sysvmsg.string"foobar"PHP_INI_ALL
Per maggiori dettagli sulle 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.

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

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_remove_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_set_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_stat_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 ( int 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 parametro max_acquire.

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

int sem_get ( int key [, int max_acquire [, int perm]])

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 si indicat 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.

La funzione ritorna un identificatore positivo di semaforo se ha successo, oppure FALSE se si verifica un errore.

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

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

sem_release

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

sem_release -- Rilascia un semaforo

Descrizione

bool sem_release ( int 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().

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

sem_remove

(PHP 4 >= 4.1.0, PHP 5)

sem_remove -- Rimuove un semaforo

Descrizione

bool sem_remove ( int 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().

Nota: Questa funzione non è utilizzabile sui sistemi Windows. Questa funzione è stata aggiunta nella versione 4.1.0 di PHP.

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

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

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.

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 id, int variable_key)

La funzione shm_get_var() restituisce la variabile identificata dalla chiave variable_key. La variabile resta presente nella memoria condivisa.

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

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 inserisce o aggiorna la variabile indicata in variable con chiave variable_key. Sono suportati Tutti i tipi di variabili.

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.

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

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 id, int variable_key)

Rimuove la variabile identificata da variable_key e libera la memoria occupata.

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

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 rimuove un segmento di memoria condivisa dal sistsema. Tutti i dati contenuti saranno persi.

Nota: Questa funzione non è utilizzabile sui sistemi Windows.

XCVIII. 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 PHP3 SESAM interface available which allows database operations via PHP-scripts.

Nota: Access to SESAM is only available with the latest CVS-Version of PHP3. PHP 4 does not support the SESAM database.


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

XCIX. 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 -- Restituisce l'espirazione della cache corrente
session_cache_limiter -- Assume o imposta il limitatore di cache corrente
session_commit -- Alias of 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 -- Restituisce l'espirazione della cache corrente

Descrizione

int session_cache_expire ( [int new_cache_expire])

session_cache_expire() restituisce l'espirazione della cache corrente. Se è data new_cache_expire , l'espirazione della cache corrente è rimpiazzata da new_cache_expire.

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

session_commit -- Alias of session_write_close()

Description

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.

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

Description

bool session_regenerate_id ( void )

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

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

Nota: As of PHP 4.3.3, if session cookies are enabled, use of session_regenerate_id() will also submit a new session cookie with the new session id.

See also session_id(), session_start(), and session_name().

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.

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

CI. SimpleXML 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.

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.


Installazione

This extension is only available if PHP was configured with --enable-simplexml. The PHP configuration script does this by default.

Nota: This extension requires PHP 5.


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]->actor[0]->age = '21';

echo $xml->asXML();
?>

The above code will output a new XML document, just like the original, except that the new XML will define Ms. Coder's age as 21.

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
simplexml_element->asXML --  Return a well-formed XML string based on SimpleXML element.
simplexml_element->attributes --  Identifies an element's attributes.
simplexml_element->children --  Finds children of given node.
simplexml_element->xpath --  Runs Xpath query on XML data.
simplexml_import_dom --  Get a simplexml_element 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.

simplexml_element->asXML

(no version information, might be only in CVS)

simplexml_element->asXML --  Return a well-formed XML string based on SimpleXML element.

Description

string simplexml_element->asXML ( void )

The asXML method formats the parent object's data in XML version 1.0.

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

simplexml_element->attributes

(no version information, might be only in CVS)

simplexml_element->attributes --  Identifies an element's attributes.

Description

object simplexml_element 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"

simplexml_element->children

(no version information, might be only in CVS)

simplexml_element->children --  Finds children of given node.

Description

object simplexml_element simplexml_element->children ( void )

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

simplexml_element->xpath

(no version information, might be only in CVS)

simplexml_element->xpath --  Runs Xpath query on XML data.

Description

array simplexml_element->xpath ( string path)

The xpath method searches the SimpleXML node for children matching the Xpath path. It always returns an array of simplexml_element 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 simplexml_element object from a DOM node.

Description

object simplexml_element simplexml_import_dom ( domNode node)

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

simplexml_load_file

(PHP 5)

simplexml_load_file --  Interprets an XML file into an object.

Description

object simplexml_element simplexml_load_file ( string filename)

This function will convert the well-formed XML document in the file specified by filename to an object of class simplexml_element. If any errors occur during file access or interpretation, the function returns FALSE.

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:

simplexml_element 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_element simplexml_load_string ( string data)

This function will take the well-formed xml string data and return an object with properties containing the data held within the xml document. If any errors occur, it returns FALSE.

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:

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

CII. SOAP 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.

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

NameDefaultChangeable
soap.wsdl_cache_enabled"1"PHP_INI_ALL
soap.wsdl_cache_dir"/tmp"PHP_INI_ALL
soap.wsdl_cache_ttl86400PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Breve descrizione dei parametri di configurazione.

soap.wsdl_cache_enabled boolean

Enables or disables WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where SOAP extension will put cache files.

soap.wsdl_cache_ttl int

(time to live) Sets the number of second while cached file will be used instead of original one.


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)

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_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
SoapClient::SoapClient --  SoapClient constructor
SoapClient::__call --  Calls a SOAP function
SoapClient::__getFunctions --  Returns list of SOAP functions
SoapClient::__getLastRequest --  Returns last SOAP request
SoapClient::__getLastResponse --  Returns last SOAP response
SoapClient::__getTypes --  Returns list of SOAP types
SoapFault::SoapFault --  SoapFault constructor
SoapHeader::SoapHeader --  SoapHeader constructor
SoapParam::SoapParam --  SoapParam constructor
SoapServer::SoapServer --  SoapServer constructor
SoapServer::addFunction --  Adds one or several functions those will handle SOAP requests
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::SoapVar --  SoapVar constructor
is_soap_fault --  Checks if SOAP call was failed

SoapClient::SoapClient

(no version information, might be only in CVS)

SoapClient::SoapClient --  SoapClient constructor

Description

object SoapClient::SoapClient ( mixed wsdl [, array options])

This constructor allows creating SoapClient objects in WSDL or non-WSDL mode. The first case requires the URI of WSDL file as the first parameter and an optional options array. The second case requires NULL as the first parameter and the options array with location and uri options set, where location is a URL to request and uri is a target namespace of the SOAP service.

The style and use options only work in non-WSDL mode. In WSDL mode, they comes 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 a HTTP connection through a proxy server, use the options proxy_host, proxy_port, proxy_login and proxy_password.

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

?>

SoapClient::__call

(no version information, might be only in CVS)

SoapClient::__call --  Calls a SOAP function

Description

mixed SoapClient::__call ( string function_name [, array arguments [, array options [, array input_headers [, array output_headers]]]])

This is a low level API function to make a SOAP call. Usually in WSDL mode you can simply call SOAP functions as SoapClient methods. It is useful for non-WSDL mode when soapaction is unknown, uri differs from the default or when you like to send and/or receive SOAP Headers. On error, a call to a SOAP function can cause PHP exceptions or return a SoapFault object if exceptions was disabled. To check if the function call failed catch the SoapFault exceptions or check the result with the is_soap_fault() function.

SOAP functions may return one or several values. In the first case it will return just the value of output parameter, in the second it will return the associative array with named output parameters.

Esempio 1. SoapClient::__call() examples

<?php
$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);
$client->__call("SomeFunction", array($a, $b, $c));
$client->__call("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->__call("SomeFunction", array($a, $b, $c));
$client->__call("SomeFunction", array($a, $b, $c),
                 array('soapaction' => 'some_action',
                       'uri'        => 'some_uri'));
?>

See also SoapClient::SoapClient(), SoapParam::SoapParam(), SoapVar::SoapVar(), SoapHeader::SoapHeader(), SoapFault::SoapFault(), and is_soap_fault().

SoapClient::__getFunctions

(no version information, might be only in CVS)

SoapClient::__getFunctions --  Returns list of SOAP functions

Description

array SoapClient::__getFunctions ( void )

This function works only in WSDL mode.

Esempio 1. SoapClient::__getFunctions() example

<?php
$client = SoapClient("some.wsdl");
var_dump($client->__getFunctions());
?>

See also SoapClient::SoapClient().

SoapClient::__getLastRequest

(no version information, might be only in CVS)

SoapClient::__getLastRequest --  Returns last SOAP request

Description

string SoapClient::__getLastRequest ( void )

This function works only with SoapClient which was created with the trace option.

Esempio 1. SoapClient::__getLastRequest() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction(...);
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

See also SoapClient::SoapClient().

SoapClient::__getLastResponse

(no version information, might be only in CVS)

SoapClient::__getLastResponse --  Returns last SOAP response

Description

object SoapClient::__getLastResponse ( void )

This function works only with SoapClient which was created with the trace option.

Esempio 1. SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction(...);
echo "RESPONSE:\n" . $client->__getLastResponse() . "\n";
?>

See also SoapClient::SoapClient().

SoapClient::__getTypes

(no version information, might be only in CVS)

SoapClient::__getTypes --  Returns list of SOAP types

Description

array SoapClient::__getTypes ( void )

This function works only in WSDL mode.

Esempio 1. SoapClient::__getTypes() example

<?php
$client = SoapClient("some.wsdl");
var_dump($client->__getTypes());
?>

See also SoapClient::SoapClient().

SoapFault::SoapFault

(no version information, might be only in CVS)

SoapFault::SoapFault --  SoapFault constructor

Description

object SoapFault::SoapFault ( string faultcode, string faultstring [, string faultactor [, mixed detail [, string faultname [, mixed 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; faultname is an optional parameter that can be used to select proper fault encoding from WSDL; headerfault is an optional parameter that can be used during SOAP header handling to report an error in the response header.

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

See also SoapClient::SoapClient(), SoapClient::__call(), SoapParam::SoapParam(), SoapVar::SoapVar(), and is_soap_fault().

SoapHeader::SoapHeader

(no version information, might be only in CVS)

SoapHeader::SoapHeader --  SoapHeader constructor

Description

object SoapHeader::SoapHeader ( string namespace, string name [, mixed data [, bool mustUnderstand [, mixed actor]]])

SoapHeader is a special low-level class for passing or returning SOAP headers. It is just a data holder and it does not have any special methods except a constructor. It can be used in the SoapClient::__call() method to pass a SOAP header or in a SOAP header handler to return the header in a SOAP response. namespace and name are namespace and name of the SOAP header element. data is a SOAP header's content. It can be a PHP value or SoapVar object. mustUnderstand and actor are values for mustUnderstand and actor attributes of this SOAP Header element.

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

See also SoapClient::__call(), SoapParam::SoapParam(), and SoapVar::SoapVar().

SoapParam::SoapParam

(no version information, might be only in CVS)

SoapParam::SoapParam --  SoapParam constructor

Description

object SoapParam::SoapParam ( mixed data, string name)

SoapParam is a special low-level class for naming parameters and return ing values in non-WSDL mode. It is just a data holder and it does not have any special methods except the constructor. The constructor takes data to pass or return and name. It is possible to pass parameters directly as PHP values, but in this case it will be named as paramN and the SOAP Service may not understand them.

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

See also SoapClient::__call(), and SoapVar::SoapVar().

SoapServer::SoapServer

(no version information, might be only in CVS)

SoapServer::SoapServer --  SoapServer constructor

Description

object SoapServer::SoapServer ( mixed wsdl [, array options])

This constuctor allows the creatiion of SoapServer objects in WSDL or non-WSDL mode. In the first case, wsdl must be set to the URI of a WSDL file. In the second case, wsdl must be set to NULL and the uri option must be set. Additional options allow setting a default SOAP version (soap_version) and actor URI (actor).

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(null, array('uri' => "http://test-uri/"));

?>

SoapServer::addFunction

(no version information, might be only in CVS)

SoapServer::addFunction --  Adds one or several functions those will handle SOAP requests

Description

void SoapServer::addFunction ( mixed functions)

Exports one or more functions for remote clients.

To export one function, pass the function name into the functions parameter as a string. To export several functions pass an array of function names, and to export all functions pass a special constant SOAP_FUNCTIONS_ALL.

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.

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

?>

See also SoapServer::SoapServer(), and SoapServer::SetClass().

SoapServer::getFunctions

(no version information, might be only in CVS)

SoapServer::getFunctions --  Returns list of defined functions

Description

array SoapServer::getFunctions ( void )

This functions returns the list of all functions which was added by SoapServer::addFunction() or SoapServer::setClass().

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

See also SoapServer::SoapServer(), SoapServer::addFunction(), and SoapServer::SetClass().

SoapServer::handle

(no version information, might be only in CVS)

SoapServer::handle --  Handles a SOAP request

Description

void SoapServer::handle ( [string soap_request])

Processes a SOAP request, calls necessary functions, and sends a response back. It assumes a request in input parameter soap_request or in the global $HTTP_RAW_POST_DATA PHP variable if the argument is omitted.

Esempio 1. Some examples

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

See also SoapServer::SoapServer().

SoapServer::setClass

(no version information, might be only in CVS)

SoapServer::setClass --  Sets class which will handle SOAP requests

Description

void SoapServer::setClass ( string class_name [, mixed args])

Exports all methods from specified class. Additional parameters args will be passed to the default class constructor during object creation. The object can be made persistent across request for a given PHP session with the SoapServer::setPersistence() method.

Esempio 1. Some examples

<?php

class foo {
    function foo() 
    {
    }
}
$server->setClass("foo");

class bar {
    function bar($x, $y) 
    {
    }
}
$server->setClass("bar", $arg1, $arg2);

?>

See also SoapServer::SoapServer(), SoapServer::addFunction(), and SoapServer::setPersistence().

SoapServer::setPersistence

(no version information, might be only in CVS)

SoapServer::setPersistence --  Sets persistence mode of SoapServer

Description

void SoapServer::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().

Esempio 1. Some examples

<?php

$server->setPersistence(SOAP_PERSISTENCE_SESSION);

$server->setPersistence(SOAP_PERSISTENCE_REQUEST);

?>

See also SoapServer::SoapServer(), and SoapServer::SetClass().

SoapVar::SoapVar

(no version information, might be only in CVS)

SoapVar::SoapVar --  SoapVar constructor

Description

object SoapVar::SoapVar ( mixed data, int encoding [, string type_name [, string type_namespace [, string node_name [, string node_namespace]]]])

SoapVar is a special low-level class for encoding parameters and returning values in non-WSDL mode. It is just a data holder and does not have any special methods except the constructor. It is useful when you would like to set the type property in SOAP request or response. The constructor takes data to pass or return, encoding ID to encode it (see XSD_... constants) and as option type name and namespace and XML node name and namespace.

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

See also SoapClient::__call() and SoapParam::SoapParam().

is_soap_fault

(PHP 5)

is_soap_fault --  Checks if SOAP call was failed

Description

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

Esempio 1. is_soap_fault() example

<?php
$client = SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction(...);
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faulstring})", E_ERROR);
}
?>

Esempio 2. SOAP's standard method for error reporting is exceptions

<?php
try {
    $client = SoapClient("some.wsdl");
    $result = $client->SomeFunction(...);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faulstring})", E_ERROR);
}
?>

See also SoapClient::SoapClient(), and SoapFault::SoapFault().

CIII. 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 --  Executes a result-less query against a given database.
sqlite_factory --  Opens a SQLite database and creates an object for it
sqlite_fetch_all --  Fetches all rows from a result set as an array of arrays
sqlite_fetch_array -- Scarica com matrice la riga successiva da un set di risultati.
sqlite_fetch_column_types --  Return an array of column types from a particular table.
sqlite_fetch_object --  Fetches the next row from a result set as an object
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_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. Crea il database se non esiste.
sqlite_popen --  Apre una connessione persistente ad un database SQLite. Crea il database se non esiste.
sqlite_query --  Esegue una query su un database e restituisce un puntatore al set di risultati.
sqlite_rewind -- Posiziona sulla prima riga.
sqlite_seek -- Posizionamento su una data riga di un set di risultati bufferizzato.
sqlite_single_query --  Executes a query and returns either an array for one single column or the value of the first row
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_array_query

(PHP 5)

sqlite_array_query -- 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]])

Chiamare sqlite_array_query() equivale ad eseguire sqlite_query() e sqlite_fetch_array() per ciascuna riga del set di risultati e memorizzare queste righe in una matrice, come illustrato nell'esempio sottostante. La chiamata a sqlite_array_query() è significativamente più veloce di uno script del genere.

Esempio 1. sqlite_array_query() implementato via script

<?php
$q = sqlite_query($dbhandle, "SELECT * from foo LIMIT 100");
$rows = array();
while ($r = sqlite_fetch_array($q)) {
    $rows[] = $r;
}
?>

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

Vedere anche sqlite_query(), sqlite_fetch_array() e sqlite_fetch_string().

sqlite_busy_timeout

(PHP 5)

sqlite_busy_timeout -- Imposta il timeout di 'in uso', o disabilita l'handle di 'in uso'.

Descrizione

void sqlite_busy_timeout ( resource dbhandle, int milliseconds)

Imposta il tempo massimo che sqlite attenderà che un dbhandle diventi disponibile all'uso. Se il parametro milliseconds è 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 1000 (1000) millisecondi in un secondo.

Vedere anche sqlite_open().

sqlite_changes

(PHP 5)

sqlite_changes --  Restituisce il numero di righe modificate dall'ultima istruzione SQL.

Descrizione

int sqlite_changes ( resource dbhandle)

Restituisce il numero di righe modificate dall'ultima istruzione SQL eseguita sul database referenziato da dbhandle.

Vedere anche sqlite_num_rows().

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.

Vedere anche sqlite_open() e sqlite_popen().

sqlite_column

(PHP 5)

sqlite_column -- Scarica una riga dal set di risultati corrente.

Descrizione

mixed sqlite_column ( resource result, 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. La decodifica dei dati binari agisce in modo analogo a quanto descritto per sqlite_fetch_array().

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 -- Registra un aggregato UDF da utilizzare nelle istruzioni SQL.

Descrizione

bool sqlite_create_aggregate ( resource dbhandle, string function_name, mixed step_func, mixed 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.

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.

Vedere anche sqlite_create_function(), sqlite_udf_encode_binary() e sqlite_udf_decode_binary().

sqlite_create_function

(PHP 5)

sqlite_create_function --  Registra una funzione utente "regolare" da utilizzare nelle istruzioni SQL.

Descrizione

bool sqlite_create_function ( resource dbhandle, string function_name, mixed 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.

Il parametro dbhandle indica l' handle dl database che si desidera estendere, function_name indica il nome della funzione che si vuole utilizzare nelle istruzioni SQL, callback è un callbak PHP valido che punti ad una funzione PHP che deve essere richiamata per gestire la funzione SQL. Il parametro opzionale num_args viene utilizzato come suggerimento dal parser delle espressioni di SQLite. Si raccomanda di indicare un valore nel caso la funzione accetti soltanto un numero fisso di parametri.

Le UDF possono essere utilizzate in qualsiasi istruzione SQL che permetta di richiamare funzioni, tipo SELECT e UPDATE e anche i triggers.

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.

Vedere anche sqlite_create_aggregate().

sqlite_current

(PHP 5)

sqlite_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]])

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.

Se la posizione corrente è oltre l'ultima riga, la funzione restituirà FALSE

Nota: Questa funzione non può essere eseguita su risultati non bufferizzati.

Vedere anche sqlite_seek(), sqlite_next() e sqlite_fetch_array().

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 restituì da da funzioni UDF create tramite sqlite_create_function() o sqlite_create_aggregate() - utilizzare invece sqlite_udf_encode_binary().

Vedere anche sqlite_udf_encode_binary().

sqlite_exec

(no version information, might be only in CVS)

sqlite_exec --  Executes a result-less query against a given database.

Description

bool sqlite_exec ( resource dbhandle, string query)

bool sqlite_exec ( string query, resource dbhandle)

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

This function will return a boolean result; TRUE for success or FALSE for failure. If you need to run a query that returns rows, see sqlite_query().

Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first one, where the db parameter is the first parameter to the function.

Avvertimento

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.

See also sqlite_query(), sqlite_unbuffered_query() and sqlite_array_query().

sqlite_factory

(PHP 5)

sqlite_factory --  Opens a SQLite database and creates an object for it

Description

object sqlite_factory ( string filename [, int mode [, string &error_message]])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

sqlite_fetch_all

(PHP 5)

sqlite_fetch_all --  Fetches all rows from a result set as an array of arrays

Description

array sqlite_fetch_all ( resource result [, int result_type [, bool decode_binary]])

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

sqlite_fetch_array

(PHP 5)

sqlite_fetch_array -- Scarica com matrice la riga successiva da un set di risultati.

Descrizione

array sqlite_fetch_array ( resource result [, 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.

Il parametro result_type può essere utilizzato per indicare come si desidera che i dati siano restituiti. Il valore di default è SQLITE_BOTH, il quale restituisce le colonne indicizzate per il loro numero ordinale di colonna e per il nome della colonna. SQLITE_ASSOC restituisce una matrice indicizzata solo per il nome delle colonne, e SQLITE_NUM restituisce una matrice indicizzata solo per il numero ordinale di colonna.

I nomi delle colonne restituiti da SQLITE_ASSOC e SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.

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 no si debba intervenire su database creati da altre applicazioni SQLite.

Vedere anche sqlite_array_query() e sqlite_fetch_string().

sqlite_fetch_column_types

(PHP 5)

sqlite_fetch_column_types --  Return an array of column types from a particular table.

Description

resource sqlite_fetch_column_types ( string table_name, resource db)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

sqlite_fetch_object

(PHP 5)

sqlite_fetch_object --  Fetches the next row from a result set as an object

Description

object sqlite_fetch_object ( resource result [, 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 -- Scarica come stringa la prima colonna di un set di risultati.

Descrizione

string sqlite_fetch_single ( resource result [, int result_type [, 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.

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

sqlite_fetch_string -- Alias di sqlite_fetch_single()

Descrizione

Questa funzione è un alias di sqlite_fetch_single().

sqlite_field_name

(PHP 5)

sqlite_field_name -- Restituisce il nome di un particolare campo.

Descrizione

string sqlite_field_name ( resource result, int field_index)

Dato il numero ordinale di colonna, field_index, restituisce il nome del campo dal set di risultati indicato in result.

sqlite_has_more

(PHP 5)

sqlite_has_more -- restituisce se sono disponibili o meno ulteriori righe.

Descrizione

bool sqlite_has_more ( resource result)

sqlite_has_more() restituisce TRUE se sono disponibili ulteriori righe dal set di risultati result, oppure FALSE in caso contrario.

Vedere anche sqlite_num_rows() e sqlite_changes().

sqlite_last_error

(PHP 5)

sqlite_last_error -- Restituisce il codice di errore dell'ultimo errore accorso sul database.

Descrizione

int sqlite_last_error ( resource dbhandle)

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

Vedere anche sqlite_error_string().

sqlite_last_insert_rowid

(PHP 5)

sqlite_last_insert_rowid -- Restituisce l'identificativo di riga dell'ultima riga inserita.

Descrizione

int sqlite_last_insert_rowid ( resource dbhandle)

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.

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

sqlite_libversion

(PHP 5)

sqlite_libversion -- Restituisce la versione della libreria SQLite.

Descrizione

string sqlite_libversion ( void )

Restituisce, come stringa, la versione della libreria SQLite.

Vedere anche sqlite_libencoding().

sqlite_next

(PHP 5)

sqlite_next -- Si sposta al successivo numero di riga.

Descrizione

bool sqlite_next ( resource result)

La funzione sqlite_next() avanza il set di risultati indicato da result alla riga successiva. Restituisce FALSE se non vi sono ulteriori righe, TRUE in caso contrario.

Nota: Questa funzione non può essere utilizzata per gestire risultati non bufferizzati.

Vedere anche sqlite_seek(), sqlite_current() e sqlite_rewind().

sqlite_num_fields

(PHP 5)

sqlite_num_fields -- Resituitsce il numero di campi da un set di risultati.

Descrizione

int sqlite_num_fields ( resource result)

Restituisce il numero di campi presenti nel set di risultati result.

Vedere anche sqlite_column() e sqlite_num_rows().

sqlite_num_rows

(PHP 5)

sqlite_num_rows -- Restituisce il numero di righe da un set di risultati bufferizzato.

Descrizione

int sqlite_num_rows ( resource result)

Restituisce il numero di righe dal set di risultati result bufferizzato.

Nota: Questa funzione non può essere utilizzata con set di risultati non bufferizzati

Vedere anche sqlite_changes() e sqlite_query().

sqlite_open

(PHP 5)

sqlite_open -- Apre un database SQLite. Crea il database se non esiste.

Descrizione

resource sqlite_open ( string filename [, int mode [, string &error_message]])

Restituisce una risorsa (database handle) se ha successo, oppure FALSE se si verifica un errore.

Il parametro filename indica il nome del database. Può essere un percorso relativo o assoluto al file che SQLite utilizzerà per memorizzare i dati. Se il file non esiste, SQLite tenterà di crearlo. BISOGNA avere i permessi di scrittura sul file se si desidera inserire dei dati o modficare lo schema del database.

Il parametro mode specifica la modalità del file ed è 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 è 0666 e questo è il valore raccomandato se si necessita di accedere al parametro errmessage.

Il parametro errmessage è passato per riferimento ed è impostato per contenere un messaggio descrittivo di errore nel caso non si riesca ad aprire il database a causa di un errore.

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

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 al safe mode e a open_basedir.

Vedere anche sqlite_popen(), sqlite_close() e sqlite_query().

sqlite_popen

(PHP 5)

sqlite_popen --  Apre una connessione persistente ad un database SQLite. 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.

Vedere anche sqlite_open(), sqlite_close() e sqlite_query().

sqlite_query

(PHP 5)

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

Esegue le istruzioni SQL indicate in query sul collegamento al database indicato dal parametro dbhandle.

Nei casi di query che restituiscano delle righe, questa funzione restituisce un handle che può essere utilizzato nelle funzioni sqlite_fetch_array() e sqlite_seek().

Negli altri tipi di query, questa funzione restituirà un risultato booleano; TRUE se la query ha successo, FALSE se non riesce.

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

Nota: Sono supportate due sintassi alternative, questo per compatibilità con altri moduli per database (esempio MySql). La forma preferita è la prima, in cui il parametro db è il primo della funzione.

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

Vedere anche sqlite_unbuffered_query() e sqlite_array_query().

sqlite_rewind

(PHP 5)

sqlite_rewind -- Posiziona sulla prima riga.

Descrizione

bool sqlite_rewind ( resource result)

sqlite_rewind() si posiziona sulla prima riga del set di risultati. La funzione restituisce FALSE se non vi sono righe nel set di risultati, TRUE in caso contrario.

Nota: Questa funzione non può essere utilizzata con set di risultati non bufferizzati.

Vedere anche sqlite_next(), sqlite_current() e sqlite_seek().

sqlite_seek

(PHP 5)

sqlite_seek -- Posizionamento su una data riga di un set di risultati bufferizzato.

Descrizione

bool sqlite_seek ( resource result, int rownum)

sqlite_seek() si posiziona sulla riga indicata dal parametro rownum. Il numero della riga parte da zero (0 indica la prima riga). La funzione restituisce FALSE se la riga richiesta non esiste, oppure TRUE.

Nota: Questa funzione non può essere utilizzata con set di risultati non bufferizzato.

Vedere anche sqlite_next(), sqlite_current() e sqlite_rewind().

sqlite_single_query

(PHP 5)

sqlite_single_query --  Executes a query and returns either an array for one single column or the value of the first row

Description

mixed sqlite_single_query ( resource db, 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.

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

?>

Vedere anche sqlite_udf_encode_binary(), sqlite_create_function() e sqlite_create_aggregate().

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

Vedere anche sqlite_udf_decode_binary(), sqlite_escape_string(), sqlite_create_function() e sqlite_create_aggregate().

sqlite_unbuffered_query

(PHP 5)

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

sqlite_unbuffered_query() è simile a sqlite_query() tranne che i risultati sono restituiti in modo sequenziale una riga dopo l'altra, senza possibilità di tornare indietro.

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() sono applicabili agli handles restituiti da sqlite_unbuffered_query().

Vedere anche sqlite_query().

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

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 )

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 )

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 )

swf_actionnextframe -- Go forward one frame

Description

void swf_actionnextframe ( void )

Go forward one frame.

swf_actionplay

(PHP 4 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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)

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 )

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 )

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 )

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 )

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 )

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 )

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 )

swf_removeobject -- Remove an object

Description

void swf_removeobject ( int depth)

Removes the object at the depth specified by depth.

swf_rotate

(PHP 4 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

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 )

swf_showframe -- Display the current frame

Description

void swf_showframe ( void )

The swf_showframe function will output the current frame.

swf_startbutton

(PHP 4 )

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 )

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 )

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 )

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 )

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 )

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 )

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.

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

int 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

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

CVI. 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_iovec_add -- Aggiunge un nuovo vettore all'array ricevuti o inviati
socket_iovec_alloc --  Costruice una struttura 'struct iovec' da utilizzare con sendmsg, recvmsg, writev, e readv
socket_iovec_delete -- Cancella un vettore da un array di vettori
socket_iovec_fetch -- Restituisce i dati contenuti nella struttura iovec specificata da iovec_id[iovec_position]
socket_iovec_free -- Libera la strutture iovec indicata da iovec_id
socket_iovec_set -- Valorizza i dati contenuti in iovec_id[iovec_position] con new_val
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_readv --  Legge da un fd, utilizzando un array invia/ricevi definito da iovec_id
socket_recv -- Riceve i dati da un socket collegato
socket_recvfrom -- Riceve i dati da un socket, che sia connesso o meno
socket_recvmsg -- Funzione usata per ricevere messaggi da un socket, a prescindere che sia orientato alla connessione 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_sendmsg -- Invia un messaggio ad un socket, a prescindere che sia orientato alla connessione o meno
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_writev -- Scrive su un descrittore di file, fd, usando un array invia/ricevi definito da iovec_id

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

La funzione socket_bind() esegue il bind del nome passato in indirizzo sul socket indicato da socket, che deve essere una risorsa valida creata 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, 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.

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. Si è rilevato che socket_last_error() riporta un codice di errore errato se si tenta di eseguire il bind di un socket con un indirizzo errato su sistemi Windows9x/ME.

Vedere anche socket_connect(), socket_listen(), socket_create(), socket_last_error() e socket_strerror().

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_iovec_add

(PHP 4 >= 4.1.0)

socket_iovec_add -- Aggiunge un nuovo vettore all'array ricevuti o inviati

Descrizione

bool socket_iovec_add ( resource iovec, int iov_len)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_iovec_alloc

(PHP 4 >= 4.1.0)

socket_iovec_alloc --  Costruice una struttura 'struct iovec' da utilizzare con sendmsg, recvmsg, writev, e readv

Descrizione

resource socket_iovec_alloc ( int num_vectors [, int ])

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_iovec_delete

(PHP 4 >= 4.1.0)

socket_iovec_delete -- Cancella un vettore da un array di vettori

Descrizione

bool socket_iovec_delete ( resource iovec, int iov_pos)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_iovec_fetch

(PHP 4 >= 4.1.0)

socket_iovec_fetch -- Restituisce i dati contenuti nella struttura iovec specificata da iovec_id[iovec_position]

Descrizione

string socket_iovec_fetch ( resource iovec, int iovec_position)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

socket_iovec_free

(PHP 4 >= 4.1.0)

socket_iovec_free -- Libera la strutture iovec indicata da iovec_id

Descrizione

bool socket_iovec_free ( resource iovec)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_iovec_set

(PHP 4 >= 4.1.0)

socket_iovec_set -- Valorizza i dati contenuti in iovec_id[iovec_position] con new_val

Descrizione

bool socket_iovec_set ( resource iovec, int iovec_position, string new_val)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_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_readv

(PHP 4 >= 4.1.0)

socket_readv --  Legge da un fd, utilizzando un array invia/ricevi definito da iovec_id

Descrizione

bool socket_readv ( resource socket, resource iovec_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.

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.

socket_recvmsg

(PHP 4 >= 4.1.0)

socket_recvmsg -- Funzione usata per ricevere messaggi da un socket, a prescindere che sia orientato alla connessione o meno

Descrizione

bool socket_recvmsg ( resource socket, resource iovec, array &control, int &controllen, 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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_sendmsg

(PHP 4 >= 4.1.0)

socket_sendmsg -- Invia un messaggio ad un socket, a prescindere che sia orientato alla connessione o meno

Descrizione

bool socket_sendmsg ( resource socket, resource iovec, 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

socket_writev

(PHP 4 >= 4.1.0)

socket_writev -- Scrive su un descrittore di file, fd, usando un array invia/ricevi definito da iovec_id

Descrizione

bool socket_writev ( resource socket, resource iovec_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.

CVII. Standard PHP Library (SPL) Functions

Introduzione

SPL is a collection of interfaces and classes that are meant to solve standard problems.


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 --  Cehck whether the inner iterator has a valid next element
CachingIterator::next --  Move the iterator forward
CachingIterator::rewind --  Rewind the iterator
CachingIterator::__toString --  Retrun the string representation of the current element
CachingIterator::valid --  Check whether the current element is valid
CachingRecursiveIterator::getChildren --  Return the inenr iteraor'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::fileATime --  Get last access time of file
DirectoryIterator::fileCTime --  Get inode modification time of file
DirectoryIterator::fileGroup --  Get file group
DirectoryIterator::fileInode --  Get file inode
DirectoryIterator::fileMTime --  Get last modification time of file
DirectoryIterator::fileOwner --  Get file owner
DirectoryIterator::filePerms --  Get file permissions
DirectoryIterator::fileSize --  Get file size
DirectoryIterator::fileType --  Get file type
DirectoryIterator::getChildren --  Returns an iterator for the current entry if it is a directory
DirectoryIterator::getFilename --  Return filename of current dir entry
DirectoryIterator::getPath --  Return directory path
DirectoryIterator::getPathname --  Return path and filename of current dir entry
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

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);
$iterator = $arrayobject->getIterator();

for($iterator = $arrayobject->getIterator();
    $iterator->valid();
    $iterator->next()) {

    echo $iterator->key() . ' => ' . $iterator->current() . "\n";
}
?>

The above example will output:

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

The above example will output:

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

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

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

The above example will output:

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 --  Cehck whether the inner iterator has a valid next element

Description

boolean 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 --  Retrun 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

boolean 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 inenr iteraor'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

void 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::fileATime

(no version information, might be only in CVS)

DirectoryIterator::fileATime --  Get last access time of file

Description

int DirectoryIterator::fileATime ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileCTime

(no version information, might be only in CVS)

DirectoryIterator::fileCTime --  Get inode modification time of file

Description

int DirectoryIterator::fileCTime ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileGroup

(no version information, might be only in CVS)

DirectoryIterator::fileGroup --  Get file group

Description

int DirectoryIterator::fileGroup ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileInode

(no version information, might be only in CVS)

DirectoryIterator::fileInode --  Get file inode

Description

int DirectoryIterator::fileInode ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileMTime

(no version information, might be only in CVS)

DirectoryIterator::fileMTime --  Get last modification time of file

Description

int DirectoryIterator::fileMTime ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileOwner

(no version information, might be only in CVS)

DirectoryIterator::fileOwner --  Get file owner

Description

int DirectoryIterator::fileOwner ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::filePerms

(no version information, might be only in CVS)

DirectoryIterator::filePerms --  Get file permissions

Description

int DirectoryIterator::filePerms ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileSize

(no version information, might be only in CVS)

DirectoryIterator::fileSize --  Get file size

Description

int DirectoryIterator::fileSize ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

DirectoryIterator::fileType

(no version information, might be only in CVS)

DirectoryIterator::fileType --  Get file type

Description

string DirectoryIterator::fileType ( 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::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::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

boolean 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

boolean 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

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

CVIII. 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 L), 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 45. 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 L 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 L 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 45. 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 L).

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. 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. Server sockets should always include this flag.
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.

Nota: The constants marked with * are just available in PHP 5.


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_context_create -- Create a 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_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_get_name -- Retrieve the name of the local or remote sockets
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_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.

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

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|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 context|stream, string wrapper, string option, mixed value)

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

Description

int stream_copy_to_stream ( resource source, resource dest [, int maxlength])

Makes a copy of up to maxlength bytes of data from the current position in source to dest. If maxlength is not specified, all remaining content in source will be copied. Returns the total count of bytes copied.

Esempio 1. 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";

?>

See also copy().

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_append -- Attach a filter to a stream.

Description

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

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(), and stream_filter_prepend().

stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_prepend -- Attach a filter to a stream.

Description

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

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.

void onCreate ( void )

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. 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");

?>

Output

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

/* Output
 * ------

LINE1
WORD - 2
EASY AS 123

 */

?>

See also stream_wrapper_register(), stream_filter_prepend(), and stream_filter_append().

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

Identical to file_get_contents(), except that stream_get_contents() operates on an already open file resource and returns the remaining contents, up to maxlength bytes, in a string.

Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)

See also fgets(), fread(), and fpassthru().

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 read buffer.

The following items were added in PHP 4.3:

  • stream_type (string) - a label describing the underlying implementation of the stream.

  • wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Appendice L for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Appendice L for more information about wrappers and their wrapper data.

  • filters (array) - and array containing the names of any filters that have been stacked onto this stream. Filters are currently undocumented.

Nota: This function was introduced in PHP 4.3, but prior to this version, socket_get_status() could be used to retrieve the first four items, for socket based streams only.

In PHP 4.3 and later, socket_get_status() is an alias for this function.

Nota: This function does NOT work on sockets created by the Socket extension.

The following items were added in PHP 5.0:

  • mode (string) - the mode (or permissions) of the URI associated with this stream.

  • seakable (bool) - whether the current stream can be seeked in.

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

See also stream_wrapper_register().

stream_register_wrapper

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.

Windows 98 Note: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

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 FALSE, the given stream will be switched to non-blocking mode, and if TRUE, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.

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.

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\n\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);
    var_dump(stream_get_meta_data($fp));
    fclose($fp);
    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 [, int 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.

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_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 N 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_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_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);
?>

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.

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 N for a list of bulitin transports.

Esempio 1. stream_socket_server() Example

<?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://0.0.0.0:13", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, date("D M j H:i:s Y\r\n"));
    fclose($conn);
  }
  fclose($socket);
}
?>

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

?>

CIX. 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 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 -- Cacola 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 -- Write a formatted string to a stream
get_html_translation_table --  Returns the translation table used by htmlspecialchars() and htmlentities()
hebrev --  Convert logical Hebrew text to visual text
hebrevc --  Convert logical Hebrew text to visual text with newline conversion
html_entity_decode --  Convert all HTML entities to their applicable characters
htmlentities --  Convert all applicable characters to HTML entities
htmlspecialchars --  Convert special characters to HTML entities
implode -- Join array elements with a string
join -- Alias of implode()
levenshtein --  Calculate Levenshtein distance between two strings
localeconv -- Get numeric formatting information
ltrim --  Strip whitespace from the beginning of a string
md5_file -- Calculates the md5 hash of a given filename
md5 -- Calculate the md5 hash of a string
metaphone -- Calculate the metaphone key of a string
money_format -- Formats a number as a currency string
nl_langinfo --  Query language and locale information
nl2br --  Inserts HTML line breaks before all newlines in a string
number_format -- Format a number with grouped thousands
ord -- Return ASCII value of character
parse_str -- Parses the string into variables
print -- Output a string
printf -- Output a formatted string
quoted_printable_decode --  Convert a quoted-printable string to an 8 bit string
quotemeta -- Quote meta characters
rtrim --  Strip whitespace from the end of a string
setlocale -- Set locale information
sha1_file -- Calculate the sha1 hash of a file
sha1 -- Calculate the sha1 hash of a string
similar_text --  Calculate the similarity between two strings
soundex -- Calculate the soundex key of a string
sprintf -- Return a formatted string
sscanf --  Parses input from a string according to a format
str_ireplace --  Case-insensitive version of str_replace().
str_pad --  Pad a string to a certain length with another string
str_repeat -- Repeat a string
str_replace --  Replace all occurrences of the search string with the replacement string
str_rot13 -- Perform the rot13 transform on a string
str_shuffle -- Randomly shuffles a string
str_split --  Convert a string to an array
str_word_count --  Return information about words used in a string
strcasecmp --  Binary safe case-insensitive string comparison
strchr -- Alias of strstr()
strcmp -- Binary safe string comparison
strcoll -- Locale based string comparison
strcspn --  Find length of initial segment not matching mask
strip_tags -- Strip HTML and PHP tags from a string
stripcslashes --  Un-quote string quoted with addcslashes()
stripos --  Find position of first occurrence of a case-insensitive string
stripslashes --  Un-quote string quoted with addslashes()
stristr --  Case-insensitive strstr()
strlen -- Get string length
strnatcasecmp --  Case insensitive string comparisons using a "natural order" algorithm
strnatcmp --  String comparisons using a "natural order" algorithm
strncasecmp --  Binary safe case-insensitive string comparison of the first n characters
strncmp --  Binary safe string comparison of the first n characters
strpbrk --  Search a string for any of a set of characters
strpos --  Find position of first occurrence of a string
strrchr --  Find the last occurrence of a character in a string
strrev -- Reverse a string
strripos --  Find position of last occurrence of a case-insensitive string in a string
strrpos --  Find position of last occurrence of a char in a string
strspn --  Find length of initial segment matching mask
strstr -- Find first occurrence of a string
strtok -- Tokenize string
strtolower -- Make a string lowercase
strtoupper -- Make a string uppercase
strtr -- Translate certain characters
substr_compare --  Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters
substr_count -- Count the number of substring occurrences
substr_replace -- Replace text within a portion of a string
substr -- Return part of a string
trim --  Strip whitespace from the beginning and end of a string
ucfirst -- Make a string's first character uppercase
ucwords --  Uppercase the first character of each word in a string
vprintf -- Output a formatted string
vsprintf -- Return a formatted string
wordwrap --  Wraps a string to a given number of characters using a string break character.

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 sranno 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 37.

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

chop -- Alias di rtrim()

Descrizione

Questa funzione è un alias di 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 diescape 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

convert_uudecode

(PHP 5)

convert_uudecode --  Decodifica una stringa codificata con uuencode

Descrizione

string convert_uudecode ( string data)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

convert_uuencode

(PHP 5)

convert_uuencode --  Codifica uuencode di una stringa

Descrizione

string convert_uuencode ( string data)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

Alcuni sistemi operativi supportano più di un tipo di criptazione. 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$

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

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

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.

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; // *

?>

Vedere anche preg_split(), spliti(), split() e implode().

fprintf

(PHP 5)

fprintf -- Write a formatted string to a stream

Description

int fprintf ( resource handle, string format [, mixed args])

Write a string produced according to the formatting string format to the stream resource specified by handle..

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to fprintf(), sprintf(), and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

  1. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

  2. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

  3. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

  4. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

  5. A type specifier that says what type the argument data should be treated as. Possible types:

    % - a literal percent character. No argument is required.
    b - the argument is treated as an integer, and presented as a binary number.
    c - the argument is treated as an integer, and presented as the character with that ASCII value.
    d - the argument is treated as an integer, and presented as a (signed) decimal number.
    u - the argument is treated as an integer, and presented as an unsigned decimal number.
    f - the argument is treated as a float, and presented as a floating-point number.
    o - the argument is treated as an integer, and presented as an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

See also: printf(), sprintf(), sscanf(), fscanf(), vsprintf(), and number_format().

Examples

Esempio 1. sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Esempio 2. sprintf(): formatting currency

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>

get_html_translation_table

(PHP 4 , PHP 5)

get_html_translation_table --  Returns the translation table used by htmlspecialchars() and htmlentities()

Description

array get_html_translation_table ( int table [, int quote_style])

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().

There are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. And as in the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. The default is ENT_COMPAT mode. See the description of these modes in htmlspecialchars().

Esempio 1. Translation Table Example

<?php
$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo & <Frau> & Krämer";
$encoded = strtr($str, $trans);
?>
The $encoded variable will now contain: "Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer".

Another interesting use of this function is to, with help of array_flip(), change the direction of the translation.

<?php
$trans = array_flip($trans);
$original = strtr($encoded, $trans);
?>

The content of $original would be: "Hallo & <Frau> & Krämer".

See also htmlspecialchars(), htmlentities(), strtr(), and array_flip().

hebrev

(PHP 3, PHP 4 , PHP 5)

hebrev --  Convert logical Hebrew text to visual text

Description

string hebrev ( string hebrew_text [, int max_chars_per_line])

The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.

See also hebrevc()

hebrevc

(PHP 3, PHP 4 , PHP 5)

hebrevc --  Convert logical Hebrew text to visual text with newline conversion

Description

string hebrevc ( string hebrew_text [, int max_chars_per_line])

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n". The optional parameter max_chars_per_line indicates maximum number of characters per line will be output. The function tries to avoid breaking words.

See also hebrev()

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5)

html_entity_decode --  Convert all HTML entities to their applicable characters

Description

string html_entity_decode ( string string [, int quote_style [, string charset]])

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities to their applicable characters from string.

The optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

Tabella 1. Available quote_style constants

Constant NameDescription
ENT_COMPATWill convert double-quotes and leave single-quotes alone.
ENT_QUOTESWill convert both double and single quotes.
ENT_NOQUOTESWill leave both double and single quotes unconverted.

The ISO-8859-1 character set is used as default for the optional third charset. This defines the character set used in conversion.

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. Decoding HTML entities

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


// For users prior to PHP 4.3.0 you may do this:
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: You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 characterset.

See also htmlentities(), htmlspecialchars(), get_html_translation_table(), and urldecode().

htmlentities

(PHP 3, PHP 4 , PHP 5)

htmlentities --  Convert all applicable characters to HTML entities

Description

string htmlentities ( string string [, int quote_style [, string charset]])

This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

Like htmlspecialchars(), the optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT:

Tabella 1. Available quote_style constants

Constant NameDescription
ENT_COMPATWill convert double-quotes and leave single-quotes alone.
ENT_QUOTESWill convert both double and single quotes.
ENT_NOQUOTESWill leave both double and single quotes unconverted.

Support for the optional quote parameter was added in PHP 4.0.3.

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Support for this argument was added in PHP 4.1.0. Presently, the ISO-8859-1 character set is used as the default.

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.

If you're wanting to decode instead (the reverse) you can use html_entity_decode().

Esempio 1. A htmlentities() example

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

See also html_entity_decode(), get_html_translation_table(), htmlspecialchars(), nl2br(), and urlencode().

htmlspecialchars

(PHP 3, PHP 4 , PHP 5)

htmlspecialchars --  Convert special characters to HTML entities

Description

string htmlspecialchars ( string string [, int quote_style [, string charset]])

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style, tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'

  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.

  • '<' (less than) becomes '&lt;'

  • '>' (greater than) becomes '&gt;'

Esempio 1. htmlspecialchars() example

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.

The third argument charset defines character set used in conversion. The default character set is ISO-8859-1. Support for this third argument was added 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.

See also get_html_translation_table(), strip_tags(), htmlentities(), and nl2br().

implode

(PHP 3, PHP 4 , PHP 5)

implode -- Join array elements with a string

Description

string implode ( string glue, array pieces)

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Esempio 1. implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?>

Nota: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Nota: As of PHP 4.3.0, the glue parameter of implode() is optional and defaults to the empty string(''). This is not the preferred usage of implode(). We recommend to always use two parameters for compatibility with older versions.

See also explode(), and split().

join

join -- Alias of implode()

Description

This function is an alias of implode().

levenshtein

(PHP 3>= 3.0.17, PHP 4 >= 4.0.1, PHP 5)

levenshtein --  Calculate Levenshtein distance between two strings

Description

int levenshtein ( string str1, string str2)

int levenshtein ( string str1, string str2, int cost_ins, int cost_rep, int cost_del)

int levenshtein ( string str1, string str2, function cost)

This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters (255 should be more than enough for name or dictionary comparison, and nobody serious would be doing genetic analysis with PHP).

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2.

A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient.

The third variant (which is not implemented yet) will be the most general and adaptive, but also the slowest alternative. It will call a user-supplied function that will determine the cost for every possible operation.

The user-supplied function will be called with the following arguments:

  • operation to apply: 'I', 'R' or 'D'

  • actual character in string 1

  • actual character in string 2

  • position in string 1

  • position in string 2

  • remaining characters in string 1

  • remaining characters in string 2

The user-supplied function has to return a positive integer describing the cost for this particular operation, but it may decide to use only some of the supplied arguments.

The user-supplied function approach offers the possibility to take into account the relevance of and/or difference between certain symbols (characters) or even the context those symbols appear in to determine the cost of insert, replace and delete operations, but at the cost of losing all optimizations done regarding cpu register utilization and cache misses that have been worked into the other two variants.

See also soundex(), similar_text(), and metaphone().

localeconv

(PHP 4 >= 4.0.5, PHP 5)

localeconv -- Get numeric formatting information

Description

array localeconv ( void )

Returns an associative array containing localized numeric and monetary formatting information.

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array elementDescription
decimal_pointDecimal point character
thousands_sepThousands separator
groupingArray containing numeric groupings
int_curr_symbolInternational currency symbol (i.e. USD)
currency_symbolLocal currency symbol (i.e. $)
mon_decimal_pointMonetary decimal point character
mon_thousands_sepMonetary thousands separator
mon_groupingArray containing monetary groupings
positive_signSign for positive values
negative_signSign for negative values
int_frac_digitsInternational fractional digits
frac_digitsLocal fractional digits
p_cs_precedes TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one
p_sep_by_space TRUE if a space separates currency_symbol from a positive value, FALSE otherwise
n_cs_precedes TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one
n_sep_by_space TRUE if a space separates currency_symbol from a negative value, FALSE otherwise
p_sign_posn

0 Parentheses surround the quantity and currency_symbol
1 The sign string precedes the quantity and currency_symbol
2 The sign string succeeds the quantity and currency_symbol
3 The sign string immediately precedes the currency_symbol
4 The sign string immediately succeeds the currency_symbol

n_sign_posn

0 Parentheses surround the quantity and currency_symbol
1 The sign string precedes the quantity and currency_symbol
2 The sign string succeeds the quantity and currency_symbol
3 The sign string immediately precedes the currency_symbol
4 The sign string immediately succeeds the currency_symbol

The grouping fields contain arrays that define the way numbers should be grouped. For example, the grouping field for the en_US locale, would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.

Esempio 1. localeconv() example

<?php
setlocale(LC_ALL, "en_US");

$locale_info = localeconv();

echo "<pre>\n";
echo "--------------------------------------------\n";
echo "  Monetary information for current 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";
?>

The constant CHAR_MAX is also defined for the use mentioned above.

See also setlocale().

ltrim

(PHP 3, PHP 4 , PHP 5)

ltrim --  Strip whitespace from the beginning of a string

Description

string ltrim ( string str [, string charlist])

Nota: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Esempio 1. Usage example of 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");
// trim the ASCII control characters at the beginning of $binary 
// (from 0 to 31 inclusive)

?>

See also trim() and rtrim().

md5_file

(PHP 4 >= 4.2.0, PHP 5)

md5_file -- Calculates the md5 hash of a given filename

Description

string md5_file ( string filename [, bool raw_output])

Calculates the MD5 hash of the specified filename using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Nota: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

This function has the same purpose of the command line utility md5sum.

See also md5(), crc32(), and sha1_file().

md5

(PHP 3, PHP 4 , PHP 5)

md5 -- Calculate the md5 hash of a string

Description

string md5 ( string str [, bool raw_output])

Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Nota: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

Esempio 1. A md5() example

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
    exit;
}
?>

See also crc32(), md5_file(), and sha1().

metaphone

(PHP 4 , PHP 5)

metaphone -- Calculate the metaphone key of a string

Description

string metaphone ( string str)

Calculates the metaphone key of str.

Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.

Metaphone was developed by Lawrence Philips <lphilips at verity dot com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

money_format

(PHP 4 >= 4.3.0, PHP 5)

money_format -- Formats a number as a currency string

Description

string money_format ( string format, float number)

money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.

Nota: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

The format specification consists of the following sequence:

  • a % character

  • optional flags

  • optional field width

  • optional left precision

  • optional right precision

  • a required conversion character

Flags. One or more of the optional flags below can be used:

=f

The character = followed by a a (single byte) character f to be used as the numeric fill character. The default fill character is space.

^

Disable the use of grouping characters (as defined by the current locale).

+ or (

Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.

!

Suppress the currency symbol from the output string.

-

If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).

Field width.

w

A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).

Left precision.

#n

The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.

If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.

To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.

Right precision .

.p

A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.

Conversion characters .

i

The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).

n

The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: DM1.234,56).

%

Returns the % character.

Nota: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.

Characters before and after the formatting string will be returned unchanged.

Esempio 1. money_format() Example

We will use different locales and format specifications to illustrate the use of this function.

<?php

$number = 1234.56;

// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";  
// USD 1,234.56

// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// L. 1.234,56

// Using a negative number
$number = -1234.5672;

// US national format, using () for negative numbers
// and 10 digits for left precision
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($        1,234.57)

// Similar format as above, adding the use of 2 digits of right 
// precision and '*' as a fill character
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)
    
// Let's justify to the left, with 14 positions of width, 8 digits of
// left precision, 2 of right precision, withouth grouping character
// and using the international format for the de_DE locale.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// DEM 1234,56****

// Let's add some blurb before and after the conversion specification
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)

?>

See also: setlocale(), number_format(),sprintf(), printf() and sscanf().

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5)

nl_langinfo --  Query language and locale information

Description

string nl_langinfo ( int item)

nl_langinfo() is used to access individual elements of the locale categories. Unlike localeconv(), which returns all of the elements, nl_langinfo() allows you to select any specific element.

If item is not valid, FALSE will be returned.

item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

Tabella 1. nl_langinfo Constants

ConstantDescription
LC_TIME Category Constants
ABDAY_(1-7)Abbreviated name of n-th day of the week.
DAY_(1-7)Name of the n-th day of the week (DAY_1 = Sunday).
ABMON_(1-12)Abbreviated name of the n-th month of the year.
MON_(1-12)Name of the n-th month of the year.
AM_STRString for Ante meridian.
PM_STRString for Post meridian.
D_T_FMTString that can be used as the format string for strftime() to represent time and date.
D_FMTString that can be used as the format string for strftime() to represent date.
T_FMTString that can be used as the format string for strftime() to represent time.
T_FMT_AMPMString that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian.
ERAAlternate era.
ERA_YEARYear in alternate era format.
ERA_D_T_FMTDate and time in alternate era format (string can be used in strftime()).
ERA_D_FMTDate in alternate era format (string can be used in strftime()).
ERA_T_FMTTime in alternate era format (string can be used in strftime()).
LC_MONETARY Category Constants
INT_CURR_SYMBOLInternational currency symbol.
CURRENCY_SYMBOLLocal currency symbol.
CRNCYSTRSame value as CURRENCY_SYMBOL.
MON_DECIMAL_POINTDecimal point character.
MON_THOUSANDS_SEPThousands separator (groups of three digits).
MON_GROUPINGLike 'grouping' element.
POSITIVE_SIGNSign for positive values.
NEGATIVE_SIGNSign for negative values.
INT_FRAC_DIGITSInternational fractional digits.
FRAC_DIGITSLocal fractional digits.
P_CS_PRECEDESReturns 1 if CURRENCY_SYMBOL precedes a positive value.
P_SEP_BY_SPACEReturns 1 if a space separates CURRENCY_SYMBOL from a positive value.
N_CS_PRECEDESReturns 1 if CURRENCY_SYMBOL precedes a negative value.
N_SEP_BY_SPACEReturns 1 if a space separates CURRENCY_SYMBOL from a negative value.
P_SIGN_POSN

  • Returns 0 if parentheses surround the quantity and currency_symbol.

  • Returns 1 if the sign string precedes the quantity and currency_symbol.

  • Returns 2 if the sign string follows the quantity and currency_symbol.

  • Returns 3 if the sign string immediately precedes the currency_symbol.

  • Returns 4 if the sign string immediately follows the currency_symbol.

N_SIGN_POSN
LC_NUMERIC Category Constants
DECIMAL_POINTDecimal point character.
RADIXCHARSame value as DECIMAL_POINT.
THOUSANDS_SEPSeparator character for thousands (groups of three digits).
THOUSEPSame value as THOUSANDS_SEP.
GROUPING 
LC_MESSAGES Category Constants
YESEXPRRegex string for matching 'yes' input.
NOEXPRRegex string for matching 'no' input.
YESSTROutput string for 'yes'.
NOSTROutput string for 'no'.
LC_CTYPE Category Constants
CODESETReturn a string with the name of the character encoding.

Nota: Questa funzione non è implementata su piattaforme Windows

See also setlocale() and localeconv().

nl2br

(PHP 3, PHP 4 , PHP 5)

nl2br --  Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string string)

Returns string with '<br />' inserted before all newlines.

Nota: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with '<br>' inserted before newlines instead of '<br />'.

Esempio 1. using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

this will output :

foo isn't<br />
 bar

See also htmlspecialchars(), htmlentities(), wordwrap(), and str_replace().

number_format

(PHP 3, PHP 4 , PHP 5)

number_format -- Format a number with grouped thousands

Description

string number_format ( float number [, int decimals])

string number_format ( float number, int decimals, string dec_point, string thousands_sep)

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.

Esempio 1. number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. This is achieved with this line :

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,234

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

See also: sprintf(), printf() and sscanf().

ord

(PHP 3, PHP 4 , PHP 5)

ord -- Return ASCII value of character

Description

int ord ( string string)

Returns the ASCII value of the first character of string. This function complements chr().

Esempio 1. ord() example

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

You can find an ASCII-table over here: http://www.asciitable.com.

See also chr().

parse_str

(PHP 3, PHP 4 , PHP 5)

parse_str -- Parses the string into variables

Description

void parse_str ( string str [, array arr])

Parses str as if it were the query string passed via a URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as array elements instead.

Nota: Support for the optional second parameter was added in PHP 4.0.3.

Nota: To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from outside of PHP.

Esempio 1. Using 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

?>

See also parse_url(), pathinfo(), set_magic_quotes_runtime(), and urldecode().

print

(PHP 3, PHP 4, PHP 5 )

print -- Output a string

Description

int print ( string arg)

Outputs arg. Returns 1, always.

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.

Esempio 1. print() examples

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

// You can use variables inside of a print statement
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" => "foo");

print "this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
print 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just print variables
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;
?>

For a short discussion about the differences between print() and echo(), see this 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

See also echo(), printf(), and flush().

printf

(PHP 3, PHP 4 , PHP 5)

printf -- Output a formatted string

Description

void printf ( string format [, mixed args])

Produces output according to format, which is described in the documentation for sprintf().

See also print(), sprintf(), vprintf(), sscanf(), fscanf(), and flush().

quoted_printable_decode

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

quoted_printable_decode --  Convert a quoted-printable string to an 8 bit string

Description

string quoted_printable_decode ( string str)

This function returns an 8-bit binary string corresponding to the decoded quoted printable string. This function is similar to imap_qprint(), except this one does not require the IMAP module to work.

quotemeta

(PHP 3, PHP 4 , PHP 5)

quotemeta -- Quote meta characters

Description

string quotemeta ( string str)

Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ )

See also addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().

rtrim

(PHP 3, PHP 4 , PHP 5)

rtrim --  Strip whitespace from the end of a string

Description

string rtrim ( string str [, string charlist])

Nota: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Esempio 1. Usage example of 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");
// trim the ASCII control characters at the end of $binary 
// (from 0 to 31 inclusive)

?>

See also trim() and ltrim().

setlocale

(PHP 3, PHP 4 , PHP 5)

setlocale -- Set locale information

Description

string setlocale ( mixed category, string locale [, string ...])

string setlocale ( mixed category, array locale)

category is a named constant (or string) specifying the category of the functions affected by the locale setting:

  • LC_ALL for all of the below

  • LC_COLLATE for string comparison, see strcoll()

  • LC_CTYPE for character classification and conversion, for example strtoupper()

  • LC_MONETARY for localeconv()

  • LC_NUMERIC for decimal separator (See also localeconv())

  • LC_TIME for date and time formatting with strftime()

Nota: As of PHP 4.2.0, passing category as a string is deprecated, use the above constants instead. Passing them as a string (within quotes) will result in a warning message.

If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".

If locale is NULL or "0", the locale setting is not affected, only the current setting is returned.

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

Nota: Passing multiple locales is not available before PHP 4.3.0

Setlocale returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message. Category/locale names can be found in RFC 1766 and ISO 639.

Nota: The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

Suggerimento: Windows users will find useful information about locale strings at Microsoft's MSDNwebsite. Supported language strings can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp and supported country/region strings at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp. Windows systems support the three letter codes for country/region specified by ISO 3166-Alpha-3, which can be found at this Unicode website .

Esempio 1. setlocale() Examples

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of 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. setlocale() Examples for Windows

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of 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 -- Calculate the sha1 hash of a file

Description

string sha1_file ( string filename [, bool raw_output])

Calculates the sha1 hash of filename using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number. Upon failure, FALSE is returned. If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20.

Nota: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

See also sha1(), crc32(), and md5_file()

sha1

(PHP 4 >= 4.3.0, PHP 5)

sha1 -- Calculate the sha1 hash of a string

Description

string sha1 ( string str [, bool raw_output])

Calculates the sha1 hash of str using the US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number. If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20.

Nota: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

Esempio 1. A sha1() example

<?php
$str = 'apple';
                     
if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
    exit;
}
?>

See also sha1_file(), crc32(), and md5()

similar_text

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

similar_text --  Calculate the similarity between two strings

Description

int similar_text ( string first, string second [, float percent])

This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.

soundex

(PHP 3, PHP 4 , PHP 5)

soundex -- Calculate the soundex key of a string

Description

string soundex ( string str)

Calculates the soundex key of str.

Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.

This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

Esempio 1. Soundex Examples

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

See also levenshtein(), metaphone(), and similar_text().

sprintf

(PHP 3, PHP 4 , PHP 5)

sprintf -- Return a formatted string

Description

string sprintf ( string format [, mixed args])

Returns a string produced according to the formatting string format.

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

  1. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

  2. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

  3. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

  4. An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

  5. A type specifier that says what type the argument data should be treated as. Possible types:

    % - a literal percent character. No argument is required.
    b - the argument is treated as an integer, and presented as a binary number.
    c - the argument is treated as an integer, and presented as the character with that ASCII value.
    d - the argument is treated as an integer, and presented as a (signed) decimal number.
    e - the argument is treated as scientific notation (e.g. 1.2e+2).
    u - the argument is treated as an integer, and presented as an unsigned decimal number.
    f - the argument is treated as a float, and presented as a floating-point number.
    o - the argument is treated as an integer, and presented as an octal number.
    s - the argument is treated as and presented as a string.
    x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

As of PHP 4.0.6 the format string supports argument numbering/swapping. Here is an example:

Esempio 1. Argument swapping

<?php
$format = "There are %d monkeys in the %s";
printf($format, $num, $location);
?>
This might output, "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:

Esempio 2. Argument swapping

<?php
$format = "The %s contains %d monkeys";
printf($format, $num, $location);
?>
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Esempio 3. Argument swapping

<?php
$format = "The %2\$s contains %1\$d monkeys";
printf($format, $num, $location);
?>
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Esempio 4. Argument swapping

<?php
$format = "The %2\$s contains %1\$d monkeys.
           That's a nice %2\$s full of %1\$d monkeys.";
printf($format, $num, $location);
?>

See also printf(), sscanf(), fscanf(), vsprintf(), and number_format().

Examples

Esempio 5. sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Esempio 6. sprintf(): formatting currency

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>

Esempio 7. sprintf(): scientific notation

<?php
$number = 362525200;

echo sprintf("%.3e", $number); // outputs 3.63e+8
?>

sscanf

(PHP 4 >= 4.0.1, PHP 5)

sscanf --  Parses input from a string according to a format

Description

mixed sscanf ( string str, string format [, string var1])

The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.

Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \t in the format string can match a single space character in the input string.

Esempio 1. sscanf() Example

<?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";
?>
If optional parameters are passed, the function will return the number of assigned values.

Esempio 2. sscanf() - using optional parameters

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

See also fscanf(), printf(), and sprintf().

str_ireplace

(PHP 5)

str_ireplace --  Case-insensitive version of str_replace().

Description

mixed str_ireplace ( mixed search, mixed replace, mixed subject [, int &count])

This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. If you don't need fancy replacing rules, you should generally use this function instead of eregi_replace() or preg_replace() with the i modifier.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.

Esempio 1. str_ireplace() example

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
?>

This function is binary safe.

Nota: As of PHP 5.0.0 the number of matched and replaced needles will be returned in count which is passed by reference. Prior to PHP 5.0.0 this parameter is not available.

See also: str_replace(), ereg_replace(), preg_replace(), and strtr().

str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_pad --  Pad a string to a certain length with another string

Description

string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]])

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

If the value of pad_length is negative or less than the length of the input string, no padding takes place.

Esempio 1. str_pad() example

<?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: The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

str_repeat

(PHP 4 , PHP 5)

str_repeat -- Repeat a string

Description

string str_repeat ( string input, int multiplier)

Returns input_str repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

Esempio 1. str_repeat() example

<?php
echo str_repeat("-=", 10);
?>

This will output "-=-=-=-=-=-=-=-=-=-=".

See also for, str_pad(), and substr_count().

str_replace

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

str_replace --  Replace all occurrences of the search string with the replacement string

Description

mixed str_replace ( mixed search, mixed replace, mixed subject [, int &count])

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value. If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

As of PHP 4.0.5, every parameter in str_replace() can be an array.

Avvertimento

In PHP versions prior to 4.3.3 a bug existed when using arrays as both search and replace parameters which caused empty search indexes to be skipped without advancing the internal pointer on the replace array. This has been corrected in PHP 4.3.3, any scripts which relied on this bug should remove empty search values prior to calling this function in order to mimick the original behavior.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.

Esempio 1. str_replace() examples

<?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: As of PHP 5.0.0 the number of matched and replaced needles (search) will be returned in count which is passed by reference. Prior to PHP 5.0.0 this parameter is not available.

See also str_ireplace(), substr_replace(), ereg_replace(), preg_replace(), and strtr().

str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 -- Perform the rot13 transform on a string

Description

string str_rot13 ( string str)

This function performs the ROT13 encoding on the str argument and returns the resulting string. The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.

Esempio 1. str_rot13() example

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

Nota: The behaviour of this function was buggy until PHP 4.3.0. Before this, the str was also modified, as if passed by reference.

str_shuffle

(PHP 4 >= 4.3.0, PHP 5)

str_shuffle -- Randomly shuffles a string

Description

string str_shuffle ( string str)

str_shuffle() shuffles a string. One permutation of all possible is created.

Esempio 1. str_shuffle() example

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

See also shuffle() and rand().

str_split

(PHP 5)

str_split --  Convert a string to an array

Description

array str_split ( string string [, int split_length])

Converts a string to an array. If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.

FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.

Esempio 1. Example uses of str_split()

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

Output may look like:

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. Examples related to 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);

?>

See also chunk_split(), preg_split(), split(), count_chars(), str_word_count(), and for.

str_word_count

(PHP 4 >= 4.3.0, PHP 5)

str_word_count --  Return information about words used in a string

Description

mixed str_word_count ( string string [, int format])

Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

  • 1 - returns an array containing all the words found inside the string.

  • 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.

Esempio 1. Example uses for str_word_count()

<?php

$str = "Hello friend, you're
        looking          good today!";

$a   = str_word_count($str, 1);
$b   = str_word_count($str, 2);
$c   = str_word_count($str);

print_r($a);
print_r($b);
echo $c;
?>

Output may look like:

Array
(
    [0] => Hello
    [1] => friend
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

Array
(
    [0] => Hello
    [6] => friend
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

6

See also explode(), preg_split(), split(), count_chars(), and substr_count().

strcasecmp

(PHP 3>= 3.0.2, PHP 4 , PHP 5)

strcasecmp --  Binary safe case-insensitive string comparison

Description

int strcasecmp ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Esempio 1. strcasecmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

See also ereg(), strcmp(), substr(), stristr(), strncasecmp(), and strstr().

strchr

strchr -- Alias of strstr()

Description

This function is an alias of strstr().

strcmp

(PHP 3, PHP 4 , PHP 5)

strcmp -- Binary safe string comparison

Description

int strcmp ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), and strstr().

strcoll

(PHP 4 >= 4.0.5, PHP 5)

strcoll -- Locale based string comparison

Description

int strcoll ( string str1, string str2)

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

Nota: strcoll() was added in PHP 4.0.5, but was not enabled for win32 until 4.2.3.

See also ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr(), and setlocale().

strcspn

(PHP 3>= 3.0.3, PHP 4 , PHP 5)

strcspn --  Find length of initial segment not matching mask

Description

int strcspn ( string str1, string str2 [, int start [, int length]])

Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

As of PHP 4.0B1 this function is binary safe. Additionally it accepts two optional integer parameters that can be used to define the starting position and the length of the string to examine.

See also strspn().

strip_tags

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

strip_tags -- Strip HTML and PHP tags from a string

Description

string strip_tags ( string str [, string allowable_tags])

This function tries to return a string with all HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

You can use the optional second parameter to specify tags which should not be stripped.

Nota: allowable_tags was added in PHP 3.0.13 and PHP 4.0b3. Since PHP 4.3.0, HTML comments are also stripped.

Avvertimento

Because strip_tags() does not actually validate the HTML, partial, or broken tags can result in the removal of more text/data than expected.

Esempio 1. strip_tags() example

<?php
$text = '
<p>Test paragraph.</p>
<!-- Comment -->
Other text';

echo strip_tags($text);

echo "\n\n-------\n";

// allow <p>
echo strip_tags($text, '<p>');
?>

The above example will output:

Test paragraph.

Other text

-------

<p>Test paragraph.</p>

Other text

Avvertimento

This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

See also htmlspecialchars().

stripcslashes

(PHP 4 , PHP 5)

stripcslashes --  Un-quote string quoted with addcslashes()

Description

string stripcslashes ( string str)

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

See also addcslashes().

stripos

(PHP 5)

stripos --  Find position of first occurrence of a case-insensitive string

Description

int stripos ( string haystack, string needle [, int offset])

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.

Note that the needle may be a string of one or more characters.

If needle is not found, stripos() will return 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. stripos() examples

<?php
$findme    = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// Nope, 'a' is certainly not in 'xyz'
if ($pos1 === false) {
    echo "The string '$findme' was not found in the string '$mystring1'";
}

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' is the 0th (first) character.
if ($pos2 !== false) {
    echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.

See also strpos(), strrpos(), strrchr(), substr(), stristr(), strstr(), strripos() and str_ireplace().

stripslashes

(PHP 3, PHP 4 , PHP 5)

stripslashes --  Un-quote string quoted with addslashes()

Description

string stripslashes ( string str)

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

Esempio 1. A stripslashes() example

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

See also addslashes() and get_magic_quotes_gpc().

stristr

(PHP 3>= 3.0.6, PHP 4 , PHP 5)

stristr --  Case-insensitive strstr()

Description

string stristr ( string haystack, string needle)

Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Esempio 1. stristr() example

<?php
  $email = 'USER@EXAMPLE.com';
  $domain = stristr($email, 'e');
  echo $domain; 
// outputs ER@EXAMPLE.com
?>

See also strstr(), strrchr(), substr(), and ereg().

strlen

(PHP 3, PHP 4 , PHP 5)

strlen -- Get string length

Description

int strlen ( string string)

Returns the length of the given string.

Esempio 1. A strlen() example

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

See also count().

strnatcasecmp

(PHP 4 , PHP 5)

strnatcasecmp --  Case insensitive string comparisons using a "natural order" algorithm

Description

int strnatcasecmp ( string str1, string str2)

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more information see: Martin Pool's Natural Order String Comparison page.

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcmp(), and strstr().

strnatcmp

(PHP 4 , PHP 5)

strnatcmp --  String comparisons using a "natural order" algorithm

Description

int strnatcmp ( string str1, string str2)

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:

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

The code above will generate the following output:

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
)

For more information see: Martin Pool's Natural Order String Comparison page.

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() and natcasesort().

strncasecmp

(PHP 4 >= 4.0.2, PHP 5)

strncasecmp --  Binary safe case-insensitive string comparison of the first n characters

Description

int strncasecmp ( string str1, string str2, int len)

This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See also ereg(), strcasecmp(), strcmp(), substr(), stristr(), and strstr().

strncmp

(PHP 4 , PHP 5)

strncmp --  Binary safe string comparison of the first n characters

Description

int strncmp ( string str1, string str2, int len)

This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

See also ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp(), and strstr().

strpbrk

(PHP 5)

strpbrk --  Search a string for any of a set of characters

Description

string strpbrk ( string haystack, string char_list)

strpbrk() searches the haystack string for a char_list, and returns a string starting from the character found (or FALSE if it is not found).

Nota: The char_list parameter is case sensitive.

Esempio 1. strpbrk() example

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

strpos

(PHP 3, PHP 4 , PHP 5)

strpos --  Find position of first occurrence of a string

Description

int strpos ( string haystack, string needle [, int offset])

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.

If needle is not found, strpos() will return 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. strpos() examples

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
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";
}

// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.

See also strrpos(), stripos(), strripos(), strrchr(), substr(), stristr(), and strstr().

strrchr

(PHP 3, PHP 4 , PHP 5)

strrchr --  Find the last occurrence of a character in a string

Description

string strrchr ( string haystack, char needle)

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Returns FALSE if needle is not found.

If needle contains more than one character, only the first is used. This behavior is different from that of strchr().

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Esempio 1. strrchr() example

<?php
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

See also strstr(), substr(), and stristr().

strrev

(PHP 3, PHP 4 , PHP 5)

strrev -- Reverse a string

Description

string strrev ( string string)

Returns string, reversed.

Esempio 1. Reversing a string with strrev()

<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>

strripos

(PHP 5)

strripos --  Find position of last occurrence of a case-insensitive string in a string

Description

int strripos ( string haystack, string needle [, int offset])

Returns the numeric position of the last occurrence of needle in the haystack string. Unlike strrpos(), strripos() is case-insensitive. Also note that string positions start at 0, and not 1.

Note that the needle may be a string of one or more characters.

If needle is not found, FALSE is returned.

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. A simple strripos() example

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

Outputs:

Congratulations!
   We found the last (aB) in (ababcd) at position (2)

offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.

See also strrpos(), strrchr(), substr(), stripos() and stristr().

strrpos

(PHP 3, PHP 4 , PHP 5)

strrpos --  Find position of last occurrence of a char in a string

Description

int strrpos ( string haystack, string needle [, int offset])

Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character in PHP 4. If a string is passed as the needle, then only the first character of that string will be used.

If needle is not found, returns FALSE.

It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

<?php

// in PHP 4.0b3 and newer:
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

// in versions older than 4.0b3:
$pos = strrpos($mystring, "b");
if (is_bool($pos) && !$pos) {
    // not found...
}
?>

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Nota: As of PHP 5.0.0 offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.

Nota: The needle may be a string of more than one character as of PHP 5.0.0.

See also strpos(), strripos(), strrchr(), substr(), stristr(), and strstr().

strspn

(PHP 3>= 3.0.3, PHP 4 , PHP 5)

strspn --  Find length of initial segment matching mask

Description

int strspn ( string str1, string str2 [, int start [, int length]])

Returns the length of the initial segment of str1 which consists entirely of characters in str2.

The line of code:

<?php
$var = strspn("42 is the answer, what is the question ...", "1234567890");
?>

will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".

As of PHP 4.0B1 this function is binary safe. Additionally it accepts two optional integer parameters that can be used to define the starting position and the length of the string to examine.

<?php
echo strspn("foo", "o", 1, 2); // 2
?>

See also strcspn().

strstr

(PHP 3, PHP 4 , PHP 5)

strstr -- Find first occurrence of a string

Description

string strstr ( string haystack, string needle)

Returns part of haystack string from the first occurrence of needle to the end of haystack.

If needle is not found, returns FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Nota: This function is case-sensitive. For case-insensitive searches, use stristr().

Esempio 1. strstr() example

<?php
$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>

Nota: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

See also ereg(), preg_match(), stristr(), strpos(), strrchr(), and substr().

strtok

(PHP 3, PHP 4 , PHP 5)

strtok -- Tokenize string

Description

string strtok ( string arg1, string arg2)

strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.

Esempio 1. strtok() example

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");
while ($tok) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.

The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:

Esempio 2. Old strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(0) ""
    string(9) "something"

Esempio 3. New strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(9) "something"
    bool(false)

Also be careful that your tokens may be equal to "0". This evaluates to FALSE in conditional expressions.

See also split() and explode().

strtolower

(PHP 3, PHP 4 , PHP 5)

strtolower -- Make a string lowercase

Description

string strtolower ( string str)

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

Esempio 1. strtolower() example

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

See also strtoupper(), ucfirst(), ucwords() and mb_strtolower().

strtoupper

(PHP 3, PHP 4 , PHP 5)

strtoupper -- Make a string uppercase

Description

string strtoupper ( string string)

Returns string with all alphabetic characters converted to uppercase.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Esempio 1. strtoupper() example

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

See also strtolower(), ucfirst(), ucwords() and mb_strtoupper().

strtr

(PHP 3, PHP 4 , PHP 5)

strtr -- Translate certain characters

Description

string strtr ( string str, string from, string to)

string strtr ( string str, array replace_pairs)

This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to.

If from and to are different lengths, the extra characters in the longer of the two are ignored.

Esempio 1. strtr() example

<?php
$addr = strtr($addr, "äåö", "aao");
?>

strtr() may be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.

Esempio 2. strtr() example with two arguments

<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

This will show:

hello all, I said hi

Nota: This optional to and from parameters were added in PHP 4.0.0

See also ereg_replace().

substr_compare

(PHP 5)

substr_compare --  Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters

Description

int substr_compare ( string main_str, string str, int offset [, int length [, bool case_sensitivity]])

substr_compare() compares main_str from position offset with str up to length characters.

Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If length is equal or greater than length of main_str and length is set, substr_compare() prints warning and returns FALSE.

If case_sensitivity is TRUE, comparison is case sensitive.

Esempio 1. A substr_compare() example

<?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 -- Count the number of substring occurrences

Description

int substr_count ( string haystack, string needle)

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

Esempio 1. substr_count() example

<?php
echo substr_count("This is a test", "is"); // prints out 2
?>

See also count_chars(), strpos(), substr(), and strstr().

substr_replace

(PHP 4 , PHP 5)

substr_replace -- Replace text within a portion of a string

Description

string substr_replace ( string string, string replacement, int start [, int length])

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.

If start is positive, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.

Esempio 1. substr_replace() example

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

See also str_replace() and substr().

substr

(PHP 3, PHP 4 , PHP 5)

substr -- Return part of a string

Description

string substr ( string string, int start [, int length])

substr() returns the portion of string specified by the start and length parameters.

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

Esempio 1. Basic substr() usage

<?php
$rest = substr("abcdef", 1);    // returns "bcdef"
$rest = substr("abcdef", 1, 3); // returns "bcd"
$rest = substr("abcdef", 0, 4); // returns "abcd"
$rest = substr("abcdef", 0, 8); // returns "abcdef"

// Accessing via curly braces is another option
$string = 'abcdef';
echo $string{0};                // returns a
echo $string{3};                // returns d
?>

If start is negative, the returned string will start at the start'th character from the end of string.

Esempio 2. Using a negative start

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than or equal to start characters long, FALSE will be returned.

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.

Esempio 3. Using a negative 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"
?>

See also strrchr(), substr_replace(), ereg(), trim(), mb_substr() and wordwrap().

trim

(PHP 3, PHP 4 , PHP 5)

trim --  Strip whitespace from the beginning and end of a string

Description

string trim ( string str [, string charlist])

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.

  • "\t" (ASCII 9 (0x09)), a tab.

  • "\n" (ASCII 10 (0x0A)), a new line (line feed).

  • "\r" (ASCII 13 (0x0D)), a carriage return.

  • "\0" (ASCII 0 (0x00)), the NUL-byte.

  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Esempio 1. Usage example of 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 :)"

// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");

?>

Nota: The optional charlist parameter was added in PHP 4.1.0

See also ltrim() and rtrim().

ucfirst

(PHP 3, PHP 4 , PHP 5)

ucfirst -- Make a string's first character uppercase

Description

string ucfirst ( string str)

Returns a string with the first character of str capitalized, if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Esempio 1. ucfirst() example

<?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

See also strtolower(), strtoupper(), and ucwords().

ucwords

(PHP 3>= 3.0.3, PHP 4 , PHP 5)

ucwords --  Uppercase the first character of each word in a string

Description

string ucwords ( string str)

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Esempio 1. ucwords() example

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World! 

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

See also strtoupper(), strtolower() and ucfirst().

vprintf

(PHP 4 >= 4.1.0, PHP 5)

vprintf -- Output a formatted string

Description

void vprintf ( string format, array args)

Display array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.

See also printf(), sprintf(), vsprintf()

vsprintf

(PHP 4 >= 4.1.0, PHP 5)

vsprintf -- Return a formatted string

Description

string vsprintf ( string format, array args)

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

See also sprintf() and vprintf()

wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap --  Wraps a string to a given number of characters using a string break character.

Description

string wordwrap ( string str [, int width [, string break [, boolean cut]]])

Returns a string with str wrapped at the column number specified by the optional width parameter. The line is broken using the (optional) break parameter.

wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.

If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).

Nota: The optional cut parameter was added in PHP 4.0.3

Esempio 1. wordwrap() example

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

This example would display:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Esempio 2. wordwrap() example

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", 1);

echo "$newtext\n";
?>

This example would display:

A very
long
wooooooo
ooooord.

See also nl2br() and chunk_split().

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

NameDefaultChangeable
sybase.allow_persistent"On"PHP_INI_SYSTEM
sybase.max_persistent"-1"PHP_INI_SYSTEM
sybase.max_links"-1"PHP_INI_SYSTEM
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"Off"PHP_INI_SYSTEM
magic_quotes_sybase"Off"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

Compatability 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 compatability 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

NameDefaultChangeable
sybct.allow_persistent"On"PHP_INI_SYSTEM
sybct.max_persistent"-1"PHP_INI_SYSTEM
sybct.max_links"-1"PHP_INI_SYSTEM
sybct.min_server_severity"10"PHP_INI_ALL
sybct.min_client_severity"10"PHP_INI_ALL
sybct.hostnameNULLPHP_INI_ALL
sybct.deadlock_retry_count"-1"PHP_INI_ALL

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 to define how often deadlocks are to be retried. The default is -1, or "forever".

For further details and definition of the PHP_INI_* constants see ini_set().


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

The above example would produce the following output:

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

Nota: Questa funzione è disponibile soltanto usando la libreria CT e non la libreria DB.

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

resource sybase_query ( string query, resource link_identifier)

Returns a positive Sybase result identifier on success, or FALSE on error.

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

See also sybase_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().

CXI. 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 --  tcpwrap check

tcpwrap_check

(no version information, might be only in CVS)

tcpwrap_check --  tcpwrap check

Description

bool tcpwrap_check ( string daemon, string address [, string user [, bool nodns]])

This function consults /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for client with remote address address (and optional username user). address can be either IP address or domain name. user can be NULL.

If address looks like domain name then DNS is used to resolve it to IP address; set nodns to TRUE to avoid this.

For more details please consult hosts_access(3) man page.

This function returns TRUE if access should be granted, FALSE otherwise.

CXII. Tidy Functions

Introduzione

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipluate 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

NameDefaultChangeableFunction
tidy.default_config""PHP_INI_SYSTEMdefault path for tidy config file
tidy.clean_output0PHP_INI_PERDIRturns on/off the output repairing by Tidy
For further details and definition of the PHP_INI_* constants see ini_set().

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.


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.

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

constantdescription
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_ROOT 
TIDY_NODETYPE_DOCTYPE 
TIDY_NODETYPE_COMMENT 
TIDY_NODETYPE_PROCINS 
TIDY_NODETYPE_TEXT 
TIDY_NODETYPE_START 
TIDY_NODETYPE_END 
TIDY_NODETYPE_STARTEND 
TIDY_NODETYPE_CDATA 
TIDY_NODETYPE_SECTION 
TIDY_NODETYPE_ASP 
TIDY_NODETYPE_JSTE 
TIDY_NODETYPE_PHP 
TIDY_NODETYPE_XMLDECL 

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_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->attributes --  Returns an array of attribute objects for node
tidy_node->children --  Returns an array of child nodes
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->hasChildren --  Returns true if this node has children
tidy_node->hasSiblings --  Returns true if this node has siblings
tidy_node->isAsp --  Returns true if this node is ASP
tidy_node->isComment --  Returns true if this node represents a comment
tidy_node->isHtml --  Returns true if this node is part of a HTML document
tidy_node->isJste --  Returns true if this node is JSTE
tidy_node->isPhp --  Returns true if this node is PHP
tidy_node->isText --  Returns true if this node represents text (no markup)
tidy_node->isXhtml --  Returns true if this node is part of a XHTML document
tidy_node->isXml --  Returns true if this node is part of a XML document
tidy_node->next --  Returns the next sibling to this node
tidy_node->prev --  Returns the previous sibling to this node
tidy_node->tidy_node --  Constructor.
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. Only non-default values are written.
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.

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

The above example will output:

<!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 ( resource tidy)

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

Object oriented style:

bool tidy->cleanRepair ( void )

This function cleans and repairs the given tidy resource.

Esempio 1. tidy_clean_repair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
tidy_clean_repair($tidy);

echo $tidy;
?>

The above example will output:

<!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 ( resource tidy)

tidy_config_count() returns the number of errors encountered in the given configuration.

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

object 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 initializate 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;
}

?>

The above example will output:

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

Object oriented style:

bool tidy->diagnose ( void )

tidy_diagnose() runs diagnostic tests on the given resource.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

tidy_error_count

(PHP 5)

tidy_error_count --  Returns the Number of Tidy errors encountered for specified document.

Description

int tidy_error_count ( resource tidy)

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

The above example will output:

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:

object tidy_get_body ( resource tidy)

Object oriented style:

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

The above example will output:

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

Object oriented style:

array tidy->getConfig ( void )

tidy_get_config() returns an array with the configuration options in use by the given resource.

For a 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));
?>

The above example will output:

Array
(
    [indent-spaces] => 2
    [wrap] => 68
    [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] => 
)

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

string tidy_get_error_buffer ( resource tidy)

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

The above example will output:

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:

object tidy_get_head ( resource tidy)

Object oriented style:

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

The above example will output:

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

Object oriented style:

int tidy->getHtmlVer ( void )

tidy_get_html_ver() returns the detected HTML version for the specified tidy resource.

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:

object tidy_get_html ( resource tidy)

Object oriented style:

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

The above example will output:

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

(PHP 5)

tidy_get_output --  Return a string representing the parsed tidy markup

Description

string tidy_get_output ( resource tidy)

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

The above example will output:

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

object tidy_get_root ( resource tidy)

Object oriented style:

object tidy->root ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

Object oriented style:

int tidy->getStatus ( void )

tidy_get_status() returns the status for the specified tidy resource. 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 ( resource tidy, string option)

Object oriented style:

mixed tidy->getOpt ( string option)

tidy_getopt() returns the value of the specified option for the specified tidy document. 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

?>

The above example will output:

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

Object oriented style:

object 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 ( resource tidy)

Object oriented style:

object 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->attributes

(no version information, might be only in CVS)

tidy_node->attributes --  Returns an array of attribute objects for node

Description

array tidy_node->attributes ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

tidy_node->children

(no version information, might be only in CVS)

tidy_node->children --  Returns an array of child nodes

Description

array tidy_node->children ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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

(no version information, might be only in CVS)

tidy_node->hasChildren --  Returns true if this node has children

Description

bool tidy_node->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.

tidy_node->hasSiblings

(no version information, might be only in CVS)

tidy_node->hasSiblings --  Returns true if this node has siblings

Description

bool tidy_node->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.

tidy_node->isAsp

(no version information, might be only in CVS)

tidy_node->isAsp --  Returns true if this node is ASP

Description

bool tidy_node->isAsp ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_asp() in PHP 4/Tidy 1.

tidy_node->isComment

(no version information, might be only in CVS)

tidy_node->isComment --  Returns true if this node represents a comment

Description

bool tidy_node->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.

tidy_node->isHtml

(no version information, might be only in CVS)

tidy_node->isHtml --  Returns true if this node is part of a HTML document

Description

bool tidy_node->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.

tidy_node->isJste

(no version information, might be only in CVS)

tidy_node->isJste --  Returns true if this node is JSTE

Description

bool tidy_node->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.

tidy_node->isPhp

(no version information, might be only in CVS)

tidy_node->isPhp --  Returns true if this node is PHP

Description

bool tidy_node->isPhp ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_php() in PHP 4/Tidy 1.

tidy_node->isText

(no version information, might be only in CVS)

tidy_node->isText --  Returns true if this node represents text (no markup)

Description

bool tidy_node->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.

tidy_node->isXhtml

(no version information, might be only in CVS)

tidy_node->isXhtml --  Returns true if this node is part of a XHTML document

Description

bool tidy_node->isXhtml ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This functions was named tidy_node->is_xhtml() in PHP 4/Tidy 1.

tidy_node->isXml

(no version information, might be only in CVS)

tidy_node->isXml --  Returns true if this node is part of a XML document

Description

bool tidy_node->isXml ( void )

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

Nota: This function was named tidy_node->is_xml() in PHP 4/Tidy 1.

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_node->tidy_node

(no version information, might be only in CVS)

tidy_node->tidy_node --  Constructor.

Description

void tidy_node->tidy_node ( 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:

resource 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_parse_string() and tidy_repair_string().

tidy_parse_string

(PHP 5)

tidy_parse_string --  Parse a document stored in a string

Description

Procedural style:

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

The above example will output:

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

The above example will output:

<!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. Only non-default values are written.

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

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

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

Nota: T_ML_COMMENT is not defined in PHP 5. All comments in PHP 5 are of token T_COMMENT.

T_DOC_COMMENT (integer)

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


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
  $source = file_get_contents("somefile.php");
  $tokens = token_get_all($source);
  /* 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);
  }
  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

Description

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. The function returns 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.

For a list of parser tokens, see Appendice P, or use token_name() to translate a token value into its string representation.

Esempio 1. token_get_all() examples

<?php
  $tokens = token_get_all('<?php'); // => array(array(T_OPEN_TAG, '<?'));
  $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

Description

string token_name ( int token)

token_name() returns the symbolic name for a PHP token value. The symbolic name returned matches the name of the matching token constant.

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

See also List of Parser Tokens.

CXIV. 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 [, bool format])

get_headers() returns an array with the headers sent by the server in response to a HTTP request.

If the optional format parameter is true, 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, true));
?>

The above example will output something like:

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 [, int 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 1 will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.

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.

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

Description

array parse_url ( string url)

This function returns an associative array containing any of the various components of the URL that are present. If one of them is missing, no entry will be created for it. The components are :

  • scheme - e.g. http

  • host

  • port

  • user

  • pass

  • path

  • query - after the question mark ?

  • fragment - after the hashmark #

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.

Nota: This function doesn't work with relative URLs.

Esempio 1. parse_url() example

$ php -r 'print_r(parse_url("http://username:password@hostname/path?arg=value#anchor"));'
Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

$ php -r 'print_r(parse_url("http://invalid_host..name/"));'
Array
(
    [scheme] => http
    [host] => invalid_host..name
    [path] => /
)

See also pathinfo(), parse_str(), dirname(), and basename().

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(urlencode($data)).

Esempio 2. urlencode() and htmlentities() example

<?php
echo '<a href="mycgi?foo=', htmlentities(urlencode($userinput)), '">';
?>

See also urldecode(), htmlentities(), rawurldecode() and rawurlencode().

CXV. Funzioni di 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

NomeDefaultModificabile
unserialize_callback_func""PHP_INI_ALL
Per maggiori dettagli sulle costanti PHP_INI_* vedere ini_set().

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

doubleval

doubleval -- Alias di floatval()

Descrizione

Questa funzione è un alias di floatval().

Nota: Questo alias è una rimanenza dalla ridenominazione di alcune funzioni. Nelle vecchie versioni di PHP, occorre utilizzare questo alias al posto della funzione floatval(), questo perchè la suddetta funzione non era disponibile.

empty

(PHP 3, PHP 4, PHP 5 )

empty -- Determina se una variabile è valorizzata

Descrizione

bool empty ( mixed var)

La funzione empty() restituisce FALSE se il parametro var non è vuoto e contiene un valore diverso da zero. In altre parole i valori "", 0, "0", NULL, FALSE, array(), var $var;, e gli oggetti con proprietà vuote sono tutti considerati vuoti. La funzione restituisce TRUE se var è vuoto.

Questo è l'opposto di (boolean) var, tranne che non viene dato alcun warning quando la variabile non è valorizzata. Vedere il capitolo Conversione a booleano per maggiori informazioni.

Esempio 1. Semplici confronti empty() / isset().

<?php
$var = 0;
// Valuata come true perchè $var è vuota
if (empty($var)) { // restituisce true 
    print '$var è uguale a 0 oppure non è definita';
}
// Valutata come vera perchè $var è impostata
if (!isset($var)) { // restituisce false
    print '$var non è definita';
}
?>

Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

Nota: Si noti che la funzione perde di significato se applicata a qualcosa che non sia una variabile; ad esempio empty (addslashes ($name)) non ha significato.

Vedere anche isset(), unset(), array_key_exists(), count(), strlen() e la tabella di comparazione dei tipi.

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.

La variabile Var può anche essere di tipo scalare. La funzione floatval() non può essere usata con variabili di tipo array oppure object.

<?php
$var = '122.34343The';
$valore_float_di_var = floatval($var);
echo $valore_float_di_var; // visualizza 122.34343
?>

Vedere anche intval(), strval(), settype() e Manipolazione dei Tipi .

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.

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

Vedere anche get_defined_functions() e get_defined_constants().

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 una stringa rappresentante il tipo di risorsa passato. Se il parametro passato non è una risorsa valida la funzione genera un errore.

<?php
$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_integer(), 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).

Var può essere una qualsiasi variabile scalare. Non è possibile utilizzare intval() con variabili di tipo array o object.

Nota: Il parametro base di intval() non ha effetto se var non è una stringa.

Vedere anche doubleval(), strval(), settype() e Manipolazione dei Tipi.

is_array

(PHP 3, PHP 4 , PHP 5)

is_array -- Verifica se una variabile è un array

Descrizione

bool is_array ( mixed var)

Restituisce TRUE se var è un array, FALSE in caso contrario.

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

Questo esempio visualizzerà:

Array
not an Array

Vedere anche is_float(), is_int(), is_integer(), is_string() e is_object().

is_bool

(PHP 4 , PHP 5)

is_bool --  Verifica se una variabile è di tipo boolean

Descrizione

bool is_bool ( mixed var)

Restituisce TRUE se var è di tipo boolean.

Esempio 1. Esempi di is_bool()

<?php
$a = false;
$b = 0;

// Poichè $a è booleana, questa è vera
if (is_bool($a)) {
    echo "Sì, è booleana";
}

// Poichè $b non è booleana, questa non è vera
if (is_bool($b)) {
    echo "Sì, è booleana";
}
?>

Vedere anche is_array(), is_float(), is_int(), is_integer(), is_string(), and is_object().

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

is_double -- Alias di is_float()

Descrizione

Questa funzione è un alias di 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)

Questa funzione restituisce TRUE se var è di tipo float, FALSE in caso contrario.

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

Vedere anche is_bool(), is_int(), is_integer(), is_numeric(), is_string(), is_array() e is_object(),

is_int

(PHP 3, PHP 4 , PHP 5)

is_int -- Verifica se una variabile è di tipo integer

Descrizione

bool is_int ( mixed var)

Restituisce TRUE se var è di tipo integer, FALSE in caso contrario.

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

Vedere anche is_bool(), is_float(), is_integer(), is_numeric(), is_string(), is_array() e is_object().

is_integer

is_integer -- Alias di is_int()

Descrizione

Questa funzione è un alias di is_int().

is_long

is_long -- Alias di is_int()

Descrizione

Questa funzione è un alias di 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)

Restituisce TRUE se var è di tipo null, FALSE in caso contrario.

Si veda il capitolo NULL per le considerazioni su quando una variabile è considerata essere NULL

Vedere anche: NULL, is_bool(), is_numeric(), is_float(), is_int(), is_string(), is_object() e is_array().

is_numeric

(PHP 4 , PHP 5)

is_numeric --  Verifica se una variabile è un numero o una stringa numerica

Descrizione

bool is_numeric ( mixed var)

Restituisce TRUE se var è un numero o una stringa numerica, FALSE in caso contrario.

Vedere anche is_bool(), is_float(), is_int(), is_string(), is_object(), is_array() e is_integer().

is_object

(PHP 3, PHP 4 , PHP 5)

is_object -- Verifica se una variabile è di tipo object

Descrizione

bool is_object ( mixed var)

Restituisce TRUE se var è un di tipo object, FALSE in caso contrario.

Vedere anche is_bool(), is_int(), is_integer(), is_float(), is_string(), and is_array().

is_real

is_real -- Alias di is_float()

Descrizione

Questa funzione è un alias di is_float().

is_resource

(PHP 4 , PHP 5)

is_resource --  Verifica se una variabile è una risorsa

Descrizione

bool is_resource ( mixed var)

is_resource() restituisce TRUE se la variabile individuata dal parametro var è di tipo resource, altrimenti restituisce FALSE.

Esempio 1. 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());
}
?>

Per maggiori dettagli fare riferimento alla documentazione di resource-type

is_scalar

(PHP 4 >= 4.0.5, PHP 5)

is_scalar --  Verifica se la variabile è di tipo scalare

Descrizione

bool is_scalar ( mixed var)

La funzione is_scalar() restituisce TRUE se la variabile indicata dal parametro var è di tipo scalare, in caso contrario restituisce FALSE.

Le variabili scalari sono quelle contenenti valori di tipo integer, float, string oppure boolean. I tipi array, object e resource non sono scalari.

<?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);
// visualizza: 3.1416

show_var($proteins)
// visualizza:
// array(3) {
//   [0]=>
//   string(10) "hemoglobin"
//   [1]=>
//   string(20) "cytochrome c oxidase"
//   [2]=>
//   string(10) "ferredoxin"
// }
?>

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.

Vedere anche is_bool(), is_numeric(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array() e is_integer().

is_string

(PHP 3, PHP 4 , PHP 5)

is_string -- Verifica se una variabile è una stringa

Descrizione

bool is_string ( mixed var)

Restituisce TRUE se var è di tipo string, FALSE in caso contrario.

Vedere anche is_bool(), is_int(), is_integer(), is_float(), is_real(), is_object() e is_array().

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: Nella versione 3 di PHP si serializzano le proprietà dell'oggetto, ma non i metodi. Nella versione 4 viene superata questa limitazione e possono essere recuperati sia le proprietà sia i metodi. Per maggiori informazioni vedere la sezione Serializzare oggetti in Oggetti e Classi.

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 integer, float, string, array oppure object. Nel caso in cui la stringa passata non sia deserializzabile la funzione restituisce FALSE.

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

L'esempio precedente 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();
?>

L'esempio precedente 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 soltanto le proprietà pubbliche di un oggetto possono essere restituite. Le funzioni var_export() e print_r() restituiranno anche le proprietà protette (protected) e private.

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.

Esempio 1. Esempio di var_dump()

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_dump($a);
?>

Output:

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

output:

float(3.1)
bool(true)

Vedere anche var_export() e 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])

Questa funzione restituisce informazioni strutturate sulla variabile che viene passata. Il comportamento è simile a var_dump() con due differenze. La prima, il valore restituito è codice PHP. La seconda è che la funzione restituisce i membri privati o protetti di un oggetto in PHP 5.

Si può anche ottenere la rappresentazione della variabile usando TRUE come secondo parametro della funzione.

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

output:

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php
$b = 3.1;
$v = var_export($b, true);
echo $v;
?>

output:

3.1

Vedere anche: var_dump() e print_r().

CXVI. 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. Restituisce true/false
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. Restituisce string
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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

vpopmail_auth_user -- Tenta di validare un nome utente/dominio/password. Restituisce true/false

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)

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)

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)

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)

vpopmail_error -- Riceve il messaggio testuale dell'ultimo errore di vpopmail. Restituisce string

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)

vpopmail_passwd -- Cambia la password virtuale ad un utente

Descrizione

bool vpopmail_passwd ( string user, string domain, string password)

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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)

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.

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

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.

CXVIII. 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 set the appropriate locale before doing so (see setlocale()).

Sommario
wddx_add_vars --  Add variables to a WDDX packet with the specified ID
wddx_deserialize -- Deserializes a WDDX packet
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_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 -- Deserializes a WDDX packet

Description

mixed wddx_deserialize ( string packet)

wddx_deserialize() takes a packet string and deserializes it. It returns the result which can be string, number, or array. Note that structures are deserialized into associative arrays.

wddx_packet_end

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

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

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

Questa estensione utilizza il modulo 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 dei dati
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.

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

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.

Durante il parsing di un documento XML, vengono richiamati i gestori degli eventi configurati, ed, al termine del processo, questa funzione restituisce TRUE oppure FALSE.

La funzione restituisce TRUE se il parsing riesce, altrimenti restituisce FALSE se non riesce oppure se il parametro parser si riferisce ad un parser non valido. 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().

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 utilizzata dal file XML di input. Le codifiche supportate sono "ISO-8859-1", che è anche il default, se non viene fornito il parametro codifica, "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 utilizzata dal file XML di input. Le codifiche supportate sono "ISO-8859-1", che è anche il default, se non viene fornito il parametro codifica, "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 l'opzione non può essere valorizzata. 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_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 dei dati

Descrizione

bool xml_set_end_namespace_decl_handler ( resource pind, 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.

<?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 pind, callback 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_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.

CXX. Funzioni XMLRPC

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

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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_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

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

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


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

(no version information, might be only in CVS)

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.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also xdiff_string_diff_binary().

xdiff_file_diff

(no version information, might be only in CVS)

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

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also xdiff_string_diff().

xdiff_file_merge3

(no version information, might be only in CVS)

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.

See also xdiff_string_merge3().

xdiff_file_patch_binary

(no version information, might be only in CVS)

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.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

See also xdiff_string_patch_binary().

xdiff_file_patch

(no version information, might be only in CVS)

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.

See also xdiff_string_patch().

xdiff_string_diff_binary

(no version information, might be only in CVS)

xdiff_string_diff_binary --  Make binary diff of two strings.

Description

mixed 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

(no version information, might be only in CVS)

xdiff_string_diff --  Make unified diff of two strings.

Description

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

Returns string with result or FALSE if an internal error happened.

See also xdiff_file_diff().

xdiff_string_merge3

(no version information, might be only in CVS)

xdiff_string_merge3 --  Merge 3 strings into one.

Description

string 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 or FALSE if an internal error happened.

See also xdiff_file_merge3().

xdiff_string_patch_binary

(no version information, might be only in CVS)

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

(no version information, might be only in CVS)

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.

Returns a patched string.

See also xdiff_file_patch().

CXXII. XSL 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.

The XSL extension implements the XSL standard, performing XSLT transformations using the libxslt library.


Installazione

PHP 5 includes the XSL extension by default and it can be enabled by adding the argument --with-xsl[=DIR] to your configure line. DIR is the libxslt installation directory. libxslt version 1.0.18 or greater is required.


Esempi

In this small tutorial we will learn how to transform an XML document into HTML.

Esempio 1. A simple XSL tree

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to my 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"/></h2>
  <h3> - <xsl:value-of select="year"/></h3>
 </xsl:template>
</xsl:stylesheet>

Esempio 2. Corresponding XML tree

<collection>
 <cd>
  <title>PHP Rock</title>
  <artist>Joe Coder</artist>
  <year>2003</year>
 </cd>
 <cd>
  <title>Squashing Typos on a Winter's Eve</title>
  <artist>kennyt</artist>
  <year>2004</year>
 </cd>
</collection>

Esempio 3. Making XML into HTML

The following PHP code uses the XML and XSL extensions to transform XML into presentable HTML.

<?php
/* Load the two XML sources */
$xml = new DomDocument; // from /ext/dom
$xml->load('example.xml');

$xsl = new DomDocument;
$xsl->load('example.xsl');

/* Configure the transformer */
$proc = new xsltprocessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
echo $proc->transformToXML($xml); // actual transformation
?>

This should produce an HTML fragment similar to the following:

Hey! Welcome to my sweet CD collection!

<h1>PHP Rock</h1>
<h2>by Joe Coder</h2>
<h3> - 2003</h3>

<h1>Squashing Typos on a Winter's Eve</h1>
<h2> by kennyt</h2>
<h3> - 2004</h3>

xsl_xsltprocessor_get_parameter

(no version information, might be only in CVS)

xsl_xsltprocessor_get_parameter -- 

Description

Procedural style

bool xsl_xsltprocessor_get_parameter ( string namespace, string name)

Object oriented style (method)

class xsltprocessor {

xsl_xsltdocucument getParameter ( string namespace, 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.

xsl_xsltprocessor_has_exslt_support

(no version information, might be only in CVS)

xsl_xsltprocessor_has_exslt_support -- Determine if PHP has EXSLT support

Description

Procedural style

bool xsl_xsltprocessor_has_exslt_support ( void )

Object oriented style (method)

class xsltprocessor {

bool hasExsltSupport ( 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.

xsl_xsltprocessor_has_exslt_support() returns TRUE if PHP was built with the EXSLT library , FALSE otherwise.

xsl_xsltprocessor_import_stylesheet

(no version information, might be only in CVS)

xsl_xsltprocessor_import_stylesheet -- 

Description

Procedural style

bool xsl_xsltprocessor_import_stylesheet ( node index)

Object oriented style (method)

class xsltprocessor {

bool importStylesheet ( node 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.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xsl_xsltprocessor_register_php_functions

(no version information, might be only in CVS)

xsl_xsltprocessor_register_php_functions -- Enables the ability to use PHP functions as XSLT functions

Description

Procedural style

void xsl_xsltprocessor_register_php_functions ( void )

Object oriented style (method)

class xsltprocessor {

void registerPHPFunctions ( 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.

xsl_xsltprocessor_register_php_functions() enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

xsl_xsltprocessor_remove_parameter

(no version information, might be only in CVS)

xsl_xsltprocessor_remove_parameter -- 

Description

Procedural style

bool xsl_xsltprocessor_remove_parameter ( string namespace, string name)

Object oriented style (method)

class xsltprocessor {

bool removeParameter ( string namespace, 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.

xsl_xsltprocessor_set_parameter

(no version information, might be only in CVS)

xsl_xsltprocessor_set_parameter -- 

Description

Procedural style

bool xsl_xsltprocessor_set_parameter ( string namespace, string name, string value)

Object oriented style (method)

class xsltprocessor {

bool setParameter ( string namespace, string name, string 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.

xsl_xsltprocessor_transform_to_doc

(no version information, might be only in CVS)

xsl_xsltprocessor_transform_to_doc -- 

Description

Procedural style

bool >xsl_xsltprocessor_transform_to_doc ( node doc [, bool clone])

Object oriented style (method)

class xsltprocessor {

bool transformToDoc ( node doc [, bool clone])

}

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xsl_xsltprocessor_transform_to_uri

(no version information, might be only in CVS)

xsl_xsltprocessor_transform_to_uri -- 

Description

Procedural style

bool xsl_xsltprocessor_transform_to_uri ( node doc, string uri [, bool clone])

Object oriented style (method)

class xsltprocessor {

bool transformToUri ( node doc, string uri [, bool clone])

}

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xsl_xsltprocessor_transform_to_xml

(no version information, might be only in CVS)

xsl_xsltprocessor_transform_to_xml -- 

Description

Procedural style

bool xsl_xsltprocessor_transform_to_xml ( node doc [, bool clone])

Object oriented style (method)

class xsltprocessor {

bool transformToXml ( node doc [, bool clone])

}

Avvertimento

Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio.

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CXXIII. Funzioni XSLT

Introduzione

XSLT e Sablotron

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.


Installazione

Questa estensione usa Sablotron e expat, i quali possono essere entrambi trovati su http://www.gingerall.com/. I binari sono forniti assieme al codice sorgente.

Su UNIX, fai partire configure con l'opzione --enable-xslt --with-xslt-sablot. La libreria Sablotron dovrebbe essere installata da qualche parte dove il compilatore può trovarla.


Questa estensione

L'estensione PHP fornisce un processore indipendente API alle trasformazioni XSLT. Attualmente questa estensione supporta solo la libreria Sablotron della Ginger Alliance. Il supporto è pianificato per le altre librerie, come la libreria Xalan o la libreria libxslt.

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.

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 -- Restituisce una stringa di errore
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)

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.

See also xslt_backend_name() and xslt_backend_version().

xslt_backend_name

(PHP 4 >= 4.3.0)

xslt_backend_name --  Returns the name of the backend

Description

string xslt_backend_name ( void )

xslt_backend_name() will always return Sablotron.

Esempio 1. xslt_backend_name() example

<?php

echo xslt_backend_name(); // Sablotron

?>

See also xslt_backend_info() and xslt_backend_version().

xslt_backend_version

(PHP 4 >= 4.3.0)

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.

Esempio 1. xslt_backend_version() example

<?php

echo xslt_backend_version(); // 0.98 for example

?>

See also xslt_backend_name() and xslt_backend_info().

xslt_create

(PHP 4 >= 4.0.3)

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.

xslt_errno

(PHP 4 >= 4.0.3)

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.

xslt_error

(PHP 4 >= 4.0.3)

xslt_error -- Restituisce una stringa di errore

Descrizione

mixed xslt_error ( resource xh)

Restituisce una stringa che descrive l'ultimo errore restituito dal processore XSLT indicato.

Esempio 1. Gli errori di Handling usano le funzioni xslt_error() e xslt_errno().

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

print($result);

xslt_free($xh);
?>

xslt_free

(PHP 4 >= 4.0.3)

xslt_free -- Libera un processore XSLT

Descrizione

void xslt_free ( resource xh)

Libera il processore XSLT identificato dall'handle dato.

xslt_getopt

(PHP 4 >= 4.3.0)

xslt_getopt --  Get options on a given xsl processor

Description

int xslt_getopt ( resource processor)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

xslt_process

(PHP 4 >= 4.0.3)

xslt_process -- Esegue una trasformazione XSLT

Descrizione

mixed xslt_process ( resource xh, string xml, string xsl [, string result [, 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. 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 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')) {
    print "SUCCESS, sample.xml was transformed by sample.xsl into result.xml";
    print ", result.xml has the following contents\n<br>\n";
    print "<pre>\n";
    readfile('result.xml');
    print "</pre>\n";
}
else {
    print "Sorry, sample.xml could not be transformed by sample.xsl into";
    print "  result.xml the reason is that " . xslt_error($xh) . " and the ";
    print "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) {
    print "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    print " variable, the \$result variable has the following contents\n<br>\n";
    print "<pre>\n";
    print $result;
    print "</pre>\n";
}
else {
    print "Sorry, sample.xml could not be transformed by sample.xsl into";
    print "  the \$result variable the reason is that " . xslt_error($xh) . 
    print " 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) {
    print "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    print " variable, the \$result variable has the following contents\n<br>\n";
    print "<pre>\n";
    print $result;
    print "</pre>\n";
}
else {
    print "Sorry, sample.xml could not be transformed by sample.xsl into";
    print "  the \$result variable the reason is that " . xslt_error($xh) . 
    print " and the error code is " . xslt_errno($xh);
}
xslt_free($xh);
?>

Finalmente, l'ultimo argomento della funzione xslt_process() è dei parametri che vuoi passare al documento XSLT. Questi parametri possono avere poi accesso tramite i tuoi files XSL usando l'istruzione <xsl:param name="parameter_name">.

xslt_set_base

(PHP 4 >= 4.0.5)

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.

xslt_set_encoding

(PHP 4 >= 4.0.5)

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)

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

xslt_set_log

(PHP 4 >= 4.0.6)

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:

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');
print($result);

xslt_free($xh);
?>

xslt_set_object

(PHP 4 >= 4.3.0)

xslt_set_object --  Sets the object in which to resolve callback functions

Description

int xslt_set_object ( resource parser, object obj)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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)

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)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

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)

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)

xslt_setopt --  Set options on a given xsl processor

Description

int xslt_setopt ( resource processor, int newmask)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

CXXIV. 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 rimosso da PHP 5 ed inserito tra le librerie PECL.


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 o YAZ. 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

NameDefaultChangeable
yaz.max_links"100"PHP_INI_ALL
yaz.log_file""PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


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
$num_hosts = count($host);
if (empty($term) || 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="term" />
    <input type="submit" name="action" value="Search" />
    </form>
    ';        
} else {
    echo 'You searched for ' . htmlspecialchars($term) . '<br />';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $term);
    }
    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 the maximum number 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, PHP 5)

yaz_addinfo -- Returns additional error information

Description

string yaz_addinfo ( resource id)

Returns additional error message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful or if no additional information was provided by the server.

See also yaz_error().

yaz_ccl_conf

(PHP 4 >= 4.0.5, PHP 5)

yaz_ccl_conf -- Configure CCL parser

Description

int 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. Each index of the array config is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN. The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.

Esempio 1. CCL configuration

In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is the connection ID.

<?php
$fields["ti"] = "1=4";
$fields["au"] = "1=1";
$fields["isbn"] = "1=7";
yaz_ccl_conf($id, $fields);
?>

yaz_ccl_parse

(PHP 4 >= 4.0.5, PHP 5)

yaz_ccl_parse -- Invoke CCL Parser

Description

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. If the supplied query was successfully converted to RPN, this function returns TRUE, and the index rpn of the supplied array result holds a valid RPN query. If the query could not be converted (because of invalid syntax, unknown field, etc.) this function returns FALSE and three indexes are set in the resulting array to indicate the cause of failure: errorcode CCL error code (integer), errorstring CCL error string, and errorpos approximate position in query of failure (integer is character position).

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, PHP 5)

yaz_close -- Close YAZ connection

Description

bool yaz_close ( resource id)

Closes the connection given by parameter id. The id is a connection resource as returned by a previous call to yaz_connect().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_connect

(PHP 4 >= 4.0.1, PHP 5)

yaz_connect --  Prepares for a connection to a Z39.50 server.

Description

resource 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. The zurl argument takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used. 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.

If the second argument, options, is given as a string it is treated as the Z39.50 V2 authentication string (OpenAuth).

If options is given as an array the contents of the array serves as options. Note that array options are only supported for PHP 4.1.0 and later.

yaz_connect() options

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.

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.

Nota: The YAZ proxy is a freely available Z39.50 proxy.

yaz_database

(PHP 4 >= 4.0.6, PHP 5)

yaz_database --  Specifies the databases within a session

Description

bool yaz_database ( resource id, string databases)

This function specifies one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect(). Multiple databases are separated by a plus sign +.

This function allows you to change databases within a session.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_element

(PHP 4 >= 4.0.1, PHP 5)

yaz_element --  Specifies Element-Set Name for retrieval

Description

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. Most servers support F (for full records) and B (for brief records).

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_errno

(PHP 4 >= 4.0.1, PHP 5)

yaz_errno -- Returns error number

Description

int yaz_errno ( resource id)

Returns an errornumber for the server (last request) identified by id. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.

yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search). To get a text description of the error, call yaz_error().

yaz_error

(PHP 4 >= 4.0.1, PHP 5)

yaz_error -- Returns error description

Description

string yaz_error ( resource id)

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_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

yaz_es_result

(PHP 4 >= 4.2.0, PHP 5)

yaz_es_result --  Inspects Extended Services Result

Description

array yaz_es_result ( resource id)

Avvertimento

Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti.

yaz_get_option

(PHP 5)

yaz_get_option -- Returns value of option for connection

Description

string yaz_get_option ( resource id, string name)

Returns the value of the option specified with name. If an option is not set, an empty string is returned.

See the description of yaz_set_option() for available options.

yaz_hits

(PHP 4 >= 4.0.1, PHP 5)

yaz_hits -- Returns number of hits for last search

Description

int yaz_hits ( resource id)

yaz_hits() returns the number of hits for the last search.

yaz_itemorder

(PHP 4 >= 4.0.5, PHP 5)

yaz_itemorder --  Prepares for Z39.50 Item Order with an ILL-Request package

Description

int 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. The args parameter must be a hash array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.

The ILL-Request parameters are:


protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
    

There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:


package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item
    

yaz_present

(PHP 4 >= 4.0.5, PHP 5)

yaz_present --  Prepares for retrieval (Z39.50 present).

Description

bool yaz_present ( resource id)

This function prepares for retrieval of records after a successful search. The yaz_range() should be called prior to this function to specify the range of records to be retrieved.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_range

(PHP 4 >= 4.0.1, PHP 5)

yaz_range --  Specifies the maximum number of records to retrieve

Description

bool yaz_range ( resource id, int start, int number)

This function should be called before either yaz_search() or yaz_present() to specify a range of records to be retrieved. The parameter start specifies the position of the first record to be retrieved and parameter number is the number of records. Records in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

yaz_record

(PHP 4 >= 4.0.1, PHP 5)

yaz_record -- Returns a record

Description

string yaz_record ( resource id, int pos, string type)

Returns the record at position pos or an empty string if no record exists at the given position.

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos. If no database record exists at the given position an empty string is returned.

Record positions in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

The type specifies the form of the returned record.

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

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

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

Esempio 1. Array for GRS-1 record

Consider 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
$ar = yaz_record($id, $p, "array");
print_r($ar);
produces
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).
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");

The record $rec can be processed with the Sablotron XSLT processor as follows:

$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);
print $res;

For PHP5 the XSL extension can be used instead of Sablotron XSLT.

yaz_scan_result

(PHP 4 >= 4.0.5, PHP 5)

yaz_scan_result -- Returns Scan Response result

Description

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(). This function 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. If the optional parameter result is given it will be modified to hold additional information taken from the Scan Response: number (number of entries returned), stepsize (Step-size), position (position of term), status (Scan Status).

yaz_scan

(PHP 4 >= 4.0.5, PHP 5)

yaz_scan -- Prepares for a scan

Description

int yaz_scan ( resource id, string type, string startterm [, array flags])

This function prepares for a Z39.50 Scan Request, where parameter id specifies connection. Starting term point for the scan is given by startterm. The form in which the starting term is specified is given by parameter type. Currently only type rpn is supported. The optional parameter flags specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size). To actually 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.

The syntax of startterm is similar to the RPN query as described in yaz_search(). The startterm consists of zero or more @attr-operator specifications, then followed by exactly one token.

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; ';
    while (list($key, $val) = each($options)) {
      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, PHP 5)

yaz_schema --  Specifies schema for retrieval.

Description

int yaz_schema ( resource id, string schema)

The schema must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ... This function should be called before yaz_search() or yaz_present().

yaz_search

(PHP 4 >= 4.0.1, PHP 5)

yaz_search -- Prepares for a search

Description

int yaz_search ( resource id, string type, string query)

yaz_search() prepares for a search on the connection given by parameter id. The parameter type represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation. Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

The RPN query

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 operater 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 queryspecifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr [set] type=value queryapplies 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.

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.

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

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

yaz_set_option

(PHP 5)

yaz_set_option -- Sets one or more options for connection

Description

string yaz_set_option ( resource id, string name, string value)

Sets option name to value.

Tabella 1. PYP/YAZ Connection Options

NameDescription
implementationNameimplementation name of server
implementationVersionimplementation version of server
implementationIdimplementation ID of server
schemaschema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntaxrecord syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
startoffset 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().

yaz_sort

(PHP 4 >= 4.1.0, PHP 5)

yaz_sort -- Sets sorting criteria

Description

int 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(). The parameter criteria 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

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, PHP 5)

yaz_syntax --  Specifies the preferred record syntax for retrieval.

Description

int yaz_syntax ( resource id, string 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.). This function should be called before yaz_search() or yaz_present().

yaz_wait

(PHP 4 >= 4.0.1, PHP 5)

yaz_wait -- Wait for Z39.50 requests to complete

Description

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

If the options array is given that holds options that change the behaviour of yaz_wait().

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.

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

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)

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)

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)

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)

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)

yp_get_default_domain -- Fetches the machine's default NIS domain

Description

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

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)

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)

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)

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

CXXVI. Funzioni per File Zip (Accesso di Sola Lettura)

Questo modulo usa le funzioni ZZIPlib della libreria di Guido Draheim per leggere archivi ZIP compressi e i file in essi contenuti.

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.

Il supporto Zip all'interno di PHP non è abilitato di default. Sarà necessario usare l'opzione di configurazione --with-zip durante la compilazione di PHP per abilitare tale supporto. Questo modulo richiede ZZIPlib versione >= 0.10.6.

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.


Esempio di Utilizzo

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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

Vedere anche zip_open(), zip_close(), zip_entry_open() e zip_entry_read().

CXXVII. 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 of 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 deflated 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

Description

int gzeof ( resource zp)

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

gzfile

(PHP 3, PHP 4 , PHP 5)

gzfile -- Read entire gz-file into an array

Description

array gzfile ( string filename [, int use_include_path])

Identical to readgzfile(), except that gzfile() returns the file in an array.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also readgzfile(), and gzopen().

gzgetc

(PHP 3, PHP 4 , PHP 5)

gzgetc -- Get character from gz-file pointer

Description

string gzgetc ( resource zp)

Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (unlike gzeof()).

The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), and gzgets().

gzgets

(PHP 3, PHP 4 , PHP 5)

gzgets -- Get line from file pointer

Description

string gzgets ( resource zp, int length)

Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), gzgetc(), and fgets().

gzgetss

(PHP 3, PHP 4 , PHP 5)

gzgetss --  Get line from gz-file pointer and strip HTML tags

Description

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.

You can use the optional third parameter to specify tags which should not be stripped.

Nota: Allowable_tags was added in PHP 3.0.13, PHP 4.0b3.

See also gzgets(), gzopen(), and strip_tags().

gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate -- Inflate a deflated string

Description

string gzinflate ( string data [, int length])

This function takes data compressed by gzdeflate() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

See also gzcompress(). gzuncompress(), gzdeflate(), and gzencode().

gzopen

(PHP 3, PHP 4 , PHP 5)

gzopen -- Open gz-file

Description

resource gzopen ( string filename, string mode [, int use_include_path])

Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

gzopen() returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns FALSE.

You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.

Esempio 1. gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

See also gzclose().

gzpassthru

(PHP 3, PHP 4 , PHP 5)

gzpassthru --  Output all remaining data on a gz-file pointer

Description

int gzpassthru ( resource zp)

Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

gzputs

gzputs -- Alias of gzwrite()

Description

This function is an alias of gzwrite().

gzread

(PHP 3, PHP 4 , PHP 5)

gzread -- Binary-safe gz-file read

Description

string gzread ( resource zp, int length)

gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

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

See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().

gzrewind

(PHP 3, PHP 4 , PHP 5)

gzrewind -- Rewind the position of a gz-file pointer

Description

int gzrewind ( resource zp)

Sets the file position indicator for zp to the beginning of the file stream.

If an error occurs, returns 0.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzseek() and gztell().

gzseek

(PHP 3, PHP 4 , PHP 5)

gzseek -- Seek on a gz-file pointer

Description

int gzseek ( resource zp, int offset)

Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

See also gztell() and gzrewind().

gztell

(PHP 3, PHP 4 , PHP 5)

gztell -- Tell gz-file pointer read/write position

Description

int gztell ( resource zp)

Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

The file pointer must be valid, and must point to a file successfully opened by gzopen().

See also gzopen(), gzseek() and gzrewind().

gzuncompress

(PHP 4 >= 4.0.1, PHP 5)

gzuncompress -- Uncompress a deflated string

Description

string gzuncompress ( string data [, int length])

This function takes data compressed by gzcompress() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

See also gzdeflate(), gzinflate(), gzcompress(), gzencode().

gzwrite

(PHP 3, PHP 4 , PHP 5)

gzwrite -- Binary-safe gz-file write

Description

int gzwrite ( resource zp, string string [, int length])

gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

gzwrite() returns the number of (uncompressed) bytes written to the gz-file stream pointed to by zp.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

See also gzread(), gzopen(), and gzputs().

readgzfile

(PHP 3, PHP 4 , PHP 5)

readgzfile -- Output a gz-file

Description

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.

Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.

The file filename will be opened from the filesystem and its contents written to standard output.

You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.

See also gzpassthru(), gzfile(), and gzopen().

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5)

zlib_get_coding_type -- Returns the coding type used for output compression

Description

string zlib_get_coding_type ( void )

Returns the coding type used for output compression. Possible return values are gzip, deflate, or FALSE

See also the zlib.output_compression directive.

VI. Zend API

Hacking the Core of PHP

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.

Hacking the Core of PHP

Capitolo 26. 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 26-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 26-1. The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.


Capitolo 27. Extension Possibilities

As shown in Figura 26-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.


Capitolo 28. 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
php4 Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory.
php4/ext Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
php4/main This directory contains the main php macros and definitions. (important)
php4/pear Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php4/sapi Contains the code for the different server abstraction layers.
php4/TSRM Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
php4/Zend Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php4/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php4/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php4/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.

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.


Capitolo 29. 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/manual/m4/html_mono/m4.html)

All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.

Step by step, the process looks like this:
:~/cvs/php4/ext:> ./ext_skel --extname=my_module
Creating directory my_module
Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/my_module/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-my_module
5.  $ make
6.  $ ./php -f ext/my_module/my_module.php
7.  $ vi ext/my_module/my_module.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
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 29-1 is a bit more complex:

Esempio 29-1. The default config.m4.

dnl $Id: Extending_Zend_Build.xml,v 1.8 2002/10/10 18:13:11 imajes 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.


Capitolo 30. 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 30-1 shows the source.

Esempio 30-1. 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 30-1 can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually. To compile your modules manually, you need the following commands:

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


Capitolo 31. 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 31-1. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

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

Figura 31-1. 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.


Capitolo 32. 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.


Capitolo 33. 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 33-1 for descriptions).

Tabella 33-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 33-1.

Esempio 33-1. 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 33-2 shows a list of all the macros that you can use to define functions.

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

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


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

Figura 34-1. 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 > 5)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
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 34-1. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Esempio 34-1. 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_P(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 34-1).

Note: All conversion functions expect a **zval as parameter.

Tabella 34-1. 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 34-2 shows the output.

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

Esempio 34-2. 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 34-2, Tabella 34-3 and Tabella 34-4.

Tabella 34-2. Zend zval Structure

EntryDescription
value Union containing this variable's contents. See Tabella 34-3 for a description.
type Contains this variable's type. For a list of available types, see Tabella 34-4.
is_ref 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.

Tabella 34-3. 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 34-4. 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 34-3.

Esempio 34-3. 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.


Capitolo 35. 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 35-1 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 35-1. 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 35-2).

Esempio 35-2. 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 35-1, Tabella 35-2 and Tabella 35-3 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Tabella 35-1. 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 35-2. 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 35-3. 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 35-3) and zend_hash_index_update() for indexed arrays (see Esempio 35-4):

Esempio 35-3. 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 35-4. 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 35-4 to add members to your object.

Tabella 35-4. 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 an unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_numberThe module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.

The return value is an 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_resource_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);

rsrc_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 an 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 35-5 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Tabella 35-5. 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 35-6. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

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

Capitolo 36. 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 lvalue (result of the evaluation of the left side of the operator) to the rvalue (same for the right side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:

zval *parameter;
   
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &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.


Capitolo 37. 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 37-1 and Tabella 37-2.

Nota: The macros in Tabella 37-1 automatically return from your function, those in Tabella 37-2 only set the return value; they don't return from your function.

Tabella 37-1. 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 37-2. 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.


Capitolo 38. 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 38-1 shows a list of possible values (see Figura 38-1). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.

Tabella 38-1. 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 38-1. 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 38-1 shows a source example and its output. To print the table footer, use php_info_print_table_end().

Esempio 38-1. 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 38-2.

Esempio 38-2. 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));


Capitolo 39. 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.


Capitolo 40. 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 40-1 shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

Esempio 40-1. 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>");
?>


Capitolo 41. 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 41-1.

Tabella 41-1. 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();

}


Capitolo 42. 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.


Capitolo 43. 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 43-1.

Tabella 43-1. 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>.

Capitolo 44. API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see Tabella 44-1).

Tabella 44-1. 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

VII. PHP API: Interfacce per gli autori di estensioni


Capitolo 45. 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 45-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 45-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 45-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 45-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 45-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 45-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 45-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 45-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 XXX

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

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

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

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

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

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

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

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

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 46. 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 qui 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.

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

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.


Capitolo 48. 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 49. 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 doing --with-mysql=/usr when building PHP. Windows users may enable the extension php_mysql.dll inside php.ini. Also, copy libmySQL.dll into the appropriate %SYSTEMROOT% directory, just like you do with every other bundled DLL from the dll directory.

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 50. 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 51. 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. While configuring PHP (./configure), you come across an error similar to the following:
4. When I try to start Apache, I get the the following message:
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. Voglio aggiornare il mio PHP. Dove posso trovare la linea di ./configure che è stata usata per creare la mia attuale versione di PHP?
16. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.

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=/percorso/per/apache e non --with-apache=/percorso/per/apache/src.

3. While configuring PHP (./configure), you come across an error similar to the following:

checking lex output file root... ./configure: lex: command not found
       configure: error: cannot find output from lex; giving up

Be sure to read the installation instructions carefully and note that you need both flex and bison installed to compile PHP. Depending on your setup you will install bison and flex from either source or a package, such as a RPM.

4. When I try to start Apache, I get the the following message:

fatal: relocation error: file /path/to/libphp4.so:
       symbol ap_block_alarms: referenced symbol not found

This error usually comes up when one compiles the Apache core program as a DSO library for shared usage. Try to reconfigure apache, making sure to use at least the following flags:

--enable-shared=max --enable-rule=SHARED_CORE

For more information, read the top-level Apache INSTALL file or the Apache DSO manual page.

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

16. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.

Make sure your GD library and PHP are linked against the same depending libraries (e.g. libpng).


Capitolo 52. 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. 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.
10. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
11. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
12. Where can I find a complete list of variables are available to me in PHP?
13. 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.
14. 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?

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/support/kb/articles/q160/4/22.asp and the manual section on HTTP Authentication .

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

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

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

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

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

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


Capitolo 53. 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 53-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 53-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 53-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'].

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

Attualmente non è possibile bloccare gli errori COM nei soliti modi disponibili in PHP (@, track_errors, ...), ma stiamo pensando di implementare questa funzione.

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:

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

Non ancora.

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 55. 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 56. 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 57. Migrazione da PHP 3 a PHP 4

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. 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. Funzioni incompatibili?

Poiché PHP 4 è semplicemente una riscrittura dell'intero engine PHP, solo alcune funzioni sono state alterare e solo alcune molto esotiche.


Capitolo 58. 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.

PHP 4 is currently the latest released version of PHP. Work has already begun on modifying and improving the Zend Engine to integrate the features which were designed for PHP 5.0.

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

The future of PHP is mainly driven by its core, the Zend Engine. PHP 5 will include the new Zend Engine 2.0. 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:

  • strrpos() and strripos() now use the entire string as a needle.

  • Illegal use of string offsets causes E_ERROR instead of E_WARNING.

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

  • The T_ML_CONSTANT 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_CONSTANT 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() starting PHP 5 returns the name of the class as it was declared which may lead to problems in older scripts that rely on the previous behaviour (the class name was lowercased). A possible solution is to search for get_class() in all your scripts and use strtolower().

  • ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.

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.


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:

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

# 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

InterBase:

iconv:

Streams:

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.


Private and Protected Members

PHP 5 introduces private and protected member variables, they allow you to define the visibility of class properties.

Esempio B-4. Private and Protected Members accesibility

Protected member variables can be accessed in classes extending the class they are declared in, whereas private member variables can only be accessed by the class they belong to.

<?php
class MyClass {
    private $Hello = "Hello, World!\n";
    protected $Bar = "Hello, Foo!\n";
    protected $Foo = "Hello, Bar!\n";

    function printHello() {
        print "MyClass::printHello() " . $this->Hello;
        print "MyClass::printHello() " . $this->Bar;
        print "MyClass::printHello() " . $this->Foo;
    }
}

class MyClass2 extends MyClass {
    protected $Foo;
              
    function printHello() {
        MyClass::printHello();                          /* Should print */
        print "MyClass2::printHello() " . $this->Hello; /* Shouldn't print out anything */
        print "MyClass2::printHello() " . $this->Bar;   /* Shouldn't print (not declared)*/
        print "MyClass2::printHello() " . $this->Foo;   /* Should print */
    }
}

$obj = new MyClass();
print $obj->Hello;  /* Shouldn't print out anything */
print $obj->Bar;    /* Shouldn't print out anything */
print $obj->Foo;    /* Shouldn't print out anything */
$obj->printHello(); /* Should print */

$obj = new MyClass2();
print $obj->Hello;  /* Shouldn't print out anything */
print $obj->Bar;    /* Shouldn't print out anything */
print $obj->Foo;    /* Shouldn't print out anything */
$obj->printHello();
?>

Private and Protected Methods

With PHP 5, private and protected methods are also introduced.

Esempio B-5. Protected methods example

<?php
class Foo {
    private function aPrivateMethod() {
        echo "Foo::aPrivateMethod() called.\n";
    }

    protected function aProtectedMethod() {
        echo "Foo::aProtectedMethod() called.\n";
        $this->aPrivateMethod();
    }
}

class Bar extends Foo {
    public function aPublicMethod() {
        echo "Bar::aPublicMethod() called.\n";
        $this->aProtectedMethod();
    }
}

$o = new Bar;
$o->aPublicMethod();
?>

Old code that has no user-defined classes or functions named "public", "protected" or "private" should run without modifications.


Abstract Classes and Methods

PHP 5 also introduces abstract classes and methods. An abstract method only declares the method's signature and does not provide an implementation. A class that contains abstract methods needs to be declared abstract.

Esempio B-6. Abstract class example

<?php
abstract class AbstractClass {
    abstract public function test();
}

class ImplementedClass extends AbstractClass {
    public function test() {
        echo "ImplementedClass::test() called.\n";
    }
}

$o = new ImplementedClass;
$o->test();
?>

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


Interfaces

PHP 5 introduces interfaces. A class may implement an arbitrary list of interfaces.

Esempio B-7. Interface example

<?php
interface Throwable {
    public function getMessage();
}

class MyException implements Throwable {
    public function getMessage() {
        // ...
    }
}
?>

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


Class Type Hints

While remaining loosely typed PHP 5 introduces the ability to use class type hints to declare the expected class of objects that are passed as parameters to a method.

Esempio B-8. Class type hinting example

<?php
interface Foo {
    function a(Foo $foo);
}

interface Bar {
    function b(Bar $bar);
}

class FooBar implements Foo, Bar {
    function a(Foo $foo) {
        // ...
    }

    function b(Bar $bar) {
        // ...
    }
}

$a = new FooBar;
$b = new FooBar;

$a->a($b);
$a->b($b);
?>

These class type hints are not checked upon compilation, as would be the case in a typed language, but during runtime. This means that:

<?php
function foo(ClassName $object) {
    // ...
}
?>

is equivalent to:

<?php
function foo($object) {
    if (!($object instanceof ClassName)) {
        die("Argument 1 must be an instance of ClassName");
    }
}
?>


final

PHP 5 introduces the "final" keyword to declare final members and methods. Methods and members declared final cannot be overridden by sub-classes.

Esempio B-9. final method

<?php
class Foo {
    final function bar() {
        // ...
    }
}
?>

It is furthermore possible to make a class final. Doing this prevents a class from being specialized (it cannot be inherited by another class). There's no need to declare the methods of a final class themselves as final.

Esempio B-10. final class

<?php
final class Foo {
    // class definition
}

// the next line is impossible
// class Bork extends Foo {}
?>

Properties can not be final.

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


Objects Cloning

PHP 4 offered no way a user could decide what copy constructor to run when an object is duplicated. During duplication, PHP 4 did a bit for bit copy making an identical replica of all the object's properties.

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

When the developer asks to create a new copy of an object, PHP 5 will check if a __clone() method has been defined or not. If not, it will call a default __clone() which will copy all of the object's properties. If a __clone() method is defined, then it will be responsible to set the necessary properties in the created object. For convenience, the engine will supply a function that imports all of the properties from the source object, so that they can start with a by-value replica of the source object, and only override properties that need to be changed.

Esempio B-11. Objects cloning

<?php
class MyCloneable {
    static $id = 0;

    function MyCloneable() {
        $this->id = self::$id++;
    }

    function __clone() {
        $this->address = "New York";
        $this->id = self::$id++;
    }
}

$obj = new MyCloneable();

$obj->name = "Hello";
$obj->address = "Tel-Aviv";

print $obj->id . "\n";

$obj_cloned = clone $obj;

print $obj_cloned->id . "\n";
print $obj_cloned->name . "\n";
print $obj_cloned->address . "\n";
?>

Constructors

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.

With PHP 4, constructor methods were class methods that had the same name as the class itself. Since it is very common to call parent constructors from derived classes, the way PHP 4 worked made it a bit cumbersome to move classes around in a large class hierarchy. If a class is moved to reside under a different parent, the constructor name of that parent changes as well, and the code in the derived class that calls the parent constructor has to be modified.

PHP 5 introduces a standard way of declaring constructor methods by calling them by the name __construct().

Esempio B-12. 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.


Destructors

Having the ability to define destructors for objects can be very useful. Destructors can log messages for debugging, close database connections and do other clean-up work. No mechanism for object destructors existed in PHP 4, although PHP had already support for registering functions which should be run on request shutdown.

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as Java: When the last reference to an object is destroyed the object's destructor, which is a class method named __destruct() that receives no parameters, is called before the object is freed from memory.

Esempio B-13. Destructor

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


Constants

PHP 5 introduces per-class constants:

Esempio B-14. Class constant example

<?php
class Foo {
    const constant = "constant";
}

echo "Foo::constant = " . Foo::constant . "\n";
?>

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


Exceptions

PHP 4 had no exception handling. PHP 5 introduces a exception model similar to that of other programming languages. Note that there is support for "catch all" but not for the "finally" clause.

Exceptions can be rethrown in catch blocks. Also it is possible to have multiple catch blocks. In that case the caught exception is compared with the classtype of each catch block from top to bottom and the first block that has an 'instanceof' match gets executed. When the catch block finishes, execution continues at the end of the last catch block. If no catch block has an 'instanceof' match then the next try/catch block is searched until no more try/catch blocks are available. In that case the exception is an uncaught exception and the program terminates with showing the exception.

Esempio B-15. Exception creation example

<?php
try {
   throw new Exception('Hello');
}
catch (Exception $exception) {
   echo $exception;
}
?>

Old code that has no user-defined classes or functions 'catch', 'throw' and 'try' will run without modifications.


Dereferencing objects returned from functions

In PHP 4 it wasn't possible to dereference objects returned by functions and make further method calls on those objects. With PHP 5, the following is now possible:

Esempio B-16. Dereferencing example

<?php
class Circle {
    function draw() {
        print "Circle\n";
    }
}
      
class Square {
    function draw() {
        print "Square\n";
    }
}

function ShapeFactoryMethod($shape) {
    switch ($shape) {
        case "Circle":
            return new Circle();
        case "Square":
            return new Square();
    }
}

ShapeFactoryMethod("Circle")->draw();
ShapeFactoryMethod("Square")->draw();
?>

Static member variables initialization

Static member variables of static classes can now be initialized.

Esempio B-17. Static variable initialization example

<?php
class foo {
    static $my_static = 5;
    public $my_prop = 'bla';
}

print foo::$my_static;
$obj = new foo;
print $obj->my_prop;
?>

Static Methods

PHP 5 introduces the 'static' keyword to declare a method static, thus callable from outside the object context.

Esempio B-18. Static Methods example

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

Foo::aStaticMethod();
?>

The pseudo variable $this is not available inside a method that has been declared static.


instanceof

PHP 5 introduces the instanceof keyword, that allows you to ascertain whether or not an object is an instance of a class, or extends a class, or implements an interface.

Esempio B-19. instanceof example

<?php
class baseClass { }

$a = new baseClass;

if ($a instanceof baseClass) {
    echo "Hello World";
}
?>

Static function variables

Statics are now treated at compile-time which allows developers to assign variables to statics by reference. This change also greatly improves their performance but means that indirect references to statics will not work anymore.


Parameters passed by reference

Parameters that are passed by reference to a function may now have default values

Esempio B-20.

<?php
function my_function(&$var = null) {
    if ($var === null) {
        die("$var needs to have a value");
    }
}
?>

__autoload()

The __autoload() interceptor function will be automatically called when an undeclared class is to be instantiated. The name of that class will be passed to the __autoload() interceptor function as its only argument.

Esempio B-21. __autoload() example

<?php
function __autoload($className) {
    include_once $className . ".php";
}

$object = new ClassName;
?>

Overloadable Method calls and Property accesses

Both method calls and property accesses can be overloaded via the __call(), __get() and __set() methods.

Esempio B-22. __get() and __set()

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

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

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

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

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


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

Esempio B-23. __get() example

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

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

Iteration

Objects may be iterated in an overloaded way when used with foreach. The default behavior is to iterate over all properties.

Esempio B-24. Object iteration example

<?php
class Foo {
    public $x = 1;
    public $y = 2;
}

$obj = new Foo;

foreach ($obj as $prp_name => $prop_value) {
    // using the property
}
?>

Each class whose instances can be iterated with foreach should implement the empty interface Traversable. Hence any object that says it implements Traversable can be used with foreach.

The interfaces IteratorAggregate and Iterator allows you to specify how class objects are iterated in PHP code. The first of them simply has a method getIterator() which must return an array or an object that either implements the interface Iterator or is instantiated from an internal class that can be iterated

Esempio B-25. Iterator creation example

<?php
class ObjectIterator implements Iterator {

    private $obj;
    private $num;

    function __construct($obj) {
        $this->obj = $obj;
    }
    function rewind() {
        $this->num = 0;
    }
    function valid() {
        return $this->num < $this->obj->max;
    }
    function key() {
        return $this->num;
    }
    function current() {
        switch($this->num) {
            case 0: return "1st";
            case 1: return "2nd";
            case 2: return "3rd";
            default: return $this->num."th";
        }
    }
    function next() {
        $this->num++;
    }
}

class Object implements IteratorAggregate {

    public $max = 3;

    function getIterator() {
        return new ObjectIterator($this);
    }
}

$obj = new Object;

// this foreach ...
foreach($obj as $key => $val) {
    echo "$key = $val\n";
}

// matches the following 7 lines with the for directive.
$it = $obj->getIterator();
for($it->rewind(); $it->valid(); $it->next()) {
    $key = $it->current();
       $val = $it->key();
          echo "$key = $val\n";
}
unset($it);
?>

__METHOD__ constant

The new __METHOD__ pseudo constant shows the current class and method when used inside a method and the function when used outside of a class.

Esempio B-26. __METHOD__ use example

<?php
class Foo {
    function show() {
        echo __METHOD__;
    }
}

class Bar extends Foo {
}

Foo::show(); // outputs Foo::show
Bar::show(); // outputs Foo::show either since __METHOD__ is
             // compile-time evaluated token

function test() {
    echo __METHOD__;
}

test();      // outputs test
?>

__toString() method

The new __toString() magic method allows you to overload the object to string conversion.

Esempio B-27. __toString() example

<?php
class Foo {
    function __toString() {
        return "What ever";
    }
}

$obj = new Foo;

echo $obj; // call __toString()
?>

Reflection API

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions.

The reflection API also offers ways of getting doc comments for functions, classes and methods.

Nearly all aspects of object oriented code can be reflected by using the reflection API which is documented separately.

Esempio B-28. Reflection API use example

<?php
class Foo {
    public $prop;
    function Func($name) {
        echo "Hello $name";
    }
}

reflectionClass::export('Foo');
reflectionObject::export(new Foo);
reflectionMethod::export('Foo', 'func');
reflectionProperty::export('Foo', 'prop');
reflectionExtension::export('standard');
?>

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: safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe mode's purpose). In contrast, Admin values can modify the value of any PHP directive.

To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.

To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:

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


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. 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. Also, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL.


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 F-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 F-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 F-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 F-3. Checking whether $foo exists in a symbol table

if (hash_exists(active_symbol_table,"foo",sizeof("foo"))) { exists... }
else { doesn't exist }

Esempio F-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 F-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 F-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 F-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 F-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 F-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.


Appendice G. 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 H. List of core php.ini directives

This list includes the core php.ini directives you can set to configure your PHP setup. Directives handled by extensions are listed and detailed at the extension documentation pages respectively; Information on the session directives for example can be found at the sessions page.


Httpd Options

Tabella H-1. Httpd Options

NameDefaultChangeable
async_send"0"PHP_INI_ALL


Language Options

Tabella H-2. Language and Misc Configuration Options

NameDefaultChangeable
short_open_tagOnPHP_INI_SYSTEM|PHP_INI_PERDIR
asp_tagsOffPHP_INI_SYSTEM|PHP_INI_PERDIR
precision"14"PHP_INI_ALL
y2k_complianceOffPHP_INI_ALL
allow_call_time_pass_referenceOnPHP_INI_SYSTEM|PHP_INI_PERDIR
expose_phpOnPHP_INI_SYSTEM

Breve descrizione dei parametri di configurazione.

short_open_tag boolean

Tells whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"'; ?>. Also if disabled, you must use the long form of the PHP open tag (<?php ?>).

Nota: This directive also affects the shorthand <?=, which is identical to <? echo. Use of this shortcut requires short_open_tag to be on.

asp_tags boolean

Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.

Nota: Support for ASP-style tags was added in 3.0.4.

precision integer

The number of significant digits displayed in floating point numbers.

y2k_compliance boolean

Enforce year 2000 compliance (will cause problems with non-compliant browsers)

allow_call_time_pass_reference boolean

Whether to enable the ability to force arguments to be passed by reference at function call time. This method is deprecated and is likely to be unsupported in future versions of PHP/Zend. The encouraged method of specifying which arguments should be passed by reference is in the function declaration. You're encouraged to try and turn this option Off and make sure your scripts work properly with it in order to ensure they will work with future versions of the language (you will receive a warning each time you use this feature, and the argument will be passed by value instead of by reference).

See also References Explained.

expose_php boolean

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.


Resource Limits

Tabella H-3. Resource Limits

NameDefaultChangeable
memory_limit"8M"PHP_INI_ALL

Breve descrizione dei parametri di configurazione.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. In order to use this directive you must have enabled it at compile time. So, your configure line would have included: --enable-memory-limit. Note that you have to set it to -1 if you don't want any limit for your memory.

As of PHP 4.3.2, and when memory_limit is enabled, the PHP function memory_get_usage() is made available.

See also: max_execution_time.


Data Handling

Tabella H-4. Data Handling Configuration Options

NameDefaultChangeable
track_vars"On"PHP_INI_??
arg_separator.output"&"PHP_INI_ALL
arg_separator.input"&"PHP_INI_SYSTEM|PHP_INI_PERDIR
variables_order"EGPCS"PHP_INI_ALL
register_globals"Off"PHP_INI_PERDIR|PHP_INI_SYSTEM
register_argc_argv"On"PHP_INI_PERDIR|PHP_INI_SYSTEM
register_long_arrays"On"PHP_INI_PERDIR|PHP_INI_SYSTEM
post_max_size"8M"PHP_INI_SYSTEM|PHP_INI_PERDIR
gpc_order"GPC"PHP_INI_ALL
auto_prepend_file""PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_append_file""PHP_INI_SYSTEM|PHP_INI_PERDIR
default_mimetype"text/html"PHP_INI_ALL
default_charset"iso-8859-1"PHP_INI_ALL
always_populate_raw_post_data"0"PHP_INI_SYSTEM|PHP_INI_PERDIR
allow_webdav_methods"0"PHP_INI_SYSTEM|PHP_INI_PERDIR

Breve descrizione dei parametri di configurazione.

track_vars boolean

If enabled, then Environment, GET, POST, Cookie, and Server variables can be found in the global associative arrays $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER.

Note that as of PHP 4.0.3, track_vars is always turned on.

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

Nota: Every character in this directive is considered as separator!

variables_order string

Set the order of the EGPCS (Environment, GET, POST, Cookie, Server) variable parsing. The default setting of this directive is "EGPCS". Setting this to "GP", for example, will cause PHP to completely ignore environment variables, cookies and server variables, and to overwrite any GET method variables with POST-method variables of the same name.

See also register_globals.

register_globals boolean

Tells whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. For example; if register_globals = on, the URL http://www.example.com/test.php?id=3 will produce $id. Or, $DOCUMENT_ROOT from $_SERVER['DOCUMENT_ROOT']. You may want to turn this off if you don't want to clutter your scripts' global scope with user data. As of PHP 4.2.0, this directive defaults to off. It's preferred to go through PHP Predefined Variables instead, such as the superglobals: $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER. Please read the security chapter on Using register_globals for related information.

Please note that register_globals cannot be set at runtime (ini_set()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals on.

Nota: register_globals is affected by the variables_order directive.

register_argc_argv boolean

Tells PHP whether to declare the argv & argc variables (that would contain the GET information).

See also command line. Also, this directive became available in PHP 4.0.0 and was always "on" before that.

register_long_arrays boolean

Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you're not using them, it's recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET.

This directive became available in PHP 5.0.0.

post_max_size integer

Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize.

If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.

gpc_order string

Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is "GPC". Setting this to "GP", for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.

Nota: This option is not available in PHP 4. Use variables_order instead.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the include() function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the include() function, so include_path is used.

The special value none disables auto-appending.

Nota: If the script is terminated with exit(), auto-append will not occur.

default_mimetype string

default_charset string

As of 4.0b4, PHP always outputs a character encoding by default in the Content-type: header. To disable sending of the charset, simply set it to be empty.

always_populate_raw_post_data boolean

Always populate the $HTTP_RAW_POST_DATA variable.

allow_webdav_methods boolean

Allow handling of WebDAV http requests within PHP scripts (eg. PROPFIND, PROPPATCH, MOVE, COPY, etc..) If you want to get the post data of those requests, you have to set always_populate_raw_post_data as well.

See also: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase.


Paths and Directories

Tabella H-5. Paths and Directories Configuration Options

NameDefaultChangeable
include_pathPHP_INCLUDE_PATHPHP_INI_ALL
doc_rootPHP_INCLUDE_PATHPHP_INI_SYSTEM
user_dirNULLPHP_INI_SYSTEM
extension_dirPHP_EXTENSION_DIRPHP_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

Specifies a list of directories where the require(), include() and fopen_with_path() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

Esempio H-1. Unix include_path

include_path=".:/php/includes"

Esempio H-2. Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html .

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

cgi.fix_pathinfo boolean

Provides real PATH_INFO/PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting this to 1 will cause PHP CGI to fix it's paths to conform to the spec. A setting of zero causes PHP to behave as before. Default is zero. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

Nota: Windows Users: You can safely turn this off for IIS, in fact, you must. To get OmniHTTPD or Xitami to work you must turn it off.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Nota: Setting this variable may cause security issues, know what you are doing first.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set 0, PHP sends a Status: header that is supported by Apache and other web servers. When this option is set to 1, PHP will send RFC 2616 compliant headers. Leave it set to 0 unless you know what you're doing.


File Uploads

Tabella H-6. File Uploads Configuration Options

NameDefaultChangeable
file_uploads"1"PHP_INI_SYSTEM
upload_tmp_dirNULLPHP_INI_SYSTEM
upload_max_filesize"2M"PHP_INI_SYSTEM|PHP_INI_PERDIR

Breve descrizione dei parametri di configurazione.

file_uploads boolean

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

upload_max_filesize integer

The maximum size of an uploaded file.


General SQL

Tabella H-7. General SQL Configuration Options

NameDefaultChangeable
sql.safe_mode"0"PHP_INI_SYSTEM

Breve descrizione dei parametri di configurazione.

sql.safe_mode boolean


Debugger Configuration Directives

Attenzione

Only PHP 3 implements a default debugger, for more information see Appendice E.

debugger.host string

DNS name or IP address of host used by the debugger.

debugger.port string

Port number used by the debugger.

debugger.enabled boolean

Whether the debugger is enabled.


Appendice I. Lista dei sinonimi delle funzioni PHP

Questa è la lista degli alias ovvero dei sinonimi delle funzioni del PHP. Tutti i sinonimi sono qui elencati. É solitamente una cattiva idea utilizzare i 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.

Ciononostante, alcune funzioni hanno semplicemente due nomi, e non c'è una reale preferenza. (Per esempio, is_int() e is_integer() sono egualmente validi)

Quest'elenco è consistente con la versione 4.0.6 del PHP.

Tabella I-1. Sinonimi

Sinonimi (alias)Funzione MasterEstensione utilizzata
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_affected_rowsmsql_affected_rows()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
orbit_caught_exceptionsatellite_caught_exception()Satellite
orbit_exception_idsatellite_exception_id()Satellite
orbit_exception_valuesatellite_exception_value()Satellite
orbit_get_repository_idsatellite_get_repository_id()Satellite
orbit_load_idlsatellite_load_idl()Satellite
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)
swfbutton_keypressswfbutton_keypress()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
xpath_evalxpath_eval()DOM XML
xpath_eval_expressionxpath_eval_expression()DOM XML
xpath_initxpath_init()DOM XML
xpath_new_contextxpath_new_context()DOM XML
xptr_new_contextxpath_new_context()DOM XML


Appendice J. Parole riservate nel PHP

Questa è la lista delle parole riservate nel PHP, tipicamente costanti e delle variabili predefinite. In questa lista non sono elencate le funzioni, ma solo i costrutti del linguaggio. I nomi qui elencati non devono essere utilizzati come nomi di variabili, funzioni, costanti o metodi, ciò porterebbe inevitabilmente a creare confusioni.

and E_PARSE old_function
$argv E_ERROR or
as E_WARNING parent
$argc eval PHP_OS
break exit() $PHP_SELF
case extends PHP_VERSION
cfunction FALSE print()
class for require()
continue foreach require_once()
declare function return()
default $HTTP_COOKIE_VARS static
do $HTTP_GET_VARS switch
die() $HTTP_POST_VARS stdClass
echo() $HTTP_POST_FILES $this
else $HTTP_ENV_VARS TRUE
elseif $HTTP_SERVER_VARS var
empty() if xor
enddeclare include() virtual()
endfor include_once() while
endforeach global __FILE__
endif list() __LINE__
endswitch new __sleep
endwhile not __wakeup
E_ALL NULL  


Appendice K. 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 K-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_init() curl_init(), curl_exec() curl_close() Curl session
dbm dbmopen() dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() dbmclose() Link to DBM database
dba dba_open() dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() dba_close() Link to DBA database
dba persistent dba_popen() dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() None Persistent link to DBA database
dbase dbase_open() dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() dbase_close() Link to Dbase database
dbx_link_object dbx_connect() dbx_query() dbx_close() dbx connection
dbx_result_object dbx_query()   None dbx result
domxml attribute    
domxml document    
domxml node    
xpath context    
xpath object    
fbsql database fbsql_select_db()   None fbsql database
fbsql link fbsql_change_user(), fbsql_connect() fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() fbsql_close() Link to fbsql database
fbsql plink fbsql_change_user(), fbsql_pconnect() fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() None Persistent link to fbsql database
fbsql result fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() fbsql_free_result() fbsql result
fdf fdf_open() fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() fdf_close() FDF File
ftp ftp_connect() ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site() ftp_quit() FTP stream
gd imagecreate(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness() imagedestroy() GD Image
gd font imageloadfont() imagechar(), imagecharup(), imagefontheight() None Font for GD
gd PS encoding    
gd PS font imagepsloadfont() imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() imagepsfreefont() PS font for GD
GMP integer gmp_init() gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() None GMP Number
hyperwave document hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() hw_deleteobject() Hyperwave object
hyperwave link hw_connect() hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() hw_close(), hw_free_document() Link to Hyperwave server
hyperwave link persistent hw_pconnect() hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() None Persistent link to Hyperwave server
icap icap_open() icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() icap_close() Link to icap server
imap imap_open() imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() imap_close() Link to IMAP, POP3 server
imap chain persistent    
imap persistent    
ingres ingres_connect() ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() ingres_close() Link to ingresII base
ingres persistent ingres_pconnect() ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() None Persistent link to ingresII base
interbase blob    
interbase link ibase_connect() ibase_query(), ibase_prepare(), ibase_trans() ibase_close() Link to Interbase database
interbase link persistent ibase_pconnect() ibase_query(), ibase_prepare(), ibase_trans() None Persistent link to Interbase database
interbase query ibase_prepare() ibase_execute() ibase_free_query() Interbase query
interbase result ibase_query() ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() ibase_free_result() Interbase Result
interbase transaction ibase_trans() ibase_commit() ibase_rollback() Interbase transaction
java    
ldap link ldap_connect(), ldap_search() ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() ldap_close() ldap connection
ldap result ldap_read() ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() ldap_free_result() ldap search result
ldap result entry    
mcal mcal_open(), mcal_popen() mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() mcal_close() Link to calendar server
SWFAction    
SWFBitmap    
SWFButton    
SWFDisplayItem    
SWFFill    
SWFFont    
SWFGradient    
SWFMorph    
SWFMovie    
SWFShape    
SWFSprite    
SWFText    
SWFTextField    
mnogosearch agent    
mnogosearch result    
msql link msql_connect() msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() msql_close() Link to mSQL database
msql link persistent msql_pconnect() msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() None Persistent link to mSQL
msql query msql_query() msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_fieldname(), msql_field_seek(), msql_fieldtable(), msql_fieldtype(), msql_fieldflags(), msql_fieldlen(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() msql_free_result(), msql_free_result() mSQL result
mssql link mssql_connect() mssql_query(), mssql_select_db() mssql_close() Link to Microsft SQL Server database
mssql link persistent mssql_pconnect() mssql_query(), mssql_select_db() None Persistent link to Microsft SQL Server
mssql result mssql_query() mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() mssql_free_result() Microsft SQL Server result
mysql link mysql_connect() mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() mysql_close() Link to MySQL database
mysql link persistent mysql_pconnect() mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() None Persistent link to MySQL database
mysql result mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query() mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() mysql_free_result() MySQL result
oci8 collection    
oci8 connection ocilogon(), ociplogon(), ocinlogon() ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() ocilogoff() Link to Oracle database
oci8 descriptor    
oci8 server    
oci8 session    
oci8 statement ocinewdescriptor() ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() ocifreestatement() Oracle Cursor
odbc link odbc_connect() odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() odbc_close() Link to ODBC database
odbc link persistent odbc_connect() odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() None Persistent link to ODBC database
odbc result odbc_prepare() odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() odbc_free_result() ODBC result
birdstep link    
birdstep result    
OpenSSL key openssl_get_privatekey(), openssl_get_publickey() openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() openssl_free_key() OpenSSL key
OpenSSL X.509 openssl_x509_read() openssl_x509_parse(), openssl_x509_checkpurpose() openssl_x509_free() Public Key
oracle Cursor ora_open() ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() ora_close() Oracle cursor
oracle link ora_logon() ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() ora_logoff() Link to oracle database
oracle link persistent ora_plogon() ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() None Persistent link to oracle database
pdf document pdf_new() pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_open_memory_image() pdf_close(), pdf_delete() PDF document
pdf image pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() pdf_close_image() Image in PDF file
pdf object    
pdf outline    
pgsql large object pg_lo_open() pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() pg_lo_close() PostgreSQL Large Object
pgsql link pg_connect() pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() pg_close() Link to PostgreSQL database
pgsql link persistent pg_pconnect() pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() None Persistent link to PostgreSQL database
pgsql result pg_query(), pg_get_result() pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() pg_free_result() PostgreSQL result
pgsql string    
printer    
printer brush    
printer font    
printer pen    
pspell pspell_new(), pspell_new_config(), pspell_new_personal() pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() None pspell dictionary
pspell config pspell_config_create() pspell_new_config() None pspell configuration
Sablotron XSLT xslt_create() xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() xslt_free() XSLT parser
shmop shmop_open() shmop_read(), shmop_write(), shmop_size(), shmop_delete() shmop_close()  
sockets file descriptor set socket() accept_connect(), bind(), connect(), listen(), read(), write() close() Socket
sockets i/o vector    
dir dir() readdir(), rewinddir() closedir() Dir handle
file fopen() feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() fclose() File handle
pipe popen() feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() pclose() Process handle
socket fsockopen() fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() fclose() Socket handle
stream    
sybase-db link sybase_connect() sybase_query(), sybase_select_db() sybase_close() Link to Sybase database using DB library
sybase-db link persistent sybase_pconnect() sybase_query(), sybase_select_db() None Persistent link to Sybase database using DB library
sybase-db result sybase_query() sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() sybase_free_result() Sybase result using DB library
sybase-ct link sybase_connect() sybase_affected_rows(), sybase_query(), sybase_select_db() sybase_close() Link to Sybase database using CT library
sybase-ct link persistent sybase_pconnect() sybase_affected_rows(), sybase_query(), sybase_select_db() None Persistent link to Sybase database using CT library
sybase-ct result sybase_query() sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() sybase_free_result() Sybase result using CT library
sysvsem sem_get() sem_acquire() sem_release() System V Semaphore
sysvshm shm_attach() shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() shm_detach() System V Shared Memory
wddx wddx_packet_start() wddx_add_vars() wddx_packet_end() WDDX packet
xml xml_parser_create() xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() xml_parser_free() XML parser
zlib gzopen() gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() gzclose() gz-compressed file


Appendice L. 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 L-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


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

Alcuni webserver non standard, tipo IIS, possono inviare dati in maniera tale da fare generare un warning al PHP. Quando si utilizza tali server si dovrebbe abbassare il livello del error_reporting in modo da non includere i warning.

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() */
foreach(stream_get_meta_data($fp) as $response) {

  /* Were we redirected? */
  if (substr(strtolower($response), 0, 10) == 'location: ') {
    /* update $url with where we were redirected to */
    $url = substr($response, 10);
  }

}

?>

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 L-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 L-3. Context options (as of PHP 5.0.0)

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

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 L-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 filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only.
Supports unlink()NoYes
Supports rename()NoYes
Supports mkdir()NoYes
Supports rmdir()NoYes

Tabella L-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)

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://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_set_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 L-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 L-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


Appendice M. 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 buffer making the fact that is 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 M-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 M-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 M-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 M-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 M-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 M-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 la Sezione Compression Streams nell'Appendice L provide a way of creating gzip and bz2 compatable 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).

Nota: The zlib.* filters are not currently built into the PHP core. To enable these filters in PHP 5, install the zlib_filter package from PECL. These filters are not available for PHP 4.

Esempio M-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 M-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 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.

Nota: The bzip2.* filters are not currently built into the PHP core. To enable these filters in PHP 5, install the bz2_filter package from PECL. These filters are not available for PHP 4.

Esempio M-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.

 */
?>

Appendice N. 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

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

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

Tabella N-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 O. 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 O-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 O-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 O-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 P. 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 P-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_CLOSE_TAG?> or %> 
T_COMMENT// or #comments
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_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_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_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
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::::
T_PLUS_EQUAL+=assignment operators
T_PRINTprint()print()
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 Q. 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 su http://www.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.

Un vantaggio del manuale online sulla maggior parte dei formati offline è l'integrazione dei contributi degli utenti 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.

I formati più adatti a diversi tipi di sistemi operativi sono l'HTML e il testo semplice. Il formato HTML è disponibile sia come unica pagina HTML, sia come pacchetto di file univoci per ogni sezione (cioè qualche migliaio di file). I formati HTML e testo semplice sono disponibili come file TAR compressi usando il programma Bzip2.

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.

I formati Palm ed iSilo sono ideali per chi ha computer portatili compatibili Palm. Puoi portare il tuo portatile con te per lavoro ed usare un lettore DOC o iSilo per controllare le tue conoscenze di PHP, o solo per avere un riferimento rapido.

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.

Nota: Un progetto in Visual Basic per Linux è in fase di lavorazione, ed includerà lo sviluppo di un programma per creare e leggere file CHM per Linux. Guarda anche questa pagina di SourceForge.net se sei interessato ai progressi del progetto.


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


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 a http://www.php.net/support.php. Inoltre, su http://www.php.net/links.php troverai un elenco di siti dedicati al PHP con articoli, forum di discussione e numerosi script.


Come aiutare a migliorare la documentazione

Ci sono due 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.


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 il testo semplice, l'HTML, il PDF, il PalmPilot DOC, il PalmPilot iSilo e l'HTML Help per Windows da http://www.php.net/docs.php. I manuali sono aggiornati automaticamente quando il loro contenuto viene aggiornato.

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.


Appendice R. 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 S. Indice delle Funzioni


Indice delle Funzioni


C

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()
clearstatcache()
closedir()
closelog()
collection->append()
collection->assign()
collection->assignelem()
collection->free()
collection->getelem()
collection->max()
collection->size()
collection->trim()
com()
com_addref()
com_get()
com_invoke()
com_isenum()
com_load()
com_load_typelib()
com_propget()
com_propput()
com_propset()
com_release()
com_set()
compact()
connection_aborted()
connection_status()
connection_timeout()
constant()
convert_cyr_string()
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_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()
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()
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::fileatime()
directoryiterator::filectime()
directoryiterator::filegroup()
directoryiterator::fileinode()
directoryiterator::filemtime()
directoryiterator::fileowner()
directoryiterator::fileperms()
directoryiterator::filesize()
directoryiterator::filetype()
directoryiterator::getfilename()
directoryiterator::getpath()
directoryiterator::getpathname()
directoryiterator::hasmore()
directoryiterator::isdir()
directoryiterator::isdot()
directoryiterator::isexecutable()
directoryiterator::isfile()
directoryiterator::islink()
directoryiterator::isreadable()
directoryiterator::iswritable()
directoryiterator::key()
directoryiterator::next()
directoryiterator::rewind()
dirname()
disk_free_space()
disk_total_space()
diskfreespace()
dl()
dngettext()
dns_check_record()
dns_get_mx()
dns_get_record()
domattribute->name()
domattribute->specified()
domattribute->value()
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->doctype()
domdocument->document_element()
domdocument->dump_file()
domdocument->dump_mem()
domdocument->get_element_by_id()
domdocument->get_elements_by_tagname()
domdocument->html_dump_mem()
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->has_attribute()
domelement->remove_attribute()
domelement->set_attribute()
domelement->tagname()
domnode->add_namespace()
domnode->append_child()
domnode->append_sibling()
domnode->attributes()
domnode->child_nodes()
domnode->clone_node()
domnode->dump_node()
domnode->first_child()
domnode->get_content()
domnode->has_attributes()
domnode->has_child_nodes()
domnode->insert_before()
domnode->is_blank_node()
domnode->last_child()
domnode->next_sibling()
domnode->node_name()
domnode->node_type()
domnode->node_value()
domnode->owner_document()
domnode->parent_node()
domnode->prefix()
domnode->previous_sibling()
domnode->remove_child()
domnode->replace_child()
domnode->replace_node()
domnode->set_content()
domnode->set_name()
domnode->set_namespace()
domnode->unlink_node()
domprocessinginstruction->data()
domprocessinginstruction->target()
domxml_new_doc()
domxml_open_file()
domxml_open_mem()
domxml_version()
domxml_xmltree()
domxml_xslt_stylesheet()
domxml_xslt_stylesheet_doc()
domxml_xslt_stylesheet_file()
domxsltstylesheet->process()
domxsltstylesheet->result_dump_file()
domxsltstylesheet->result_dump_mem()
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_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()
floatval()
flock()
floor()
flush()
fmod()
fnmatch()
fopen()
fpassthru()
fprintf()
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->dstofsrcanchors()
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->setcommitedversion()
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()
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_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()
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()
intval()
ip2long()
iptcembed()
iptcparse()
ircg_channel_mode()
ircg_disconnect()
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_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()

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_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()
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_getdata()
msession_inc()
msession_list()
msession_listvar()
msession_lock()
msession_plugin()
msession_randstr()
msession_set()
msession_set_array()
msession_setdata()
msession_timeout()
msession_uniq()
msession_unlock()
msg_get_queue()
msg_receive()
msg_remove_queue()
msg_send()
msg_set_queue()
msg_stat_queue()
msql()
msql()
msql_affected_rows()
msql_close()
msql_connect()
msql_create_db()
msql_createdb()
msql_data_seek()
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_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-init()
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_num_rows()
mysqli_stmt_param_count()
mysqli_stmt_prepare()
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_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()
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()
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()
parse_ini_file()
parse_str()
parse_url()
passthru()
pathinfo()
pattern modifiers()
pattern syntax()
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()
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_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()
php_ini_scanned_files()
php_logo_guid()
php_sapi_name()
php_uname()
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_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()

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_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_element->asxml()
simplexml_element->attributes()
simplexml_element->children()
simplexml_element->xpath()
simplexml_import_dom()
simplexml_load_file()
simplexml_load_string()
simplexmliterator::current()
simplexmliterator::getchildren()
simplexmliterator::haschildren()
simplexmliterator::key()
simplexmliterator::next()
simplexmliterator::rewind()
simplexmliterator::valid()
sin()
sinh()
sizeof()
sleep()
snmp_get_quick_print()
snmp_set_quick_print()
snmpget()
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_iovec_add()
socket_iovec_alloc()
socket_iovec_delete()
socket_iovec_fetch()
socket_iovec_free()
socket_iovec_set()
socket_last_error()
socket_listen()
socket_read()
socket_readv()
socket_recv()
socket_recvfrom()
socket_recvmsg()
socket_select()
socket_send()
socket_sendmsg()
socket_sendto()
socket_set_block()
socket_set_blocking()
socket_set_nonblock()
socket_set_option()
socket_set_timeout()
socket_shutdown()
socket_strerror()
socket_write()
socket_writev()
sort()
soundex()
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_fetch_array()
sqlite_fetch_single()
sqlite_fetch_string()
sqlite_field_name()
sqlite_has_more()
sqlite_last_error()
sqlite_last_insert_rowid()
sqlite_libencoding()
sqlite_libversion()
sqlite_next()
sqlite_num_fields()
sqlite_num_rows()
sqlite_open()
sqlite_popen()
sqlite_query()
sqlite_rewind()
sqlite_seek()
sqlite_udf_decode_binary()
sqlite_udf_encode_binary()
sqlite_unbuffered_query()
sqrt()
srand()
sscanf()
stat()
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_options()
stream_context_set_option()
stream_context_set_params()
stream_copy_to_stream()
stream_filter_append()
stream_filter_prepend()
stream_filter_register()
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_get_name()
stream_socket_recvfrom()
stream_socket_sendto()
stream_socket_server()
stream_wrapper_register()
strftime()
strip_tags()
stripcslashes()
stripos()
stripslashes()
stristr()
strlen()
strnatcasecmp()
strnatcmp()
strncasecmp()
strncmp()
strpos()
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

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_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_create()
xslt_errno()
xslt_error()
xslt_free()
xslt_process()
xslt_set_base()
xslt_set_encoding()
xslt_set_error_handler()
xslt_set_log()
xslt_set_sax_handler()
xslt_set_sax_handlers()
xslt_set_scheme_handler()
xslt_set_scheme_handlers()